I am trying to get a picture from the database and echo this on my website, and everything works like I want to, but now I got this tiny problem where if the image has no name yet, or it errors (like a 404 error), that I get a ugly tiny broken image icon.
Can I get it to work that I get a default image when I get the error? I tried this, but it only worked for where there was no name set yet.
if(!empty($filename)){ echo $filename;} else{ echo "pf.png"; }
Insert this in the image tag:
onerror="this.src='[img src]'"
Since you say it is working with "pf.png", I assume that you are at least using the filename correctly. So if you get that broken image, it means the resource could not be loaded, because it does not exist or cannot be retrieved.
So you also have to check that the image exists before trying to use it anyhow :
if(!empty($filename) && file_exists($filename) {
echo $filename;
} else {
echo "pf.png";
}
To do this i php, you will have to check if the file exists. You wont be able to do this if the link to the image is over "http:/www.*"
Clément Malet code above works fine.
You can read more about file_exitsts function here:
http://php.net/manual/en/function.file-exists.php
If the link to image is over "http:/www.*" you can use jquery.
Put this code before </body> Remember to include jquery
$(document).ready(function(){
$("img").error(function(){
$(this).attr("src", "http://google.dk/default.php");
})
.each(function() {
$(this).attr("src",$(this).attr("src"));
});
})
Related
I have a set of articles in Drupal 7, each with a field for an image. If I remove an image from FTP, or it becomes corrupt, or for some reason it's not at the location it thinks it is, the site will display the alt text and appear broken. I would like to tell Drupal to do something else in this case, like display a 'filler' or 'default' image. Is there a way to do that?
I tried doing a 'if file exists' statement in php but it won't let me write it. I tried adding a case for if no output is presented, but that only works for empty output, not output which points to an invalid file. I haven't found anything else in my research which allows me to do this in Drupal.
Please note this is not an action for when there is no image provided. This is for when an image IS provided but it doesn't exist. I want the site to fail gracefully.
Thanks!
Brendan
In hook_field_display_alter you can check for file_exists and show a default image
In template_preprocess_node pass the uri value of the image variable to file_create_url. This will get you the absolute path to the image.
Then use PHP's file_exists function to verify its existence of the image path. Assign this to a variable $variables[image_exists] = file_exists($image_path);
Then in your node article template file:
if ($image_exists) {
// render $content['field_image']
} else {
// render some other markup
}
Im using a great opensource script called bulletproof allowing users to upload a profile picture.
The profile picture gets stored in a folder as specified. Im not using any mysql.
What I would like to do is display a default user img if user has not uploaded a profile picture.
If he/she has uploaded a profile picture the default img will obviously get overwritten to the pic uploaded by user.
The problem comes in on how would I display the default profile pic, if user has not uploaded anything? Keeping in mind im not using any mysql.
When an image is uploaded it is assigned the name of the user ID, like so
<img src="imgs/users/1.png" style="width:100%" height="125px">
Would you say it is the most efficient way to search the folder for an image match on the name userID?
If something is found display uploaded img else display default img? Or should I rather go a mysql route?
Hope the question is clear, if you need any more info please drop me a comment below. Any advice and/or help appreciated.
EDIT: this is what I eventually came up with, probably not most efficient but does the job
function getProfilePic($userID){
$filename ='imgs/users/'.$userID.'.png';
if(file_exists($filename)){
return $img = $userID.'png';
exit();
}
$filename='imgs/users/'.$userID.'.jpg';
if(file_exists($filename)){
return $img = $userID.'jpg';
exit();
}
else{
return $img = 'default.jpg';
exit();
}
}
<img src="imgs/users/<?php echo getProfilePic($userID) ?>" style="width:100%" height="125px" />
You can use:
PHP file_exists() Function
Reference
https://www.w3schools.com/Php/func_filesystem_file_exists.asp
Or modify this code :)
<?php
function show_image($user_id){
if(file_exists("imgs/users/$user_id.png")){
return "<img src=\"imgs/users/$user_id.png\" style=\"width:100%\" height=\"125px\">";
}
else{
return "<img src=\"imgs/users/default.png\" style=\"width:100%\" height=\"125px\">";
}
}
echo show_image(1);
?>
You can use file_exists to check if the image exists, and then use the default image if that returns false.
At the time of image upload, make user-wise image. Means image name must be the name of username or id.
At the time of showing image put a if condition to check if logged-in user image exist using its id or name in file_exists. If not then load the default image.
So this is a weird phenomenon I've never experienced in that I have an HTML form on image upload (exactly the one on W3). It does it's job properly when clicked and pushes the user profile picture into a folder while saving the name of the file on a database. Underneath the upload, I have a little image tag that spits out the uploaded profile picture. The end goal is for that profile picture to be displayed on the page constantly while the session exists. When uploaded, it works perfectly fine and the profile picture appears. After one refresh, the image can't be found and the alt="blank" takes over. The location still stays proper in the database so I don't think that's the issue. Is there an error? Do I need to use JS onload? Does the image tag only work once? Please help and thank you for taking the time to read this.
PHP:
echo '<img src="'.$loaded_profile_picture.'"id="HOMEPROFILE" alt="blank" style="width:128px;height:128px">';
//$loaded_profile_picture has the value uploads/photo.jpg
Classes.php:
public function addProfilePicture(){
include_once "conn.php";
$sql=$dbh->prepare("UPDATE users SET UserProfilePicture=:UserProfilePicture WHERE UserName=:UserName;");
$sql->execute(array(
'UserProfilePicture'=>$this->getUserProfilePicture(),
'UserName'=>$_SESSION['UserName'],
));
}
Image Upload (Might be the culprit):
if($uploadsuccess&&move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)){
echo " The file ".basename($_FILES['fileToUpload']['name'])." has been uploaded.";
$user->setUserProfilePicture($target_file);
$user->addProfilePicture();
if($user->getUserProfilePicture()!=NULL){
echo '<img src="'.$target_file. '" alt="nom">';
}
}
Edit:
While many users have a similar problem (i.e. Image display with <img src=""> not working) I have tried looking at localhost:8888/xampp/LocalPost/pages/uploads/photos.jpg and it displays just fine. I have also changed file permissions on Windows 7 with no luck. Thanks for all your hard work I'll keep searching.
Edit:
I got around the problem by using $_SESSION['UserProfilePicture'] and it sticks after a refresh. This doesn't solve the question. I'd still very much like someone to help me find what went wrong, because later on I would like to display other people's Profile Pictures which you obviously can't do with session variables.
first of all your missing } et the end of your script
if($uploadsuccess && move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)){
echo " The file ".basename($_FILES['fileToUpload']['name'])." has been uploaded.";
$user->setUserProfilePicture($target_file);
$user->addProfilePicture();
if($user->getUserProfilePicture()!=NULL){
echo '<img src="'.$target_file. '" alt="nom">';
}
}
Check once that after refreshing your page you will be get the value of $loaded_profile_picture variable or not?
If you got the value of $loaded_profile_picture variable then check it is same as your previous path or not?
I currently have a imagecreatefrompng function and it works, but when I use an IF statement on it, then it doesn't work and shows it cannot load image... here is what I have:
$design = $_GET["design"];
if ($design == "DESIGN_1") { $image = imagecreatefrompng('designs/hill.png'); }
if ($design == "DESIGN_2") { $image = imagecreatefrompng('designs/hill2.png'); }
In the header I have:
http://www.website.com/create.png?design=DESIGN_1
it displays the HILL.PNG
But when I have this following in header:
http://www.website.com/create.png?design=DESIGN_2
it doesn't display HILL2.PNG but shows the image not found symbol.
PS. Both images are in the designs folder.
Can you view the second .png in a browser if you navigate to it? Could it be a malformed image file? Since the code appears to be fine, and it's actually trying to display an image... I have to think that there's a problem with the image itself.
The PHP code is OK.
Probably there's an error with the image "designs/hill2.png"
Check it with
<img src="http://www.website.com/designs/hill2.png"/>
Say, for this example, this is an image: http://www.basitansari.com/wp-content/uploads/logoaba.png which is hosted on website A.
I am calling this image into website B with an <img> tag. If the owner of site A removes this image then how can I know that the image has been removed using PHP? If the owner of site A removes the image then I want to show a notfound.jpg image. Should I use cURL for this purpose, or something else?
Checking the image server-side is definitely possible, but it may not be the best solution. Doing so means that all valid images will be loaded twice (once server-side and again by the client). A better method may be to use JavaScript to handle broken images. The following code will only take action if an error occurs while loading the image, replacing it with the image you specify:
<script type="text/javascript">
function brokenImage( obj ) {
obj.onerror = '';
obj.src = 'path/to/notfound.jpg';
return true;
}
</script>
<img onerror="brokenImage(this);" src="broken.jpg" alt="" />
if (!$fp = fopen('http://www.basitansari.com/wp-content/uploads/logoaba.png', 'r')) {
// The image cannot be retrieved, handle it here.
} else {
fclose($fp);
}
This is the quickest way as it just checks that the image can be successfully retrieved, it doesn't download the whole file.
You should call that URL with HEAD method and check if status code 404 (Not found) or 200 (OK)
You can call directly: Check if image source exists using fopen and if not show notfound.jpg. # is used to supress warning
<img src="<?php if (#fopen("http://www.basitansari.com/wp-content/uploads/logoaba.png", "r")) {echo 'http://www.basitansari.com/wp-content/uploads/logoaba.png';} else{echo 'notfound.jpg';}?>" />