Skip to content

Instantly share code, notes, and snippets.

@man4toman
Last active October 4, 2018 11:40
Show Gist options
  • Save man4toman/eff893e5974cf6a62f90a45896c589c2 to your computer and use it in GitHub Desktop.
Save man4toman/eff893e5974cf6a62f90a45896c589c2 to your computer and use it in GitHub Desktop.
Check file exists from url
<?php
/*
* Method 1: use curl, it must return 200 for http return code
*/
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if( $httpCode == 200 ){ echo "File exists"; }
/*
* Method 2: use get_headers
*/
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false ) {
echo 'File does NOT exist';
}else {
echo 'File exists';
}
/*
* Method 3: use fopen
*/
$file_exists = (@fopen($url, "r")) ? true : false;
/*
* Method 4: use getimagesize
*/
$imageArray = getimagesize($url);
if($imageArray[0]){
echo "File exists";
//print_r($imageArray);
}
else{
echo "File does NOT exist";
}
/*
* Method 5: use getimagesize
*/
if (false === file_get_contents($url,0,null,0,1)) {
$image = $default_image;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment