Why is file_exists() returning false? - php

I'm trying to retrieve images for WP posts, which are held in a wp-uploads directory, using if (file_exists() but it's not recognising the file path.
For each post, there are up to 8 images available. Each image has the letters a-g at the end of the file name (or nothing), and has str_replace to replace certain characters in the file names.
I need to show each image if it exists, and if not, to return nothing. So if the post is associated with images with b, d and f at the end, it just shows those three.
I've tested without the (file_exists()) and its able to pick up the images with a simple echo for each - but it seems the $img paths aren't being recognised.
Im a bit of a php noob so any help would be appreciated...
$uid = get_post_meta (get_the_ID(), 'Unique number', true);
$root ="/wp-content/uploads/2016/Collection/";
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$img = $root.$path.".jpg";
$imga = $root.$path."a.jpg";
$imgb = $root.$path."b.jpg";
$imgc = $root.$path."c.jpg";
$imgd = $root.$path."d.jpg";
$imge = $root.$path."e.jpg";
$imgf = $root.$path."f.jpg";
$imgg = $root.$path."g.jpg";
if (file_exists($img)) { echo "<img src='".$root.$path.".jpg' />"; } else { echo ""; }
if (file_exists($imga)) { echo "<img src='".$root.$path.".jpg' />"; } else { echo ""; }
if (file_exists($imgb)) { echo "<img src='".$root.$path."b.jpg' />"; } else { echo ""; }
if (file_exists($imgc)) { echo "<img src='".$root.$path."c.jpg' />"; } else { echo ""; }
if (file_exists($imgd)) { echo "<img src='".$root.$path."d.jpg' />"; } else { echo ""; }
if (file_exists($imge)) { echo "<img src='".$root.$path."e.jpg' />"; } else { echo ""; }
if (file_exists($imgf)) { echo "<img src='".$root.$path."f.jpg' />"; } else { echo ""; }
if (file_exists($imgg)) { echo "<img src='".$root.$path."g.jpg' />"; } else { echo ""; }`

You need to rearrange the way you are telling PHP to look up the address,
$root is probably not your absolute file path root (probably meaning absolutely) so instead use the special super variable for this, $_SERVER['DOCUMENT_ROOT'] which is the root of the web accessible filepath, therefore you then have:
$img = $_SERVER['DOCUMENT_ROOT'].$root.path.".jpg"
//while retaining your current / at the start of $root
This is the file structure to check if the file exists, not the file structure to reference in the <img> tag, that appears to be correct in your examples above.
So, your overall correction should look like this:
$root ="/wp-content/uploads/2016/Collection/";
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$img = $root.$path.".jpg";
...
if (file_exists($_SERVER['DOCUMENT_ROOT'].$img)){
....
}
An additional note is that the results of this function are cached so you should call clearstatcache() at the start of this file so that it can make fresh checks for if the images exist. Currently without this even if the image does exist, PHP will be using the cached - past- results which may not be up to date.

You start $root with a /, therefore it's starting from the server's root directory. Remove the first / and retry.

$uid = get_post_meta (get_the_ID(), 'Unique number', true);
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$uploads = wp_upload_dir();
Get base root directory.
$root = $uploads['path'];
$imgDir = $root.$path.".jpg";
if (file_exists($imgDir)){
.......
}

Related

How to integrate a link to parse in PHP Simple XML

I need to download all photos about estates from an XML to save on the server. Every estate child in the XMl has a general section with all information and then a node called Foto (estate's photos) and another one for plans (Planimetria). The link of every image is structured as is:
<Link>http://www.site.it/ImageView.ashx?id=[photoID]&reduce=1438[can be set as I want es: 1000, 960, 1080]</Link>
I need to call it inside the $url_photo and $url_plan so I can read the photoID from XML and set resolution (1438,1000,960) with a global variable.
This is my code:
<?php
$xml = simplexml_load_file("Schede.xml"); // your xml
$path = '/mnt/c/Users/Giuseppe/Desktop/FotoTest/';
$i = 1;
$resolution = '1000';
// Estate Image
foreach($xml->CR03_SCHEDE as $estate){
//if((string) $estate['ELIMINATO'] = "NO"){
echo "\nEstate n $i Images\n";
foreach($estate->Foto->CR04_SCHEDE_FOTO as $photo){
$url_photo = (string) $photo->Link;
$filename_photo = basename($photo->CR04_FILENAME); // get the filename
if(file_exists($path . $filename_photo)) {
echo "file $filename_photo already exists \n";
}
else {
$img_photo = file_get_contents($url_photo); // get the image from the url
file_put_contents($path . $filename_photo, $img_photo); // create a file and feed the image
echo "file $filename_photo created \n";
}
}
// Plans
echo "\nEstate n $i plans\n";
foreach($estate->Planimetria->CR04_SCHEDE_FOTO as $plan) {
$url_plan = (string) $plan->'http: // www.site.it/ImageView.ashx?id=' . $plan->ID . '&reduce=' . $resolution; //$plan->Link;
$filename_plan = basename($plan->CR04_FILENAME);
if(file_exists($path . $filename_plan)) {
echo "file planimetry $filename_plan already exists \n";
}
else {
$img_plan = file_get_contents($url_plan); // get the image from the url
file_put_contents($path . $filename_plan, $img_plan); // create a file and feed the image
echo "file planimetry $filename_plan created \n";
}
}
$i++;
/*}
else{
echo "$estate->attributes(Riferimento)"."Deleted\n";
}*/
}
?>
I also have a problem with the first if commented:
if((string) $estate['ELIMINATO'] = "NO")...
Eliminato is an attribute of CR03_SCHEDE but the script won't read it and in any case go inside the if.
The complete XML has about 70/80 properties and the foreach works well to download all images, but I need that it should download the only one that has that attribute equals to NO
This is the example of XML (only one estate): link
Thanks to all
This is a classic mistake:
if((string) $estate['ELIMINATO'] = "NO")
You used the assignment operator instead of the comparison operator. Please use this exact form:
if ('NO' == (string)$estate['ELIMINATO'])

PHP file_exists returns false when variable is in file name

I want to check if a jpeg file exists on my server. However, when I check it, the return value is false.
clearstatcache();
// the $img variable is dynamically got from $split[1] which is something like image.jpeg" />
$img = str_replace('"','',$split[1]); // remove double quotes
$img = str_replace('/>','',$img); // remove img end tag
$img = str_replace(' ','',$img); // remove spaces
$filename = "uploads/image.jpeg"; // original file name
$fn = "uploads/".$img; // file name with dynamic variable in it
if(file_exists($fn)){
echo "yes";
}else{
echo "no";
}
// Check if the two strings are the same and they are
if($fn == $filename){
echo "same";
}
The original static file name returns back yes, while the dynamic one gives back no. I checked and safe_mode is off on my server and the two variables ($fn and $filename) are completely the same. If I just simply make $img equal to image.jpeg without any str_replace it also gives back true and echos out yes.
Overall, I do not know what is the problem with the $img variable and why does it give me back two different results, if the variables are the same?
You have some serious flaw in your debugging logic somewhere, try this:
echo '<hr/>';
clearstatcache();
// the $img variable is dynamically got from $split[1] which is something like image.jpeg" />
$img = str_replace('"','',$split[1]); // remove double quotes
$img = str_replace('/>','',$img); // remove img end tag
$img = str_replace(' ','',$img); // remove spaces
$filename = "uploads/image.jpeg"; // original file name
$fn = "uploads/".$img; // file name with dynamic variable in it
if(file_exists($fn)){
echo '$fn: yes';
echo '<br/>';
}else{
echo '$fn: no';
echo '<br/>';
}
if(file_exists($filename)){
echo '$filename: yes';
echo '<br/>';
}else{
echo '$filename: no';
echo '<br/>';
}
// Check if the two strings are the same and they are
if($fn == $filename){
echo "same";
echo '<br/>';
}
else
{
echo 'different';
echo '<br/>';
}
echo '<pre>';
var_dump( $split[1], $filename, $fn )
echo '</pre>';
echo '<hr/>';

PHP foreach loop from a text file

I'm having trouble with a foreach loop from a text file. I have a directory tree, and a list of these directories is in a text file, I want to check the tree against the list, and echo if any directories are missing.
The problem that I'm having is that I can't see an account for a new line, so if the file has 1 line, then it returns that it exists, but if the file has two line it returns the first as missing and the second as existing, even if it's the same entry twice in the file - see code below for clarification
<?php
$logFile = 'LogFile.txt';
$rootDirectory = 'C:\testdir\\';
$verificationFile = 'verificationfiles/directoryverification.txt';
$verificationContents = file($verificationFile);
$fh = fopen($logFile,'a') or die("can't open file");
$new_line = "\r\n";
foreach($verificationContents as $directoryName) {
$subDirectory = $rootDirectory.$directoryName;
echo "$subDirectory <br />";
if (file_exists($subDirectory)) {
echo "$subDirectory Exists <br />";
} else {
echo "$subDirectory Does Not Exist <br />";
$libverificationfailed = 'failed';
fwrite($fh, "$subDirectory Not Found");
fwrite($fh, $new_line);
}
}
?>
So, as an example, the root directory has 2 sub directories, subdir1 and subdir2.
directoryverification.txt
subdir1
subdir2
and the page echos
C:\testdir\subdir1
C:\testdir\subdir1 Does Not Exist
C:\testdir\subdir2
C:\testdir\subdir2 Exists
So if there is a new line after the data in the text file, the code isn't reading it correctly. I'm hoping that this makes sense and that somebody can help.
regards,
Thanks rickdenhaan,
$subDirectory = rtrim($subDirectory);
Just before the if statement sorted it.
Try this
$rootDirectory = 'C:\testdir\\';
$verificationFile = 'verificationfiles/directoryverification.txt';
$file = new \SplFileObject($verificationFile, 'r');
$file->setFlags(\SplFileObject::SKIP_EMPTY);
while ( $dirname = $file->fgets() )
{
$dirname = $rootDirectory . trim($dirname);
if ( !file_exists($dirname) )
{
echo sprintf("direcrory %s does not exist\n", $dirname);
continue;
}
echo sprintf("direcrory %s exists\n", $dirname);
}

PHP unlinking not working with variable

Going out of my mind with php unlinking
Here is my delete file script
$pictures = $_POST['data'];
//print_r ($pictures);
$imageone = $pictures[0];
$filename = "file:///Users/LUJO/Documents/CODE/REVLIVEGIT/wp-content/uploads/dropzone/" . $imageone;
echo $filename;
if (is_file($filename)) {
chmod($filename, 0777);
if (unlink($filename)) {
echo 'File deleted';
} else {
echo 'Cannot remove that file';
}
} else {
echo 'File does not exist';
}
The above does not work, error response is file does not exist
however if i change the filename path to this (the echo data from the echo above)
$filename = "file:///Users/LUJO/Documents/CODE/REVLIVEGIT/wp-content/uploads/dropzone/1420291529-whitetphoto.jpeg "
works fine and deletes the image.
Why can i not use the $imageone variable?
Do a print_r($pictures) to see if $pictures[0] is indeed the filename you're looking for.
Also note that if $pictures[0] is "//windows/*" you'll loose your windows if the user running PHP has administrative rights... so just using $pictures=$_POST["data"] is very VERY unsafe!

How to get the extension of a file which is stored in the system using php

I am trying to check whether a file name (user_id) with a particular extension exists in a location. Whenever I execute this only if part gets executed and the control does not goes to the else if part, even though the image is not of the png extension.
$img1 = "../img/profile_imgs/".$user_id.".jpg";
$img2 = "../img/profile_imgs/".$user_id.".png";
$img3 = "../img/profile_imgs/".$user_id.".jpeg";
if (is_bool(file_exists($img1))==1)
{
echo "am here in jpg";
$prof_img =$img_name_jpg;
}
else if (is_bool(file_exists($img2))==1)
{
echo "am here in png";
$prof_img =$img_name_png;
}
else if (is_bool(file_exists($img3))==1){
echo "am here in jpeg";
$prof_img =$img_name_jpeg;
}
Why do you use this complicated condition:
if (is_bool(file_exists($img1))==1)
This should work just fine:
$img1 = "../img/profile_imgs/".$user_id.".jpg";
$img2 = "../img/profile_imgs/".$user_id.".png";
$img3 = "../img/profile_imgs/".$user_id.".jpeg";
if (file_exists($img1))
{
echo "am here in jpg";
$prof_img = $img_name_jpg;
}
else if (file_exists($img2))
{
echo "am here in png";
$prof_img = $img_name_png;
}
else if (file_exists($img3))
{
echo "am here in jpeg";
$prof_img = $img_name_jpeg;
}
In your code:
is_bool(file_exists($img1)) == 1
Tests whether the outcome of file_exists() is a boolean, which it always is.
That said, you can write a small helper function that does the testing for you using an array of extensions you want to look for:
function filePathMatchingExtensions($path, array $extensions)
{
foreach ($extensions as $extension) {
if (file_exists($path . $extension)) {
return $path . $extension;
}
}
return false;
}
$extensions = ['.jpg', '.jpeg', '.png'];
$prof_img = filePathMatchingExtensions("../img/profile_imgs/$user_id", $extensions);
if ($prof_img !== false) {
// it exists
} else {
// it doesn't exist
}
I think it will be better to keep file name in your database , and not try to guess the extension of the file.
Anyways you can try the #Typoheads reply or function glob() if necessary
http://php.net/manual/en/function.glob.php

Categories