PHP if image file doesn't exist, show another image - php

I was wondering if someone would be able to help me out with this PHP script I am using for a Jquery Nivo slideshow. The script gets filenames from a text file, and displays them according to the page you are on through pagination.
Is there a way for the script to display another image if the file doesn't exist? For example, if image1.jpg doesn't exist in the images/work/ directory, then the image unavailable.jpg will display instead?
The script:
<?php
echo"
<div class='slider-wrapper theme-custom'>
<div id='slider' class='nivoSlider'>";
$photos=file("photos.txt");
foreach($photos as $image){
$item=explode("|",$image);
if($item[0]==$fields[0]){
$photo=trim($item[1]);
echo"<img src='images/work/$photo' alt='' />\n";
}
}
echo"
</div>
</div>
"?>

foreach ($photos as $image) {
... explode
... trim
if (!is_readable($your_document_root . '/images/work/$photo)) {
$photo = 'default.jpg'; // if the required photo isn't there, change to default image
}
echo blah blah blah
}
Note that I've used is_readable() - some people may suggest using file_exists(), but that can return a false positive: the file may exist, but still can't be read due to a permissions issue. is_readable() combines both and will only return true if the file exists AND can be accessed by the webserver.

You could use file_exists() if it's on your server. It takes a path to the file as an argument, not a URL.
http://php.net/manual/en/function.file-exists.php

You need file_exists();
Returns a boolean. Use it in an if statement. Provided you have proper permissions to access the images.

Related

PHP check if file_exists without extension then Ajax a div with appropriate media tag (img or video) based on filepath

First posting here. I know inline php is not preferred but I haven't converted all my scripts to echo json_encoded arrays to work in javascript on the client side...so for now, I have inline php.
I do not know the extension of the user uploaded media because it could be a jpg,mp4,etc and upon upload it goes into a media folder with the user id as an identifier.
When my user first loads the div (and html page), the php script cycles through an array and does a fetch_assoc from sql query to the database each time; It returns the (media_id #) and prints out an li with the respective media displayed next to some other values from the query.
I only know the (media_id) and the file path name without the extension. When the page first loads, everything works great and the file_exists function returns correctly.
THE PROBLEM
When I AJAX the div and do the query again, because the user added a row to the database, the new list prints out with all info, BUT the file_exists function doesn't recognize the exact same paths as before and I don't have an img or video on the page.
I copy/pasted the exact same code from the original div and put it in a file for ajax to re-query and print the new li's.
All variables are the same and when I hard code a test filepath, it prints fine. Maybe there's a caching issue?
THE CODE
<?php
$result=$conn->query($select);
$row=$result->fetch_assoc();
?>
<li>
<?php
if ($row['count']>0) {
echo "<div class='media-container'>";
$pathname = "uploads/".$row["id"]."media1";
$testjpg=$pathname.".jpg";
$testjpeg=$pathname.".jpeg";
$testpng=$pathname.".png";
$testmp4=$pathname.".mp4";
if (file_exists($testjpg)==TRUE || file_exists($testpng)==TRUE || file_exists($testjpeg)==TRUE) {
echo '<img src="'.$pathname.'">';
}if(file_exists($testmp4)==TRUE) {
echo "<video></video>";
}
echo "</div>";
}?>
</li>
I could use some advice on how to fix this and how to print appropriate media tags on unknown media types.
THE OUTPUT
<div class='media-container'>
</div>
DEBUGGING ATTEMPTS
echoing the exact file path of a known image in an <img> tag works fine. putting echo'test'; inside the file_exists case does nothing.
--
Solution (Kind of)
So I've used html's onerror before and I found a workaround, though I'd still like to know why I was getting an error. PSA this uses JQuery but javascript works too:
My Solution
<script>
function img2video(el, src) {
$( el ).replaceWith( '<video class="videoClass"><source src="'+src+'" type="video/mp4"></video>' );
}
</script>
<body>
<img style="width:100%" onerror="img2video(this,'<?php echo$pathname;?>')" src="<?php echo$pathname;?>">
</body>
Alright, so here's the final answer I made to best fit the problem using glob:
Javascript:
function img2video(el,src,place) {
if (place=='type') {
$( el ).replaceWith( '<video controls controlsList="nodownload" disablePictureInPicture style="width:100%;object-fit:contain;" preload="auto"><source src="'+src+'" type="video/mp4"></video>');
}
}
PHP:
<?php for ( $i=1; $i <= $limit; $i++) {
$path ="[DIRECTORY]/".$row["id"]."media".$i;
$path = (!empty(glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0])) ? glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0] : false;?>
<div>
<img onerror="img2video(this,'<?php echo$path;?>','type',<?php echo$row["id"];?>,<?php echo$i;?>)" src="<?php echo$path;?>">
</div>
<?php } ?>
I don't know how to mark as duplicate, if someone could help with that. My answer uses Glob_Brace from #Akif Hussain 's response on This Question.

Use an image file link to display a random banner

