Checking if file exists - php

I have a piece of code that checks whether an image exists in the file system and if so, displays it.
if (file_exists(realpath(dirname(__FILE__) . $user_image))) {
echo '<img src="'.$user_image.'" />';
}
else {
echo "no image set";
}
If I echo $user_image out, copy and paste the link into the browser, the image is there.
However, here, the 'no image set' is always being reached.
The $user_image contents are http://localhost:8888/mvc/images/users/1.jpg
Some of these functions not needed?
Any ideas?
Broken code or a better way of doing it (that works!)?

Beside #hek2mgl answer which i think is correct, i also think you should switch to is_file() instead of file_exists().
Also, you can go a bit further like:
if(is_file(dirname(__FILE__). '/' . $user_image) && false !== #getimagesize(dirname(__FILE__) . '/'. $user_image)) {
// image is fine
} else {
// it isn't
}
L.E:1
Oh great, now you are telling us what $user_image contains? Couldn't you do it from the start, could you?
So you will have to:
$userImagePath = parse_url($user_image, PHP_URL_PATH);
$fullPath = dirname(__FILE__) . ' / ' . $userImagePath;
if($userImagePath && is_file($fullPath) && false !== #getimagesize($fullPath)) {
// is valid
}else {
// it isn't
}
L.E: 2
Also, storing the entire url is not a good practice, what happens when you switch domain names? Try to store only the relative path, like /blah/images/image.png instead of http://locathost/blah/images/image.png

