Trouble getting PHP file_exists to work - php

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.

Related

PHP image load function reads from the controller instead of domain/folder/to/image

Dear stackoverflow community,
Loading images from function works when I am in the indexAction (index of the controller, e.g gallery). When I want to load images from function while in a sublink of the main controller (e.g gallery/family) it doesn't load the images.
So when going to: domain.com/gallery everything is working.
When going to domain.com/gallery/family the images will be trying to find "domain.com/gallery/app/assets/image/gallery/family/" instead of "domain.com/app/assets/image/gallery/family/".
Image location is at "app/assets/image/gallery/family/" then running this function:
public function insertFamilyImages()
{
$directory = 'app/assets/image/gallery/family/';
$extension = '.jpg';
$html = '';
if ( file_exists($directory) ) {
foreach ( glob($directory . '*' . $extension) as $file ) {
$html .= '<li>';
$html .= '<img src="' . $file . '" alt="">';
$html .= '</li>';
}
} else {
echo 'directory ' . $directory . ' doesn\'t exist!';
}
return $html;
}
I am stuck at this and google doesn't help me. Neither I can find a similiar post on stackoverflow regarding this issue.
Thanks in advance,
Caleb
From looking at this it looks like when you create your html you point the img src to the file system path and not the uri. This html will be loaded in a remote browser and the browser can't access a remote file system. It needs an uri.
E.g.
Let say your domain name is example.com and en example image is called eg.png
Your image is located on your disk at app/assets/image/gallery/family/eg.png (relative).
However your images are accessible externally at https://example.com/gallery/family/eg.png.
You code would look something like this:
public function insertFamilyImages()
{
$directory = 'app/assets/image/gallery/family/';
$uri = 'https://example.com/gallery/family/';
$extension = '.jpg';
$html = '';
if ( file_exists($directory) ) {
foreach ( glob($directory . '*' . $extension) as $file ) {
$file = $uri.basename($file);
$html .= '<li>';
$html .= '<img src="' . $file . '" alt="">';
$html .= '</li>';
}
} else {
echo 'directory ' . $directory . ' doesn\'t exist!';
}
return $html;
}
You'll have to adjust this code to fit your case, but it should point you in the right direction where the problem lies. I used a complete uri here to point to the image to illustrate the point, but this could be made relative as well to the web root.
Never load / read / import any file with relative path. Otherwise your code will be faulty unpredictable.
Always use absolute path. In first php file like index.php which is entry point to your application define global root path like this:
define('ROOT', __DIR__);
then use ROOT as your constant at all files access/manipulation in your application.
$directory = ROOT.'/app/assets/image/gallery/family/';
You will never have problems with paths.

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.

use file_exists() to check wordpress uploads folder

I have created a directory in Wordpress uploads folder for end user to bulk upload photos via ftp. Images are numbered 1.jpg, 2.jpg... etc. I've generated the image urls successfully, but now I want to test for empty urls - i.e. if "8.jpg" doesn't exist, show a placeholder image from the theme's images folder instead.
I'm trying to use file_exists(), but this returns false every time and always displays the placeholder image. Any suggestions would be appreciated.
<?php while ( have_posts() ) : the_post();
// create url to image in wordpress 'uploads/catalogue_images/$sale' folder
$upload_dir = wp_upload_dir();
$sub_dir = $wp_query->queried_object;
$image = get_field('file_number');
$image_url = $upload_dir['baseurl'] . "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG"; ?>
<?php if(file_exists($image_url)){
echo '<img src="' . $image_url . '" alt="" />';
} else {
//placeholder
echo '<img src="' . get_bloginfo("template_url") . '/images/photo_unavailable.jpg" alt="" />';
} ?>
<?php endwhile; ?>
The PHP file_exists function mainly expects an internal server path to the file to be tested. This is made obvious with the example.
Fortunately, we see that wp_upload_dir() gives us several useful values:
'path' - base directory and sub directory or full path to upload directory.
'url' - base url and sub directory or absolute URL to upload directory.
'subdir' - sub directory if uploads use year/month folders option is on.
'basedir' - path without subdir.
'baseurl' - URL path without subdir.
'error' - set to false.
I've bolded what we want to use. Using these two values, you have to generate two variables, one for the external URL and one for the internal file path:
$image_relative_path = "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG";
$image_path = $upload_dir['basedir'] . $image_relative_path;
$image_url = $upload_dir['baseurl'] . $image_relative_path;
Then use file_exists($image_path) instead of file_exists($image_url).
Note
As with the PHP notes on PHP >= 5.0.0, you can indeed use file_exists with some URLs, however the http:// protocol is not supported for the stat() function (which is what file_exists uses.)
You have to use an internal path for checking if a file exists.
So use $upload_dir['path'] instead $upload_dir['baseurl']
[path] - base directory and sub directory or full path to upload
directory.
http://codex.wordpress.org/Function_Reference/wp_upload_dir

Delete an image after it has been seen by a visitor

I want to show my visitors the images in a folder and after then have seen it, I want all those files deleted!
This is what I tried, but It won't work. I think it's because PHP is generating a html file which tells the browser it must first get an image from a different place but the html file was already removed.
<?php
foreach (glob("files/*.*") as $prevpic) {
echo '<img src="' . $prevpic . '" />';
}
foreach (glob("files/*.*") as $file) {
unlink($file);
}
move_uploaded_file($_FILES["file"]["tmp_name"], "files/" . $_FILES["file"]["name"]);
?>
You can do something like so ...
<?php
foreach (glob("files/*.*") as $file) {
echo '<img src="data:image/' . pathinfo($file, PATHINFO_EXTENSION) . ';base64,' . base64_encode(file_get_contents($file)) . '" />';
unlink($file);
}
?>
... which is basically writing the image data into the html, and then discarding the image.
I would handle this by simply managing your images through a download script (php).
You track sessions and simply don't display the images requested, but fail gracefully with a response, or let your app handle it via session based tracking.
That way no images are deleted 'onview'.

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