PHP: How to check if image file exists? - php

I need to see if a specific image exists on my cdn.
I've tried the following and it doesn't work:
if (file_exists(http://www.example.com/images/$filename)) {
echo "The file exists";
} else {
echo "The file does not exist";
}
Even if the image exists or doesn't exist, it always says "The file exists". I'm not sure why its not working...

You need the filename in quotation marks at least (as string):
if (file_exists('http://www.mydomain.com/images/'.$filename)) {
… }
Also, make sure $filename is properly validated. And then, it will only work when allow_url_fopen is activated in your PHP config

if (file_exists('http://www.mydomain.com/images/'.$filename)) {}
This didn't work for me. The way I did it was using getimagesize.
$src = 'http://www.mydomain.com/images/'.$filename;
if (#getimagesize($src)) {
Note that the '#' will mean that if the image does not exist (in which case the function would usually throw an error: getimagesize(http://www.mydomain.com/images/filename.png) [function.getimagesize]: failed) it will return false.

Try like this:
$file = '/path/to/foo.txt'; // 'images/'.$file (physical path)
if (file_exists($file)) {
echo "The file $file exists";
} else {
echo "The file $file does not exist";
}

Well, file_exists does not say if a file exists, it says if a path exists. ⚡⚡⚡⚡⚡⚡⚡
So, to check if it is a file then you should use is_file together with file_exists to know if there is really a file behind the path, otherwise file_exists will return true for any existing path.
Here is the function i use :
function fileExists($filePath)
{
return is_file($filePath) && file_exists($filePath);
}

Here is the simplest way to check if a file exist:
if(is_file($filename)){
return true; //the file exist
}else{
return false; //the file does not exist
}

A thing you have to understand first: you have no files.
A file is a subject of a filesystem, but you are making your request using HTTP protocol which supports no files but URLs.
So, you have to request an unexisting file using your browser and see the response code. if it's not 404, you are unable to use any wrappers to see if a file exists and you have to request your cdn using some other protocol, FTP for example

If the file is on your local domain, you don't need to put the full URL. Only the path to the file. If the file is in a different directory, then you need to preface the path with "."
$file = './images/image.jpg';
if (file_exists($file)) {}
Often times the "." is left off which will cause the file to be shown as not existing, when it in fact does.

public static function is_file_url_exists($url) {
if (#file_get_contents($url, 0, NULL, 0, 1)) {
return 1;
}
return 0;
}

There is a major difference between is_file and file_exists.
is_file returns true for (regular) files:
Returns TRUE if the filename exists and is a regular file, FALSE otherwise.
file_exists returns true for both files and directories:
Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
Note: Check also this stackoverflow question for more information on this topic.

You have to use absolute path to see if the file exists.
$abs_path = '/var/www/example.com/public_html/images/';
$file_url = 'http://www.example.com/images/' . $filename;
if (file_exists($abs_path . $filename)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
If you are writing for CMS or PHP framework then as far as I know all of them have defined constant for document root path.
e.g WordPress uses ABSPATH which can be used globally for working with files on the server using your code as well as site url.
Wordpress example:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
if (file_exists($image_path)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
I'm going an extra mile here :). Because this code would no need much maintenance and pretty solid, I would write it with as shorthand if statement:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
echo (file_exists($image_path))?'The file exists. URL:' . $file_url:'The file does not exist';
Shorthand IF statement explained:
$stringVariable = ($trueOrFalseComaprison > 0)?'String if true':'String if false';

you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.
Here is example:
function remoteFileExists($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
echo 'file exists';
} else {
echo 'file does not exist';
}

You can use the file_get_contents function to access remote files. See http://php.net/manual/en/function.file-get-contents.php for details.

If you are using curl, you can try the following script:
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
Reference URL: https://hungred.com/how-to/php-check-remote-email-url-image-link-exist/

try this :
if (file_exists(FCPATH . 'uploads/pages/' . $image)) {
unlink(FCPATH . 'uploads/pages/' . $image);
}

If path to your image is relative to the application root it is better to use something like this:
function imgExists($path) {
$serverPath = $_SERVER['DOCUMENT_ROOT'] . $path;
return is_file($serverPath)
&& file_exists($serverPath);
}
Usage example for this function:
$path = '/tmp/teacher_photos/1546595125-IMG_14112018_160116_0.png';
$exists = imgExists($path);
if ($exists) {
var_dump('Image exists. Do something...');
}
I think it is good idea to create something like library to check image existence applicable for different situations. Above lots of great answers you can use to solve this task.

Here is one function that I use to check any kind of URL. It will check response code is URL exists or not.
/*
* Check is URL exists
*
* #param $url Some URL
* #param $strict You can add it true to check only HTTP 200 Response code
* or you can add some custom response code like 302, 304 etc.
*
* #return string or NULL
*/
function is_url_exists($url, $strict = false)
{
if (is_int($strict) && $strict >= 100 && $strict < 600 || is_array($strict)) {
if(is_array($strict)) {
$response = $strict;
} else {
$response = [$strict];
}
} else if ($strict === true || $strict === 1) {
$response = [200];
} else {
$response = [200,202,301,302,303];
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
if (!curl_errno($ch) && $return !== false) {
return ( in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE), $response) !== false );
}
return false;
}
This is exactly what you need.

Read first 5 bytes form HTTP using fopen() and fread() then use this:
DEFINE("GIF_START","GIF");
DEFINE("PNG_START",pack("C",0x89)."PNG");
DEFINE("JPG_START",pack("CCCCCC",0xFF,0xD8,0xFF,0xE0,0x00,0x10));
to detect image.

file_exists reads not only files, but also paths. so when $filename is empty, the command would run as if it's written like this:
file_exists("http://www.example.com/images/")
if the directory /images/ exists, the function will still return true.
I usually write it like this:
// !empty($filename) is to prevent an error when the variable is not defined
if (!empty($filename) && file_exists("http://www.example.com/images/$filename"))
{
// do something
}
else
{
// do other things
}

file_exists($filepath) will return a true result for a directory and full filepath, so is not always a solution when a filename is not passed.
is_file($filepath) will only return true for fully filepaths

you need server path with file_exists
for example
if (file_exists('/httpdocs/images/'.$filename)) {echo 'File exist'; }

if(#getimagesize($image_path)){
...}
Is working for me.

Try it:
$imgFile = 'http://www.yourdomain.com/images/'.$fileName;
if (is_file($imgFile) && file_exists($imgFile)) {
echo 'File exists';
} else {
echo 'File not exist';
}
Another Way:
$imgFile = 'http://www.yourdomain.com/images/'.$fileName;
if (is_file($imgFile)) {.....
}

Related

file_exists not working with localhost URL

I have this piece of code in PHP:
if (file_exists($_POST['current_folder'])) {
//do something
}
But file_exists always returns false. The value passed to the function is:
echo $_POST['current_folder']); //This prints: http://localhost/wordpress/wp-content/music
I also tried with different folders on the localhost. The function always returns false.
I also tried is_dir(). But even this function returns false with the above URL.
There are many related questions on Stack Overflow. But most of them suggest that file_exists only works with relative URLs. But from this link it is clear that http:// URLs are also supported by the file_exists function.
What am I missing?
Use directory path; not web URL:
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
Tested under windows using Apache 2.4.9.
<?PHP
$crl = curl_init("http://localhost/symfony2/");
curl_setopt($crl, CURLOPT_NOBODY, true);
curl_exec($crl);
$ret = curl_getinfo($crl, CURLINFO_HTTP_CODE);
curl_close($crl);
if ($ret == 200)
echo 'File exists';
else
echo 'File does not exist';
?>
It works, just a note, it requires trailing slash for some reason.
Code 200 means OK (success).

Unable to copy image from URL in PHP with upload class

I'm trying to make a upload class with PHP. so this is my first PHP class:
//Create Class
class Upload{
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
if(copy($Content, '/test/sdfsdfd.jpg')){
return "UPLOADED";
}else{
return "ERROR";
}
}
}
and usage:
$Upload = new Upload();
echo $Upload->Remote('https://www.gstatic.com/webp/gallery/4.sm.jpg');
problem is, this class is not working. where is the problem? I'm new with PHP classes and trying to learn it.
thank you.
copy expects filesystem paths, e.g.
copy('/path/to/source', '/path/to/destination');
You're passing in the literal image you fetched, so it's going to be
copy('massive pile of binary garbage that will be treated as a filename', '/path/to/destination');
You want
file_put_contents('/test/sdfsdfg.jpg', $Content);
instead.
PHP's copy() function is used for copying files that you have permission to copy.
Since you're getting the contents of the file first, you could use fwrite().
<?php
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
// Create the file
if (!$fp = fopen('img.png', 'w')) {
echo "Failed to create image file.";
}
// Add the contents
if (fwrite($fp, $Content) === false) {
echo "Failed to write image file contents.";
}
fclose($fp);
}
Since you want to download a image, you could also use the imagejpeg-method of php to ensure you do not end up with any corrupted file format afterwards (http://de2.php.net/manual/en/function.imagejpeg.php):
download the target as "String"
create a image resource out of it.
save it as jpeg, using the proper method:
inside your method:
$content = file_get_contents($Image);
$img = imagecreatefromstring($content);
return imagejpeg($img, "Path/to/targetFile");
In order to have file_get_contents working correctly you need to ensure that allow_url_fopen is set to 1 in your php ini: http://php.net/manual/en/filesystem.configuration.php
Most managed hosters disable this by default. Either contact the support therefore or if they will not enable allow_url_fopen, you need to use another attempt, for example using cURL for file download. http://php.net/manual/en/book.curl.php
U can use the following snippet to check whether its enabled or not:
if ( ini_get('allow_url_fopen') ) {
echo "Enabled";
} else{
echo "Disabled";
}
What you describe is more download (to the server) then upload. stream_copy_to_stream.
class Remote
{
public static function download($in, $out)
{
$src = fopen($in, "r");
if (!$src) {
return 0;
}
$dest = fopen($out, "w");
if (!$dest) {
return 0;
}
$bytes = stream_copy_to_stream($src, $dest);
fclose($src); fclose($dest);
return $bytes;
}
}
$remote = 'https://www.gstatic.com/webp/gallery/4.sm.jpg';
$local = __DIR__ . '/test/sdfsdfd.jpg';
echo (Remote::download($remote, $local) > 0 ? "OK" : "ERROR");

php check if file exists on an external doman (accessing form a sub domain)

I have a website on http://www.reelfilmlocations.co.uk
The above site has an admin area where images are uploaded and different size copies created in subfolders of an uploads/images directory.
I am creating a site for mobile devices, which will operate on a sub-domain, but use the database and images from the main domain,
http://2012.reelfilmlocations.co.uk
I want to be able to access the images that are on the parent domain, which i can do by linking to the image with the full domain i.e http:www.reelfilmlocations.co.uk/images/minidisplay/myimage.jpg
Though i need to check if the image exists first...
I have a php function that checks if the images exists, if it does it returns the full url of the image.
If it doesn't exist i want to return the path of a placeholder image.
The following function i have, returns the correct image if it exists, but if it doesn't, it is just returning the path to the directory where the placeholder image resides i.e http://www.reelfilmlocations.co.uk/images/thumbs/. without the no-image.jpg bit.
The page in question is: http://2012.reelfilmlocations.co.uk/browse-unitbases/
the code i have on my page to get the image is:
<img src="<?php checkImageExists('/uploads/images/thumbs/', $row_rs_locations['image_ubs']);?>">
My php function:
if(!function_exists("checkImageExists")){
function checkImageExists($path, $file){
$imageName = "http://www.reelfilmlocations.co.uk".$path.$file;
$header_response = get_headers($imageName, 1);
if(strpos($header_response[0], "404" ) !== false ){
// NO FILE EXISTS
$imageName = "http://www.reelfilmlocations.co.uk".$path."no-image.jpg";
}else{
// FILE EXISTS!!
$imageName = "http://www.reelfilmlocations.co.uk".$path.$file;
}
echo($imageName);
}
}
Failing to get this to work i did some digging around and read some posts about curl:
This just returns a placeholder image everytime.
if(!function_exists("remoteFileExists")){
function remoteFileExists($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200 ) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
}
if(!function_exists("checkImageExists")){
function checkImageExists($path, $file){
$imageName = "http://www.reelfilmlocations.co.uk".$path.$file;
$exists = remoteFileExists($imageName);
if ($exists){
// file exists do nothing we already have the correct $imageName
} else {
// file does not exist so set our image to the placeholder
$imageName = "http://www.reelfilmlocations.co.uk".$path."no-image.jpg";
}
echo($imageName);
}
}
I dont know if it could be to do with getting a 403, or how to check if this is the case.
any pointers or things i could try woud be greatly appreciated.
I'd do it using CURL, issuing a HEAD request and checking the response code.
Not tested, but should do the trick:
$URL = 'sub.domain.com/image.jpg';
$res = `curl -s -o /dev/null -IL -w "%{http_code}" http://$URL`;
if ($res == '200')
echo 'Image exists';
The code above will populate $res with status code of the requisition (pay attention that I DON'T include the http:// prefix to the $URL variable because I do it in the command line.
Of course the same might be obtained using PHP's CURL functions, and the above call might not work on your server. I am just explaining what I'd be doing if I had the same need.

How to check if Image exists on server using URL

I am trying to check whether image file is exist on server Or not. I am getting image path with other server.
Please check below code which I've tried,
$urlCheck = getimagesize($resultUF['destination']);
if (!is_array($urlCheck)) {
$resultUF['destination'] = NULL;
}
But, it shows below warning
Warning: getimagesize(http://www.example.com/example.jpg) [function.getimagesize]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in
Is there any way to do so?
Thanks
$url = 'http://www.example.com/example.jpg)';
print_r(get_headers($url));
It will give an array. Now you can check the response to see if image exists or not
You need to check that the file is exist regularly on server or not.you should used:
is_file .For example
$url="http://www.example.com/example.jpg";
if(is_file($url))
{
echo "file exists on server";
}
else
{
echo "file not exists on server ";
}
Fastest & efficient Solution for broken or not found images link
i recommend you that don't use getimagesize() because it will 1st download image then it will check images size+if this will not image then it will throw exception so use below code
if(checkRemoteFile($imgurl))
{
//found url, its mean
echo "this is image";
}
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
Note:
this current code help you to identify broken or not found url image this will not help you to identify image type or headers
Use fopen function
if (#fopen($resultUF['destination'], "r")) {
echo "File Exist";
} else {
echo "File Not exist";
}
Issue is that the image may not exist or you don't have a direct permission for accessing the image, else you must be pointing an invalid location to the image.
you can use file_get_contents. This will cause php to issue a warning along side of returning false. You may need to handle such warning display to ensure the user interface doesn't get mixed up with it.
if (file_get_contents($url) === false) {
//image not foud
}

How do I check if a directory exists? "is_dir", "file_exists" or both?

I want to create a directory if it does not exist already.
Is using the is_dir function enough for that purpose?
if ( !is_dir( $dir ) ) {
mkdir( $dir );
}
Or should I combine is_dir with file_exists?
if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
mkdir( $dir );
}
Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.
$filename = "/folder/" . $dirname . "/";
if (file_exists($filename)) {
echo "The directory $dirname exists.";
} else {
mkdir("folder/" . $dirname, 0755);
echo "The directory $dirname was successfully created.";
exit;
}
I think realpath() may be the best way to validate if a path exist
http://www.php.net/realpath
Here is an example function:
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (long version)
* #param string $folder the path being checked.
* #return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
if($path !== false AND is_dir($path))
{
// Return canonicalized absolute pathname
return $path;
}
// Path/folder does not exist
return false;
}
Short version of the same function
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (sort version)
* #param string $folder the path being checked.
* #return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
Output examples
<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input); // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output); // bool(false)
/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input); // string(5) "/home"
var_dump($output); // string(5) "/home"
/** CASE 3 **/
$input = '/home/..';
var_dump($input); // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output); // string(1) "/"
Usage
<?php
$folder = '/foo/bar';
if(FALSE !== ($path = folder_exist($folder)))
{
die('Folder ' . $path . ' already exist');
}
mkdir($folder);
// Continue do stuff
Second variant in question post is not ok, because, if you already have file with the same name, but it is not a directory, !file_exists($dir) will return false, folder will not be created, so error "failed to open stream: No such file or directory" will be occured. In Windows there is a difference between 'file' and 'folder' types, so need to use file_exists() and is_dir() at the same time, for ex.:
if (file_exists('file')) {
if (!is_dir('file')) { //if file is already present, but it's not a dir
//do something with file - delete, rename, etc.
unlink('file'); //for example
mkdir('file', NEEDED_ACCESS_LEVEL);
}
} else { //no file exists with this name
mkdir('file', NEEDED_ACCESS_LEVEL);
}
I had the same doubt, but see the PHP docu:
https://www.php.net/manual/en/function.file-exists.php
https://www.php.net/manual/en/function.is-dir.php
You will see that is_dir() has both properties.
Return Values is_dir
Returns TRUE if the filename exists and is a directory, FALSE otherwise.
$year = date("Y");
$month = date("m");
$filename = "../".$year;
$filename2 = "../".$year."/".$month;
if(file_exists($filename)){
if(file_exists($filename2)==false){
mkdir($filename2,0777);
}
}else{
mkdir($filename,0777);
}
$save_folder = "some/path/" . date('dmy');
if (!file_exists($save_folder)) {
mkdir($save_folder, 0777);
}
This is an old, but still topical question. Just test with the is_dir() or file_exists() function for the presence of the . or .. file in the directory under test. Each directory must contain these files:
is_dir("path_to_directory/.");
Well instead of checking both, you could do if(stream_resolve_include_path($folder)!==false). It is slower but kills two birds in one shot.
Another option is to simply ignore the E_WARNING, not by using #mkdir(...); (because that would simply waive all possible warnings, not just the directory already exists one), but by registering a specific error handler before doing it:
namespace com\stackoverflow;
set_error_handler(function($errno, $errm) {
if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();
This is how I do
if(is_dir("./folder/test"))
{
echo "Exist";
}else{
echo "Not exist";
}
A way to check if a path is directory can be following:
function isDirectory($path) {
$all = #scandir($path);
return $all !== false;
}
NOTE: It will return false for non-existant path too, but works perfectly for UNIX/Windows
i think this is fast solution for dir check.
$path = realpath($Newfolder);
if (!empty($path)){
echo "1";
}else{
echo "0";
}

Categories