Validate a file at a given Path or URL

Posted by & filed under PHP.

This class is useful for verifying an uploaded file to tell you the file type and whether or not the file can be opened.

Usage would be:

$f = new validateURI('[path or URL]');
print_r($f->uriInfo);

Here is the class…

<?php
class validateURI {

    public $uriInfo;

    function __construct($uri = null) {

	if (is_null($uri)){
	    return false;
	}
	
	$this->uriInfo = array(
	    'errors' => array(),
	    'validURI' => 0,
	    'uri' => $uri
	);

	// get an array of loaded PHP extensions
	$exts = get_loaded_extensions();

	// find the filetype - try SPL first.
	if (in_array('SPL', $exts)) {
	    $info = new SplFileInfo($uri);
	    $this->uriInfo['fileType'] = $info->getExtension();
	    $this->uriInfo['fileType_method'] = 'SplFileInfo';
	} else {
	    $this->uriInfo['filetype'] = substr($uri, strrpos($uri, '.') + 1);
	    $this->uriInfo['fileType_method'] = 'substring';
	}

	// Use cURL or fopen (if ini allow_url_fopen) to test absolute URLs
	if (parse_url($uri, PHP_URL_SCHEME) != '') {
	    $this->uriInfo['uri_type'] = 'URL';
	    if (in_array('curl', $exts)) {
		$this->uriInfo['method'] = 'cURL';
		// urlencode breaks the path on my local windows machine!
		if ($_SERVER['SERVER_ADDR']!='127.0.0.1'){
		    $uri = urlencode($uri);
		}
		$ch = curl_init($uri);
		if ($ch === false) {
		    $this->uriInfo['errors'][] = 'curl_init failed';
		} else {
		    curl_setopt($ch, CURLOPT_NOBODY, true);
		    curl_exec($ch);
		    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		    $this->uriInfo['contentType'] = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
		    // $retcode > 400 -> not found, $retcode = 200, found.
		    //echo curl_error($ch);exit;
		    curl_close($ch);
		    $this->uriInfo['cURL_retcode'] = $retcode;
		    if ($retcode > 199 && $retcode < 400) {
			$this->uriInfo['validURI'] = 1;
		    }
		}
	    } elseif (ini_get('allow_url_fopen')) {
		$this->uriInfo['method'] = 'url_fopen';
		if (fopen($uri, "r") !== false) {
		    $this->uriInfo['validURI'] = 1;
		} else {
		    $this->uriInfo['errors'][] = 'url_fopen failed';
		}
	    }
	} else {
	    $this->uriInfo['uri_type'] = 'unknown';
	    $this->uriInfo['method'] = 'local fopen';
	    // test paths/relative URLs
	    if (fopen($uri, "r") !== false) {
		$this->uriInfo['uri_type'] = 'valid path';
		$this->uriInfo['validURI'] = 1;
	    }
	}
    }
}
?>

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Bitnami