file_exists() not working codeigniter - php

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.

Related

how to grab the relative path of a file with php

i am trying to catch the relative path to a file to create a share link.
From my httpdocs folder on the webserver, my file is here:
jack/single/uploads/folder1/image.jpg
The var $dir . '/' . $file gives me this output:
uploads/folder1/image.jpg
realpath($dir . '/' . $file gives me this output:
/home/vhosts/example.com/subdomains/develop3/httpdocs/jack/single/uploads/folder1/image.jpg
What i want to achieve is this output:
`http://develop3.example.com/jack/single/uploads/folder1/image.jpg`
How can i achieve this, so that i can create a share link?
You could use preg_replace on the output of realpath to replace everything up to httpdocs with your site's URL:
echo preg_replace('#^' . preg_quote($_SERVER['DOCUMENT_ROOT']) . '[\\\\/]#', "{$_SERVER['HTTP_HOST']}/", realpath('test6.php')) . "\n";
You can use $_SERVER['HTTP_HOST'] to get you site's name:
function get_link($to_file){
return "https://".$_SERVER['HTTP_HOST']."/jack/single/".$to_file;
}
echo get_link($dir . '/' . $file);
Change the function's url parts according to your project (do you use https or http? Will /jack/single always be the parent folder of uploads?)

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.

Cakephp: Show image if uploaded or show text if image was not uploaded

I am developing a system where the user may upload up to four photos. If the user does not upload a photo I would like that the follow text will be displayed: 'empty'.
I have prepared the below code however I didn't managed :/ The problem is that when an image is uploaded it still prints 'empty' and the uploaded image does not show up.
<?php if (file_exists('../files/collection/photo2/' .$collection['Collection']['photo_dir2'] . '/thumb_' . $collection['Collection']['photo2']))
{
echo $this->Html->image('../files/collection/photo2/' . $collection['Collection']['photo_dir2'] . '/thumb_' . $collection['Collection']['photo2']);}
else
{
echo ('empty');
}
?>
I appreciate you guidance and help :)
TLDR: The file you're checking for doesn't exist. Fix your path.
Detail:
You're trying to use the same path for both your HTML <img> as well as the PHP file_exists() check.
The problem is, that the HTML image is looking for a file via the user's browser, where the file_exists() method is looking for the file via your server. The two paths are very rarely the same.
Try using a correct path in your PHP's file_exists() method, and it should pass the check.
For example:
if(file_exists(APP . 'files' . DS . 'collection' . DS . 'photos2' . $collection['Collection']['photo_dir2'] . DS . 'thumb_' . $collection['Collection']['photo2'])) {
echo $this->Html->image('../files/collection/photo2/' . $collection['Collection']['photo_dir2'] . '/thumb_' . $collection['Collection']['photo2']);
}
else {
echo ('empty');
}

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.

Checking if file exists

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.

Categories