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
Related
I'm using Laravel 5.4.*. I've this simple code in a helper file to upload images/gif in S3 bucket under a folder named say "instant_gifs/". The code is below:
if ( !function_exists('uploadFile') ) {
function uploadFile($fileContent, $fileName, $size='full', $disk='s3')
{
$rv = '';
if( empty($fileContent) ) {
return $rv;
}
if($size == 'full') {
dump($fileName);
$path = Storage::disk($disk)->put(
$fileName,
$fileContent,
'public'
);
}
if ( $path ) {
$rv = $fileName;
}
return $rv;
}
}
From the controller, I'm calling the helper method as below:
$file = $request->gif;
$file_name = 'instant_gifs/' . $user_id . '_' . time() . '_' . $file->getClientOriginalName();
$result = uploadFile($file, $file_name);
In the the $fileName parameter of the helper method, I'm providing the fileName as for example in this format:
"instant_gifs/83_1518596022_giphy.gif"
but after the upload, I see that the file gets stored under this folder
"vvstorage/instant_gifs/83_1518596022_giphy.gif/CRm1o1YEcvX3fAulDeDfwT7DIMCxOKG8WFGcA3lB.gif"
with a random file name
CRm1o1YEcvX3fAulDeDfwT7DIMCxOKG8WFGcA3lB.gif
Whereas, according to the code, it should get stored in this path:
"vvstorage/instant_gifs/83_1518596022_giphy.gif"
Doesn't get any explanation why this is happening. Any clue will be appreciated.
BucketName = vvstorage
Folder I'm mimicking = instant_gifs
After some research & testing, found the issue. put() method expects the 2nd parameter as the file contents or stream not the file object. In my code, I was sending the file as $file = $request->gif; or $file = $request->file('gif'); hoping that Storage class will implicitly get the file contents. But to get the expected result, I needed to call the helper method from the controller as below. Notice the file_get_contents() part.
$file = $request->gif;
$file_name = 'instant_gifs/' . $user_id . '_' . time() . '_' . $file>getClientOriginalName();
$result = uploadFile( file_get_contents($file), $file_name );
Now, I got the image correctly stored under the correct path for example in /instant_gifs/9_1518633281_IMG_7491.jpg.
Now, let me compare/summarize the available methods for achieving the same result:
1) put():
$path = Storage::disk('s3')->put(
'/instant_gifs/9_1518633281_IMG_7491.jpg', #$path
file_get_contents($request->file('gif')), #$fileContent
'public' #$visibility
Got it stored in /vvstorage/instant_gifs/9_1518633281_IMG_7491.jpg
2) putFileAs(): To achieve the same thing withputFileAs(), I needed to write it as below. 1st parameter expects the directory name, I left it blank as I'm mimicking the directory name in s3 through the filename.
$path = Storage::disk('s3')->putFileAs(
'', ## 1st parameter expects directory name, I left it blank as I'm mimicking the directory name through the filename
'/instant_gifs/9_1518633281_IMG_7491.jpg',
$request->file('gif'), ## 3rd parameter file resource
['visibility' => 'public'] #$options
);
Got it stored in /vvstorage/instant_gifs/9_1518633281_IMG_7491.jpg
3) storeAs():
$path = $request->file('gif')->storeAs(
'', #$path
'/instant_gifs/9_1518633281_IMG_7491.jpg', #$fileName
['disk'=>'s3', 'visibility'=>'public'] #$options
);
Got it stored in /vvstorage/instant_gifs/9_1518633281_IMG_7491.jpg
Extras::
4) For storing Thumbnails through put(). Example of stream() ...
$imgThumb = Image::make($request->file('image'))->resize(300, 300)->stream(); ##create thumbnail
$path = Storage::disk('s3')->put(
'profilethumbs/' . $imgName,
$imgThumb->__toString(),
'public'
);
Hope that it helps someone.
1.) Why is there vvstorage in the url?
It is appending that route because your root folder inside of your configuration for S3 is set as vvstorage, so whenever you upload to S3 all files will be prepended with vvstorage.
2.) Why random name even when you passed the name of the file?
Because when using put the file will get a unique ID generated and set as it's file name so no matter what you pass, it won't save the file under the name you wanted. But if you use putFileAs then you can override the default behaviour of put and pass a name of the file.
Hope this clarifies it
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.
I need to look for and echo an image file name that's located in either of these two directories named 'photoA' or 'photoB'.
This is the code I started with that tries to crawl through these directories, looking for the specified file:
$file = 'image.jpg';
$dir = array(
"http://www.mydomain.com/images/photosA/",
"http://www.mydomain.com/images/photosB/"
);
foreach( $dir as $d ){
if( file_exists( $d . $file )) {
echo $d . $file;
} else {
echo "File not in either directories.";
}
}
I feel like I'm way off with it.
You cannot use a url in file_exists, you need to use an absolute or relative path (relative to the runnings script) in the file-system of the server, so for example:
$dir = array(
"images/photosA/",
"../images/photosB/",
"/home/user/www/images/photosB/"
);
You can also use paths relative to the root of the web-server if you don't know the exact path and add the document root before that:
$dir = array(
$_SERVER['DOCUMENT_ROOT'] . "/images/photosA/",
$_SERVER['DOCUMENT_ROOT'] . "/images/photosB/"
);
(or you use it once, where you use file_exists())
Since you are running this script from within the root directory of your website, you won't need to define 'http://www.mydomain.com/' as this will cause Access Denied issues as it is not an absolute/relative file path. Instead, if the images/ folder is at the same directory level as your PHP script, all you will need to do is
$dir = array(
"images/photosA/",
"images/photosB/"
);
Otherwise, just add the absolute path as needed to make it work, but you can not put the. The rest seems as if it should work fine.
As the others said, file_exists() is for local files.
If you REALLY need to look for files over http, you can use :
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
NOTE: This relies on the server returning a 404 if the image does not exist. If the server instead redirects to an index page or a pporly-coded error page, you could get a false success.
I'm learning CodeIgniter. I have a directory img with images (path /img/). I am trying to access it through CI view and check if exists with this code:
$av = '../../../img/content/users/'.$userID.'.jpg';
if(file_exists($av)) {
$avatar = $av;
} else {
$avatar = 'img/content/users/none.jpg';
}
Funny thing is, echoing <img src="'.$av.'"> works. What should I do?
CI always runs on index.php, so paths are always relative from there.
Assuming index.php and /img are at the same level in the root, try this:
$av = 'img/content/users/'.$userID.'.jpg';
if(is_file($av)) { // or better yet, make sure it's really an image
$avatar = $av;
} else {
$avatar = 'img/content/users/none.jpg';
}
Funny thing is, echoing <img src="'.$av.'"> works
It's because the browser is looking in a different place than the server. I'd recommend not using ../../relative/paths but using functions like base_url() and img(). When there are additional segments in the URL, relative paths break.
URLs and file paths are not the same. From the current URL ../../../img/content/users may and likely is something completely different than the file path on the hard disk where the view file is located.
Use following steps
1) Create a custom config file name site_config.php in config file (/application/config/) and paste following code
<?php
$config['base_url'] = "http://".$_SERVER['SERVER_NAME'] . str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
if(!defined('DOCUMENT_ROOT')) define('DOCUMENT_ROOT',str_replace('system/application/config','',substr(__FILE__, 0, strrpos(__FILE__, '/'))));
$config['base_path'] = constant("DOCUMENT_ROOT");
?>
2) Edit autoload.php to autoload site_config.php (/application/config/autoload.php)
$autoload['config'] = array('site_config');
3) Then using following code to view image
$image_path = $this->config->item('base_path').'folder_name/'.$userID.'.jpg';
if(file_exists($image_path)) {
$avatar = $this->config->item('base_url').'folder_name/'.$userID.'.jpg';
} else {
$avatar = $this->config->item('base_url').'default_folder_name/profile.jpg';
}
echo '<img src="'.$avatar.'" />';
I think it will help you
Try this:
$av = './img/content/users/'.$userID.'.jpg';
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;