Not sure if this is even appropriate here, but I'm trying to work out how a banner rotator website is using standard html image code, to return a random banner?
<a target=_blank href=http://intellibanners.com/click.php?cid=campaign1>
<img border=0 src=http://intellibanners.com/campaign1.jpg>
</a>
In the example above, that html will display a random image from that campaign.
This started as a bit of a whim to see if I could set up something similar to work with different image sizes, but now it's driving me nuts... trying to figure out how to go from a image url to a database call to send back a different image!?
No lucky searching for ideas or examples, probably because I don't know what sort of processes or functions I should actually be looking for?
I'm thinking there must be some sort of url rewrite for all image calls, that redirects to a handler script...
That script makes the database call, grabs a random image from the nominated campaign, updates stats etc...
And possibly a php header response returns the corresponding image file?
But most of that is new to me and I'm not sure where/how to search for guidance or examples to get me started.
If anyone has any ideas on this, or even the kind of phrasing/functions I need that might help me get there in my own searching, it would be much appreciated!
(I've also installed and tested about 12 different rotator scripts hoping to find one that works the same, but no luck there either).
Thanks!
Matt
I wrote a php script that assumes to exist the wanted folders in the root of your website. Then you can invoke it in a simple way in any location of your website. Here is my script:
rotate.php
<?php
##########################################################
# Simple Script Random Images Rotator • 1.4 • 04.01.2020 #
# Alessandro Marinuzzi [alecos] • https://www.alecos.it/ #
##########################################################
function rotate($folder) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder")) && (is_dir($_SERVER['DOCUMENT_ROOT'] . "/$folder"))) {
$list = scandir($_SERVER['DOCUMENT_ROOT'] . "/$folder");
$fileList = array();
$img = '';
foreach ($list as $file) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file")) && (is_file($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file"))) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
$fileList[] = $file;
}
}
}
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder . '/' . $fileList[$imageNumber];
}
return $img;
} else {
mkdir($_SERVER['DOCUMENT_ROOT'] . "/$folder", 0755, true);
}
}
?>
Now you can create a index.php file where you want and put this line:
<?php include("your_path/rotate.php"); ?>
<a target="_blank" href="http://intellibanners.com/click.php?cid=campaign1">
<img border="0" src="/<?php echo rotate('campaign1'); ?>">
</a>
other like this:
<a target="_blank" href="http://intellibanners.com/click.php?cid=campaign2">
<img border="0" src="/<?php echo rotate('campaign2'); ?>">
</a>
and so that...
You have only to create the wished folders in the root called campaign1, campaign2...etc...
then in each folder put the banner images of the current campaign...
for example: in the folder campaign1 put image like 001.png, 002,png, 003.png, 004.jpg, 005.jpg... (where these filenames match your campaign banners).
for example: in the folder campaign2 put image like 001.png, 002,png, 003.png, 004.jpg, 005.jpg, 006.gif, 007.png, 008.jpg... (where these filenames match your campaign banners).
Please note that if you don't want rename your banner images you can take the original names, my script will work in any way.
My script will turn all in wished output like this:
campaign1:
<a target="_blank" href="http://intellibanners.com/click.php?cid=campaign1">
<img border="0" src="/campaign1/002.jpg">
</a>
<a target="_blank" href="http://intellibanners.com/click.php?cid=campaign1">
<img border="0" src="/campaign1/007.jpg">
</a>
campaign2:
<a target="_blank" href="http://intellibanners.com/click.php?cid=campaign2">
<img border="0" src="/campaign2/004.png">
</a>
<a target="_blank" href="http://intellibanners.com/click.php?cid=campaign2">
<img border="0" src="/campaign2/005.gif">
</a>
See you and test all into your localhost website... for me works fine on PHP 7.4.5 and Apache 2.4.43.
The script will do the rest!
Hope this helps you!

Image display with <img src=""> not working

