file_exists returning false in all cases - php

I'm working on Wordpress at the moment and as simple as it's sounds i'm trying to check if the image is there in the directory if not then it will show a standard no-image.
My problem is that the file_exists is returning false although the url is correct inside it, and it's accessible via browser so it's not a permission issue, and maybe i'm doing it wrong, here's the code;
$img = 'no_img.jpg';
if($val->has_prop('user_image')){
$img_tmp = $val->get( 'user_image' );
if(file_exists($upload_dir['baseurl'].'/users/'.$img_tmp)){
$img = $val->get( 'user_image' );
}
}
if i do var_dump($upload_dir['baseurl'].'/users/'.$img_tmp); it will show the exact direct URL to the file, and it's correct one, but when it enters the file_exists it returns $img = 'no_img.jpg' although the file exists in the directory.... What am i doing wrong??
I tried also to add clearstatcache(); before the file_exists but didn't work also.
Any ideas?

Try to use:
if( getimagesize($upload_dir['baseurl'].'/users/'.$img_tmp) !== false ){
$img = $val->get( 'user_image' );
}
else {
$img = $val->get( 'no_image' );
}
Also refer to the doc getimagesize

you can use
$fullPath=$upload_dir['baseurl'].'/users/'.$img_tmp;
if(#fopen($fullPath,"r")){
........
}

Or as mentioned in comments, try sniff instead :
if (#file_get_contents($upload_dir['baseurl'].'/users/'.$img_tmp, null, null, 0, 1)) {
//ok
}

You need to use $upload_dir['basedir'] instead of baseurl if you used $upload_dir = wp_upload_dir(); to determine the upload path of your WP installation.
or you can use file_get_contents, cURL, or fopen to sniff if image exists for the url.

Related

move_uploaded_file not working despite correct path and existing file

I'm really struggling with an issue relating the move_uploaded_file function of php.
The path should be correct, but see yourself:
$imgDir = "../img/".$CATEGORY;
$fileName = $_FILES['image']['name'];
$maxsize = 800;
$compQuality= 75;
if(!is_dir($imgDir)) {
mkdir($imgDir.'/tn', 0777, true);
chmod($imgDir, 0777);
chmod($imgDir, 0777);
}
$imgDir = $imgDir."/";
$imgTnDir = $imgDir."tn/";
I have also tested it by echo-ing everything and it seems to work, but when it comes to the move_uploaded_file it still does not work, even though I test if the file really exists:
if(file_exists($imgDir.$fileName)) {
$status = "The file ".$fileName." already exists, please choose a different title.";
}
if(!move_uploaded_file($_FILES['image']['tmp_name'], $imgDir.$fileName)) {
$status = "File upload failed, sorry.";
}
if(!empty($status)) {
echo $status;
exit();
}
I hope that someone can help me. If you want I can print anything out you need or give you more snippets of the code. The var $_FILES['image']['tmp_name'] does not only exist, but has a proper name by the way.
Also I have checked the php.ini and both uploading is allowed and the size is surely set high enough.
Thank you in advance.
make sure that you have the right path in $imgDir. You can try:
if(!is_writable($imgDir)) { exit('CANNOT_WRITE_IN_DIR'); }
and also you can use an absolute path, like this:
$imgDir = __DIR__ . "/../img/".$CATEGORY;

File_exists if statement not failing

So I have this If statement that is supposed to check if the file exist and if it fail it should show a default file but the else is not triggering instead it shows "upload//"
if(file_exists($_SERVER['DOCUMENT_ROOT'] ."/uploads/".$photo['album_id'].'/'.
$photo['photo_filename']) == TRUE) {
//gets image if it exist, this part works
$imgsrc .= "../uploads/".$photo['album_id'].'/'.$photo['photo_filename'];
} else {
//gets a default image if it doesn't exist, this doesn't work
$imgsrc .='../uploads/45/image.jpg"';
}
So what happens is either the file name shows from the first part of the if state or "uploads//" shows but what does not show is the else part "../uploads/45/image.jpg". So it looks like it isn't failing.
From the php manual for file_exists
Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
to make sure that the file exist:
$filename = "/uploads/".$photo['album_id'].'/'.$photo['photo_filename'];
$filepath = $_SERVER['DOCUMENT_ROOT'].$filename;
if(file_exists($filepath) && is_file($filepath)){
$imgsrc = '..'.$filename;
}
else{
$imgsrc .='../uploads/45/image.jpg';
}
And for file_exists you don't need to == true. you can just if(file_exists($filepath)).
try this condition:
$file = $_SERVER['DOCUMENT_ROOT'] ."/uploads/".$photo['album_id'].'/'.$photo['photo_filename'];
if(file_exists($file) && !is_dir($file))

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.

Check if file exists before displaying in Magento PHP?