You missed the directory separator / between path and filename. Add it:
if (file_exists(realpath(dirname(__FILE__) . '/' . $user_image))) {
Note that dirname() will return the directory without a / at the end.

Related

PHP file_exists does not work. It seems to be reversing true and false

While working on my photo gallery I decided it was best to have an alternate file if image that should display doesn't. I've looked on this site, and may others. They all say to use:
$VariableName = "photography/small/2014-09-21-red-1.png";
if (file_exists ($VariableName)) {echo "Yes!!!";}
else {echo "Nooo!!!";}
or
if (file_exists ("photography/small/2014-09-21-red-1.png")) {echo "Yes!!!";}
else {echo "Nooo!!!";}
For some reason, this will not work for me. It does work, but only when file_exists is set to !file_exists, which is saying: "if this file does not exist, display the image that exists (the image I want, not it's replacement)". In other words:
this is saying if apple exists, display "orange"; and if apple does not exist, display apple.
I've even placed the generated image link in the search bar (when using !file_exists), and after pressing enter, it brings me to the image. I've made sure that the images are set to 0777 in case that's interfering, but it seems to have no effect. All of the $DataRows variables are connected to a database and I've triple-checked that the file names in photography/small match those in the database table.
Why is this happening?
$URLPath = "http://localhost/~matthew/";
if (file_exists ($URLPath . "photography/small/" . $DataRows["DatePublished"] . "-" . $DataRows["FileName"] . "." . $DataRows["ImageExtension"])) {
echo '<img src="' . $URLPath . "photography/small/" . $DataRows["DatePublished"] . "-" . $DataRows["FileName"] . "." . $DataRows["ImageExtension"] . '" alt="' . $DataRows["PhotoName"] . '">' . "\n";
}
else {
echo '<img src="' . $URLPath . 'img/no-image.png" alt="Image Not Here">' . "\n";
}
Thank you very much for the help.
What happens if you change $URLPath from
$URLPath = "http://localhost/~matthew/";
to
$URLPath = $_SERVER['DOCUMENT_ROOT'] . "/~matthew/";
It looks like you are checking for a file but passing a URL into the function. It is probably returning false since the URL is not a valid path on your server. I would suggest using the actual path of the file or if you have to use a URL check out this post: How to check if a file exists from a url
Try using clearstatcache() and double check the file names and paths.
if (file_exists ($VariableName or "path-to-image")) {
This is gibberish. As long as "path-to-image" is not null, the operand will evaluate as (bool) true.
It should be:
if (file_exists ($VariableName)) {
It looks like you should be using
If(is_readable($variable)) {
But looking at your later code you are not using the construct you originally quoted.
file_exists() works as described for me in lots of different contexts.

file_exists() not working codeigniter

I am working with codeigniter. I want to display images but if some image is not exist it should show image-not-found-medium.jpg which is dummy image..
below is my code
<?php
$image_path_medium = site_url('assets/images-products/medium');
$image_not_found_medium = $image_path_medium . "/" . "image-not-found-medium.jpg";
$image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";
if (file_exists($image_name_with_path)) {
echo $image_name_with_path;
} else {
echo $image_not_found_medium;
}
?>
but it always shows $image_not_found_medium i think there is problem with my if condition.
Please help.
<?php
$image_path_medium = site_url('assets/images-products/medium');
$image_not_found_medium = $image_path_medium . "/" . "image-not-found-medium.jpg";
$image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your image url
$image_file_path=FCPATH.'assets/images-products/medium'. $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your file path
if (file_exists($image_file_path)) //file_exists of a url returns false.It should be real file path
{
echo $image_name_with_path;
}
else
{
echo $image_not_found_medium;
}
?>
You are using absolute path for file existence which is wrong. You have to use real path because the file_exists() function checks whether or not a file or directory exists on the current server.
If your assets folder is placed in root then just use getcwd() - Gets the current working directory as
$image_path_medium = getcwd().'assets/images-products/medium';
Otherwise give the proper path to the assets folder like
$image_path_medium = getcwd().'application/views/assets/images-products/medium';
Instead of file_exists() prefer is_file() when checking files, as file_exists() returns true on directories. In addition, you might want to see if getimagesize() returns FALSE to make sure you have an image.
Use like this.
$g = base_url().'upload/image.jpg';
if(file_exists($g) !== null){//your code..}
This is works for me in CI.

File exists issues

I'm attempting to try and debug the following code with the file_exists function. I've ran a var_dump on the avatar directory and it always returns as bool(false). I'm not sure why. I tested the code below and it gets to the file exists but it proves the if statement false everytime. Any thoughts? I have looked and the image is in the directory correctly.
$default_avatar = 'default.jpg';
$avatar_directory = base_url() . 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists($avatar))
{
$user_data->avatar = $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
$default_avatar = 'default.jpg';
$avatar_directory = 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists(FCPATH . $avatar))
{
$user_data->avatar = base_url() . $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = base_url() . $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
from the name base_url seems like a function that will get a url like http://www.mysite.com, which will not work for doing local directory functions.
you need something like getcwd, or a full path
getcwd will get the current working directory (the directory where the initial script was executed from):
//If say script.php was exectued from /home/mysite/www
$avatar_directory = getcwd() . '/assets/globals/images/avatars/';
//$avatar_directory would be
/home/mysite/www/assets/globals/images/avatars/
Well this works both CLI and via Apache etc...:
$avatar_directory = substr(str_replace(pathinfo(__FILE__, PATHINFO_BASENAME), '', __FILE__), 0, -1) . '/assets/globals/images/avatars/'
The did returned is the one that the php file itself is in, not the root.
assuming you meant base_url() to point to the root of your project -
$file = __DIR__ . "/path/to/file.ext";
if (file_exists($file)) {
//...
}
Or some variation thereof. This also works:
__DIR__ . "/.."
it resolves to the parent directory of __DIR__.
see PHP's magic constants:
http://php.net/manual/en/language.constants.predefined.php
If you are looking for a remote resource - a file not located on your local filesystem - you have to change your php.ini to permit that. And it's probably not a good idea, this is not usually considered safe or secure. At all.
http://php.net/manual/en/features.remote-files.php
And note:
"This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir."
-- from http://php.net/manual/en/function.file-exists.php
-- edited to add relevant information based on a comment from OP.

PHP Including a file based on pathinfo - security concern?

I am redirecting all page requests through a file called index.php which looks at the URL the visitor requested and sees if there is a template file to match.
For example, http://www.website.com/contact will actually route to the index.php script and should check to see if the file /var/html/template/contact.tpl exists and include it if it does.
My concern is with regards to security and null characters, extra dots and slashes, etc. Does any kind of filter need applying to the code below or is the use of pathinfo and the directory prefix enough? Obviously I don't want anyone to be able to maliciously include files outside of the designated template directory.
<?php
define ('TEMPLATES', '/var/html/templates');
$page = pathinfo ($_SERVER['REQUEST_URI'], PATHINFO_FILENAME);
if (file_exists (TEMPLATES . '/' . $page . '.tpl')) {
include (TEMPLATES . '/' . $page . '.tpl');
} else {
header ('HTTP/1.0 404 Not Found');
echo 'Sorry page not found';
}
?>
To be 100% safe, make a list of allowed pages and check that it's in that array before returning the page.
You could even try a php glob() e.g..
define ('TEMPLATES', '/var/html/templates/');
$page = TEMPLATES . pathinfo($_SERVER['REQUEST_URI'], PATHINFO_FILENAME) . '.tpl';
if (in_array($page, glob(TEMPLATES . '*.tpl'))) {
include ($page);
} else {
header ('HTTP/1.0 404 Not Found');
echo 'Sorry page not found';
}
This will validate that it's in that folder and that the extension is '.tpl'
Sorry - just edited to make glob() behaviour correct.

Trouble getting PHP file_exists to work

I'm trying to get a thumbnail to link to a PDF of the same name if the PDF exists, but to not link to anything if the PDF doesn't exist. Here's the code I have:
<?php
if ( function_exists('has_post_thumbnail') && has_post_thumbnail() ) {
$full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full') ;
$pdf = substr_replace($full_image_url , 'pdf', strrpos($full_image_url[0] , '.') +1);
$filename = $pdf[0];
if (file_exists($filename)) {
echo '<a href="' . $pdf[0] . '" title="' . the_title_attribute('echo=0') . '" . target="_blank" >';
the_post_thumbnail('Full Size');
echo '</a>';
}
else {
echo "The file $filename exists";
}
}
?>
Currently, the else statement is just to prove whether or not it's finding the file. Which it seems to, as it displays The file http://localhost/AWAD/wp-content/uploads/2012/03/+D.pdf exists. And if I get rid of the conditional, the post thumbnail displays with a link to the PDF. I just can't get the conditional to work.
Can anyone spot why it's not working?
You should pass a path on your FS to file_exists, you are passing an URL now
I'm pretty sure file_exists wants a full file path, not a URL. So, you'll probably want to use the WordPress wp_uploads_dir function to get the base path to your uploads directory and then append the rest of the path to the end of that and then pass that string to file_exists. Hopefully that makes sense.

Categories