EDIT :: I found out that i am having a permission error. For whatever reason i dont have "permission" to grab the image from the images folder ... *
a few days ago i asked this question about uploading images and was very satisfied with the anwser. I integrated it into my site and it works no problem.
Image - Upload not responding, no access to $_FILES
The problem i am having now is i cannot retrieve the images in any way shape or form. I have tried opening them and setting them to read, with fopen($image, r). I tried even more complicated things like loading the image back into a database ... then it hit me that the anwser is simple.
I CAN see the image in my images folder, so should work no problem. But it doesnt =(
Here is the PHP script one more time,
if (isset($_FILES['fupload'] ))
{
$max_size = mysql_real_escape_string(strip_tags($_POST['MAX_FILE_SIZE']));
$file = $_FILES['fupload']['name'];
if(isset($max_size) && !empty($max_size) && !empty($file)) {
$file_type = $_FILES['fupload']['type'];
$tmp = $_FILES['fupload']['tmp_name'];
$file_size = $_FILES['fupload']['size'];
$allowed_type = array('image/png', 'image/jpg', 'image/jpeg', 'image/gif');
if(in_array($file_type, $allowed_type)) {
if($file_size < $max_size) {
$path ='images/'.$file;
$move = move_uploaded_file($tmp, $path);
$sql = "UPDATE info.profile SET Profile_pic='".$move."', pic_name='".$file."' WHERE Nick='".$_SESSION['Nick']."'";
mysql_query($sql) or die ("Error: " .mysql_error());
$_SESSION['pic'] = $path;
echo "image added successfully :) :) :) ";
}
I left out all the else statements, since they are not relevent. The folowing is an example of where the image should be displayed.
<td rowspan=2 align=center width=100px> <img src="<?php $_SESSION['pic']; ?>"
alt="Here would be the picture, if it was working !!"> </td>
The alt is a small teaser of course, but i have tried everything and with the current script i managed to get the alt text to display. Sometimes a "bad image" icon displayes (like when you open images in an email before allowing images to be displayed)
When i echo the path it shows the "right" path, just like i would enter when manualy giving it in. The reason i store the path in DB and in a session is because the image is a profile image and should only be displayed for THAT user ... wouldnt want other users having other images as their profile pic. =)
Did you cross check the file permission issue?
What is the response code return when you copy and paste the image path to the browser?
e.g. http://yourserver.com/part-to-image/image.jpg
If 404 returned, you may need to troubleshoot the server directory mapping.
If 500 returned, might be file permission.
Apart from that your code
<?php $_SESSION['pic']; ?>
Should it require echo to embed to html tag?
<?php echo $_SESSION['pic']; ?>
The path should be relative to the current directory. Have u checked it ?
Try the answer given in comment by Rohit.
<img src='<?php echo $_SESSION['pic']; ?>' />

Glob function output all files

Hi I am using this code to output image from a file called images
<?php
//Path to folder which contains images
$dirname = $_POST['dir'];
//Use glob function to get the files
//Note that we have used " * " inside this function. If you want to get only JPEG or PNG use
//below line and commnent $images variable currently in use
$images = glob($dirname."*");
//Display image using foreach loop
foreach($images as $image) {
//print the image to browser with anchor tag (Use if you want really :) )
echo '<p><img style="height:176px; width:221px; float:right;" src="'.$image.'" /></p>';
}
?>
I called it image.php and I used this form to make the user choose the directory
<form method="POST" action="image.php">
<input type="text" name="dir" placeholder="choose directory" />
<input type="submit" value="choose" />
</form>
when I run the code it output all files in the folder I have files like test.php and files as js and css and a file called images what happening is when I run it output the js and css and all .php file put it's not output the images what the error
That is extremely dangerous. Anyone can type whatever folder they want and immediately see (and in the case of PHP files, execute) all files in that directory.
Note the comment in your code about "only want JPEG or PNG", well you can do this:
$images = glob($dirname."*.{png,jpg,jpeg,gif}",GLOB_BRACE);
This will only allow image files of those types.
You should also be aware that glob is NOT recursive. You have to manually recurse through directories for that.
Or this, if you don't want to filter the extensions:
//Path to folder which contains images
$dirname = $_POST['dir'];
//Use glob function to get the files
//Note that we have used " * " inside this function. If you want to get only JPEG or PNG use
//below line and commnent $images variable currently in use
$images = glob($dirname."/"."*");
//Display image using foreach loop
foreach($images as $image) {
//print the image to browser with anchor tag (Use if you want really :) )
echo '<p><img style="height:176px; width:221px; float:right;" src="'.$image.'" /></p>';
}

Get images one by one from directory

in php i want to ask how to get images one by one from folder directory and display in the jquery slider i have tried this php code by it's not working as i want?
<ul class="jcarousel-list">
<li class="jcarousel-item">
<?php
$directory = "data/uploads/topslider/";
if (glob($directory . "*") != false)
{
$filecount = count(glob($directory . "*"));
}
else
{
}
$files_index = glob("data/uploads/"."top"."slider/*.*");
for ($i=0; $i<$filecount; $i++)
{
$num2 = $files_index[$i];
?>
<img src="<?php echo $num2;?>" width="50" height="50" alt="" /> <?
}?></li>
</ul>
i want display like this:
Image1 Imag2 Image3......and So On from single folder or directory
There are four main things to check:
Is your $directory path correct relative to your current working directory in PHP? You can determine your current working directory by doing a temporary echo getcwd();. It needs to return the parent directory of your "data" folder for your code to work.
Is the data folder accessible from the current page on the web? e.g. if you manually remove the page from the URL (say, index.php) and add data/uploads/topslider/someimage.png where someimage.png is an image you know exists in your topslider folder, does the image load properly in the browser? If not, you'll need to update the way you build the src attribute in your img tag(s).
You're only adding one jcarousel-item for all your images, which doesn't seem right to me. I'm guessing you're expected to add a list item for each image.
You don't need to call glob twice just to ascertain how many files you have to work with. Just do a foreach statement once:
echo '<ul class="jcarousel-list">';
foreach(glob($directory . '*') as $filename) {
echo '<li class="jcarousel-item"><img src="'.$filename.'" width="50" height="50" alt="" /></li>';
}
echo '</ul>';

Categories