I have an image url but there is not image or the image name has been renamed, so i am not able to view the image in this case i want to show a default custom image. any idea on how to do it
thanks in advance
If it's the same site, you can use any of PHP filesystem functions to see if an image file still on it's place. is_readable() is my favorite one for that purpose.
Sure, not URL but a filesystem path should be used.
If it's just a hotlinks to other sites - forget it. You can't check it for reasonable price.
if the image is one your server ie. if you know the path to the image file, you can use the php function file_exists
if (file_exists($imageFilePath)){
$url = $imageUrl;
} else {
$url = $customImageUrl;
}
if the file is located on your server
<?php
$filename = '/path/to/file.jpg';
if (!file_exists($filename)) {
$filename = '/path/to/default.jpg'
}
?>
otherwise you can try using GetImageSize
if(#GetImageSize($remoteImageURL)){
//image exists!
}
Related
So I have a few images in the server (public_html/img/profile_pictures/).
This is how I currently set the image:
echo "<img src='img/profile_pictures/main_photo.png'/>";
The main_photo can change each day, but if it changes to main_photo.jpg insted, it wont show (because the extension is hardcoded on that line(.png)). Is it possible to display the photo without knowing the extension for the image file?
If you want a PHP code, then try this. This code will look for main_photo.* inside your folder and automatically set the extension upon finding one.
Remember to set the path properly
<?php
$yourPhotoPath = "img/profile_pictures/";
foreach (glob($yourPhotoPath.'main_photo.*') as $filename) {
$pathInfo = pathinfo($filename);
$extension = $pathInfo['extension'];
$fileName = chop($pathInfo['basename'], $extension);
echo "<img src='".$yourPhotoPath.$fileName.$extension."'/>";
}
?>
if a Photo isn't loaded, it's width and size is null.
Although I would advise you to write a class that checks and loads images, I get a feeling you want a simple solution. so, given by the premise that the photo is either
<img src='img/profile_pictures/main_photo.png'/>
or
<img src='img/profile_pictures/main_photo.jpg'/>
and that neither this path nor this filename ever changes and in the folder is only one picture,
you could simply echo both.
The img of the one that is empty will not be shown.
A better way was to write a class that loads your photo and checks if the photo is really there, like
$path = 'img/profile_pictures/main_photo.png';
if(!file_exists('img/profile_pictures/main_photo.png'))
{
//use the jpg path
$path = 'img/profile_pictures/main_photo.jpg';
}
You can ofc just inline this if case, but it's bad practise to intermix buisinesslogic and format logic, so I advice you to write a class for it.
I am having a problem with move_uploaded_file().
I am trying to upload a image path to a database, which is working perfectly and everything is being uploaded and stored into the database correctly.
However, for some reason the move_uploaded_file is not working at all, it does not produce the file in the directory where I want it to, in fact it doesn't produce any file at all.
The file uploaded in the form has a name of leftfileToUpload and this is the current code I am using.
$filetemp = $_FILES['leftfileToUpload']['tmp_name'];
$filename = $_FILES['leftfileToUpload']['name'];
$filetype = $_FILES['leftfileToUpload']['type'];
$filepath = "business-ads/".$filename;
This is the code for moving the uploaded file.
move_uploaded_file($filetemp, $filepath);
Thanks in advance
Try this
$target_dir = "business-ads/";
$filepath = $target_dir . basename($_FILES["leftfileToUpload"]["name"]);
move_uploaded_file($_FILES["leftfileToUpload"]["tmp_name"], $filepath)
Reference - click here
Try using the real path to the directory you wish to upload to.
For instance "/var/www/html/website/business-ads/".$filename
Also make sure the web server has write access to the folder.
You need to check following details :
1) Check your directory "business-ads" exist or not.
2) Check your directory "business-ads" has permission to write files.
You need to give permission to write in that folder.
make sure that your given path is correct in respect to your current file path.
you may use.
if (is_dir("business-ads"))
{
move_uploaded_file($filetemp, $filepath);
} else {
die('directory not found.');
}
I have visited this article previously and found it useful, but i would like to add more functionality to it by having it save an image file name according to the URL name.
This is what I've done so far and it works.
$contents=file_get_contents('http://www.domain.com/logo.png');
$save_path="C:/xampp/htdocs/proj1/download/[logo.png]";
file_put_contents($save_path,$contents);
Basically, where I have put square brackets around I want to have that dynamic based on the URL file name. For example, if i have an image url such as this: https://cf.dropboxstatic.com/static/images/brand/glyph-vflK-Wlfk.png, I would like it to save the image into the directory with that exact image name which in this case is glyph-vflK-Wlfk.png.
Is this possible to do?
I would do this way
$url = "http://www.domain.com/logo.png";
$file = file_get_contents($url);
$path = "C:/xampp/htdocs/proj1/download/". basename($url);
return !file_exists($path) ? file_put_contents($path, $file) : false;
From what I understand, what you're trying to do is the following :
$url = 'http://www.domain.com/logo.png';
$contents=file_get_contents($url);
$posSlash = strrpos($url,'/')+1);
$fileName = substr($url,$posSlash);
$save_path="C:/xampp/htdocs/proj1/download/".$fileName;
file_put_contents($save_path,$contents);
There is a function for that, basename():
$url="http://www.domain.com/logo.png";
$contents=file_get_contents($url);
$save_path="C:/xampp/htdocs/proj1/download/".basename($url);
file_put_contents($save_path,$contents);
You might want to check if it already exists with file_exists().
Is it safe to display a image using $_GET for path?
For example using this format: image.php?path=/images/example.jpg
Yes you can, just make sure you use isset so that it doesn't throw undefined index if someone fiddles with your URL, also you need to check whether the path is valid else show some other image, like image not found by writing text in alt attribute
if(isset($_GET['index'])) {
echo '';
}
Points to be looked for:-
Anybody can tinker URL
You'll have to sanitize the value
Often path's will be changed so be sure you use alt text if image is not found
If you don't sanitize, will lead to easy intrusion for hackers
Inshort I suggest you NOT TO DO SO
Its perfectly safe if you check the path exists after using basename($_GET['path']) on the file name, also define your path to the images folder.
Then check that it is an image with getimagesize($path). If any fail, change the filename to a not found image or such.
<?php
$path_to_images = '/images/';
$not_found_img = './path/to/not_found_image.jpg';
// check path is set and not empty
if(empty($_GET['path'])){
$path = $not_found_img;
}else{
$path = $path_to_images.basename($_GET['path']);
// check that image exists
if(!file_exists($path)){
$path = $not_found_img;
}else{
//Check if image
if($img_size = getimagesize($path)) {
//alls good $path validated
}else{
$path = $not_found_img;
}
}
}
// do somthing with your $path
?>
Completely yes. There are no problems, hackers can't give there bad code, what can hack your page or work with your database. But take care on some other elements.
My app has a 'Photo' field to store URL. It uses sfWidgetFormInputFileEditable for the widget schema. To delete the old image when a new image is uploaded, I use unlink before setting the value in the over-ridden setter and it works!!!
if (file_exists($this->_get('photo')))
unlink($this->_get('photo'));
Photos are stored in uploads/photos and when saving 'Photo' only the file name xxx-yyy.zzz is saved (and not the full path). However, I wish to know how symfony/php knows the full path of the file to be deleted?
Part 2:
I am using sfThumbnailPlugin to generate thumbnails. So the actual code looks like this:
public function setPhoto($value)
{
if(!empty($value))
{
Contact::generateThumbnail($value); // delete current Photo & create thumbnail
$this->_set('photo',$value); // setting new value after deleting old one
}
}
public function generateThumbnail($value)
{
$uploadDir = sfConfig::get('app_photo_upload'); // path to upload folder
if (file_exists($this->_get('photo')))
{
unlink($this->_get('photo')); // delete full-size image
// path to thumbnail
$thumbpath = $uploadDir.'/thumbnails/'.$this->get('photo');
// read a blog, tried setting dir manually, doesn't work :(
//chdir('/thumbnails/');
// tried closing the file too, doesn't work! :(
//fclose($thumbpath) or die("can't close file");
//unlink($this->_get('photo')); // doesn't work; no error :(
unlink($thumbpath); // doesn't work, no error :(
}
$thumbnail = new sfThumbnail(150, 150);
$thumbnail->loadFile($uploadDir.'/'.$value);
$thumbnail->save($uploadDir.'/thumbnails/'.$value, 'image/png');
}
Why can't the thumbnail be deleted using unlink()? is the sequence of ops incorrect?
Is it because the old thumbnail is displayed in the sfWidgetFormInputFileEditable widget?
I've spent hours trying to figure this out, but unable to nail down the real cause.
Thanks in advance.
$path = "uploads/photos";
$image = "Name of image";
unlink($path.$image);
Solved & Surprised
OK, here is the code that worked after adding some echoes...
public function generateThumbnail($value)
{
$uploadDir = sfConfig::get('app_photo_upload'); // path to upload folder
// path to thumbnail
$thumbpath = $uploadDir.'/thumbnails/'.$this->get('photo');
if (file_exists($uploadDir.$this->_get('photo')))
{
>> unlink($uploadDir.$this->_get('photo')); // delete full-size image
>> unlink($thumbpath); // delete thumn
}
//thumbnail generation code
}
Supposedly, the unlink($this->_get('photo')) never worked. Infact, the if(fileExists) block was never entered and yet the file was deleted.
I think sfWidgetFormInputFileEditable was deleting the full-image automatically when a new one was being uploaded.
Thanks Martin & Kanak
Are you sure about this line?
$thumbpath = $uploadDir.'/thumbnails/'.$this->get('photo');
I think you should use $this->_get('photo'); instead of $this->get('photo');
Maybe try to dump $thumbpath variable.
var_dump($thumbpath); exit;