I am able to get the web path to the file like so:
$filename = 'elephant.jpg';
$path_to_file = $this->getSkinUrl('manufacturertab');
$full_path = $path_to_file . '/' . $filename;
But if the file doesn't exist, then I end up with a broken image link.
I tried this:
if(!file_exists($full_path)) {
Mage::log('File doesn\'t exist.');
} else {
?><img src="<?php echo $full_path ?>" /><?php
}
Of course that didn't work because file_exists does not work on urls.
How do I solve this?
1.)
Can I translate between system paths and web urls in Magento?
e.g. something like (pseudocode):
$system_path = $this->getSystemPath('manufacturertab');
That looks symmetrical and portable.
or
2.)
Is there some PHP or Magento function for checking remote resource existence? But that seems a waste, since the resource is really local. It would be stupid for PHP to use an http method to check a local file, wouldn't it be?
Solution I am currently using:
$system_path = Mage::getBaseDir('skin') . '/frontend/default/mytheme/manufacturertab'; // portable, but not pretty
$file_path = $system_path . '/' . $filename;
I then check if file_exists and if it does, I display the img. But I don't like the asymmetry between having to hard-code part of the path for the system path, and using a method for the url path. It would be nice to have a method for both.
Function
$localPath = Mage::getSingleton( 'core/design_package' )->getFilename( 'manufacturertab/' . $filename, array( '_type' => 'skin', '_default' => false ) );
will return the same path as
$urlPath = $this->getSkinUrl( 'manufacturertab/' . $filename );
but on your local file system. You can omit the '_default' => false parameter and it will stil work (I left it there just because getSkinUrl also sets it internaly).
Note that the parameter for getSkinUrl and getFilename can be either a file or a directory but you should always use the entire path (with file name) so that the fallback mechanism will work correctly.
Consider the situation
skin/default/default/manufacturertab/a.jpg
skin/yourtheme/default/manufacturertab/b.jpg
In this case the call to getSkinUrl or getFilename would return the path to a.jpg and b.jpg in both cases if file name is provided as a parameter but for your case where you only set the folder name it would return skin/yourtheme/default/manufacturertab/ for both cases and when you would attach the file name and check for a.jpg the check would fail. That's why you shold always provide the entire path as the parameter.
You will still have to use your own function to check if the file exists as getFilename function returns default path if file doesn't exist (returns skin/default/default/manufacturertab/foo.jpg if manufacturertab/foo.jpg doesn't exist).
it help me:
$url = getimagesize($imagepath); //print_r($url); returns an array
if (!is_array($url))
{
//if file does not exists
$imagepath=Mage::getDesign()->getSkinUrl('default path to image');
}
$fileUrl = $this->getSkinUrl('images/elephant.jpg');
$filePath = str_replace( Mage::getBaseUrl(), Mage::getBaseDir() . '/', $fileUrl);
if (file_exists($filePath)) {
// display image ($fileUrl)
}
you can use
$thumb_image = file_get_contents($full_path) //if full path is url
//then check for empty
if (#$http_response_header == NULL) {
// run check
}
you can also use curl or try this link http://junal.wordpress.com/2008/07/22/checking-if-an-image-url-exist/
Mage::getBaseDir() is what you're asking for. For your scenario, getSkinBaseDir() will perform a better job.
$filename = 'elephant.jpg';
$full_path = Mage::getDesign()->getSkinBaseDir().'/manufacturertab/'.$filename;
$full_URL=$this->getSkinUrl('manufacturertab/').$filename;
if(!is_file($full_path)) {
Mage::log('File doesn\'t exist.');
} else {
?><img src="<?php echo $full_URL ?>" /><?php
}
Note that for the <img src> you'll need the URL, not the system path. ...
is_file(), rather than file_exists(), in this case, might be a good option if you're sure you're checking a file, not a dir.
You could use the following:
$file = 'http://mysite.co.za/files/image.jpg';
$file_exists = (#fopen($file, "r")) ? true : false;
Worked for me when trying to check if an image exists on the URL

PHP's file_exists() will not work for me?

For some reason this PHP code below will not work, I can not figure it out.
It is very strange,
file_exists does not seem to see that the image does exist, I have checked to make sure a good file path is being inserted into the file_exists function and it is still acting up
If I change file_exists to !file_exists it will return an images that exist and ones that do not exist
define('SITE_PATH2', 'http://localhost/');
$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($thumb_name)) {
$img_name = $thumb_name;
}else{
$img_name = $noimg;
}
echo $img_name;
file_exists() needs to use a file path on the hard drive, not a URL. So you should have something more like:
$thumb_name = $_SERVER['DOCUMENT_ROOT'] . 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if(file_exists($thumb_name)) {
some_code
}
http://us2.php.net/file_exists
docs say:
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.
file_exists does only work on the local file system.
So try this if you’re using localhost:
$thumb_name = 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($_SERVER['DOCUMENT_ROOT'].$thumb_name)) {
$img_name = SITE_PATH2.$thumb_name;
} else {
$img_name = $noimg;
}
Have you enabled the option which allows you to use external URLs? You can set it in php.ini:
allow_url_fopen = 1
You have to write the file path like "file:///C:/Documents%20and%20Settings/xyz/Desktop/clip_image001.jpg".
http://php.net/manual/en/function.file-exists.php
did you check the comments below?
Just reading parts of it, but there seem to be several issues.
Caching may be a problem.
When opening FTP urls it always returns true (they say in the comments)
...
Try Below one. Its working for me
define('SITE_PATH2', 'http://localhost/');
$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if ($fileopen = #fopen($thumb_name)) {
$img_name = $thumb_name;
fclose($fileopen);
}else{
$img_name = $noimg;
}
echo $img_name;

Categories