PHP if file exists not working - php

I am using a simple script that displays images in a jquery slideshow - these image filenames are listed in a .txt file, and change depending on the page you are on (im also using pagination in another script).
If the filename that is listed in the .txt file doesn't exist, I would like the image 'unavailable.jpg' to display instead...
The original script:
<?php
echo"
<div id='slider-wrapper'><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>
"?>
And here is my try at it...but it doesn't work properly- instead of the 'unavailable.jpg' image being displayed, it shows all of the images in the directory... :S Anyone have any ideas of what I might be doing wrong? :S
<?php
echo"
<div id='slider-wrapper'><div id='slider' class='nivoSlider'>";
$photos=file("photos.txt");
foreach($photos as $image){
$item=explode("|",$image);
$photo=trim($item[1]);
if (file_exists("images/work/".$photo)) {
echo"<img src='images/work/$photo' alt='' />\n";
}
else{
echo"<img src='images/work/unavailable.jpg' alt='' />\n";
}
}
echo"
</div>
</div>
"?>
Instead of all the images showing, I only want images for that page to display. Here is an example of my text file:
1|image1.jpg
1|image2.jpg
1|image3.jpg
2|image1.jpg
2|image2.jpg
The 1 and 2 are for the pages 1 and 2, and they display the images that are listed. This all works fine in the above original script that I have posted, but it seems to break when I add the if file_exists.

The path to your images uses a relative path. Are you sure the current working directory is the directory you think it is?
To verify do an echo 'Current Working Directory: '.getcwd()."<br />\n" and verify what directory you are in.
Its probably best to use a full file path to your image's directory so the script can be placed anywhere on your server.
Now if that is correct then you need to check that your script has permission to your image directory. Typically php runs as nobody:nobody or apache:apache depending on your configuration.
The directories above as well as the files should have 644 (-rw-r--r--) or at a minimum 444 permission (-r--r--r--).
Try these two things and let us know if that solved your specific problem or not; I hope it does.

You need to re-add the test for $item[0] == $fields[0]:
<?php
echo "<div id='slider-wrapper'><div id='slider' class='nivoSlider'>";
$photos = file("photos.txt");
foreach ($photos as $image) {
$item = explode("|",$image);
$photo = trim($item[1]);
if (file_exists("images/work/".$photo)
&& $item[0] == $fields[0]
) {
echo "<img src='images/work/$photo' alt='' />\n";
} else {
echo "<img src='images/work/unavailable.jpg' alt='' />\n";
}
}
echo "</div></div>";
?>
Edit:
I just noticed that Ott pointed this out already in the comments. Are you still having the issue with unavailable.jpg?

Related

PHP dynamically change filename

I was able to get some help earlier today, but I didn't have everything from the original script for it to work. Basically I have a list of image file names in a .txt file. They each load in a slideshow, and change with the pagination on the page.
What I would like to do, is if I have a file that has a .mov extension, for example, the php script will load a movie player instead.
Here is the original slideshow script
<div id='jessslide'>
<?php
echo"
<div id='slider-wrapper'>
<div id='slider' class='nivoSlider'>";
$photos = file("work.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>"
?>
</div>
And here is my bad attempt at trying to make this work...
<div id='jessslide'>
<?php
$photos = file("work.txt");
$img = array('jpg', 'png', 'gif');
$vid = array('swf', 'mp4', 'mov', 'mpg', 'flv');
foreach ($photos as $image) {
$item = explode("|", $image);
if ($item[0] == $fields[0]) {
$photo = trim($item[1]);
$ext = explode(".", $image);
if (in_array($ext[1], $img))
{
echo "<div id='slider-wrapper'><div id='slider' class='nivoSlider'><img src='images/work/$photo' alt='' /> </div></div>";
}
elseif (in_array($ext[1], $vid))
{
echo "<iframe src='$photo' width='800' height='450' frameborder='0' webkitAllowFullScreen allowFullScreen></iframe>";
}
}
}
?>
</div>
I would really appreciate if someone could help me out to finally bring this script to life! :)
The most likely problem I see is the possibility that the assignment to $ext should be tied to $item or $photo instead of $image. If that solves it, then great. Otherwise, read below for a more complete analysis and some suggestions for steps to debug until you narrow in on the cause of the problem.
Assuming all of the data is accurate, the script you've written looks like it should work. I've reformatted it here to conduct some analysis:
<div id='jessslide'>
<?php
$photos=file("work.txt");
$img = array('jpg', 'png', 'gif');
$vid = array('swf', 'mp4', 'mov', 'mpg', 'flv');
foreach($photos as $image){
$item=explode("|",$image);
if($item[0]==$fields[0]){
$photo=trim($item[1]);
$ext = explode(".", $image);
if(in_array($ext[1], $img))
{ echo "<div id='slider-wrapper'><div id='slider' class='nivoSlider'><img src='images/work/$photo' alt='' /> </div></div>"; }
elseif(in_array($ext[1], $vid))
{ echo "<iframe src='$photo' width='800' height='450' frameborder='0' webkitAllowFullScreen allowFullScreen></iframe>"; }
}
}
?>
</div>
There are three major places in this script for problems to occur that would cause nothing to be output.
The first is in the foreach() loop. If the $photos array has nothing in it, you would skip the entire block of code. You can test for this condition by adding a print_r($photos); before the foreach() and then as the first line in the body of the foreach() add echo $image." "; to verify that all the files are listed as you expect. If that looks correct, remove that debugging code and move on.
The 2nd potential for problems is if the $item[0] is not equal to $fields[0]. To test this, add echo 0; as the first line inside if($item[0]==$fields[0]). If you see zeros as expected when the script is run, then you can remove this debugging code and move on.
The 3rd potential for problems is pull/examination of the extension. One likely candidate for problems here is if the assignment to $ext should be tied to $item or $photo instead of $image but there are definitely other possible issues. To test this, add echo $image." ".$ext[1]."\n"; print_r($img); print_r($vid); before the if(in_array($ext[1], $img)). Then add a temporary else clause with the body of echo 3; as well. Verify that th
Once you figure out which condition in the code is causing problems, you will be well on the way toward solving it. My guess is that you'll get through the tests and either find an obvious mistake in one of the early sections that we are assuming works right, or you will end up with 3 being printed out a lot. In the later case, one possible issue could come from lower/upper-case differences, which could be solved via changing the $item assignment to $item=strtolower(explode("|", $image);

PHP: if image exists show image else show different image

i am making a login system with registration and a profile page in php and i am trying to make a profile picture work.
if the user has not uploaded a profile picture yet then make it show a "no profile picture" image if the user has uploaded a profile picture make make it show the image that he has uploaded.
Right now it only show the default picture, noprofile.png.
< img src="uploads/< ? echo "$username" ? >/noprofile.png">
i want it to show icon.png if icon.png has been uploaded and if it hasnt been uploaded make it show, noprofile.png.
Just run it through the logic, using file_exists:
$image="/path/on/local/server/to/image/icon.png";
$http_image="http://whatever.com/url/to/image";
if(file_exists($image))
{
echo "<img src=\"$http_image\"/>\n";
}
else
{
echo "<img src=\"uploads/$username/noprofile.png\"/>\n";
}
Check to see if the file has been uploaded by using file exists. If the file exists, use that url else use the default noprofile.png.
you could make a column in the DB to store a value if it has been uploaded or not.
OR
you could see if the file exists.
<?php
if (file_exists('uploads/' . $username . '/icon.png')) {
echo '<img src="uploads/' . $username . '/icon.png">';
}
else {
echo '<img src="uploads/' . $username . '/noprofile.png">';
}
?>
<?php
$img = file_exists(sprintf('/path/to/uploads/%s/icon.png', $username))
? 'icon.png' : 'noprofile.png';
?>
<img src="uploads/<?php printf('%s/%s', htmlspecialchars($username), $img) ?>">
You could use http://us3.php.net/file_exists to check if the image file is there.
Another alternative is - assuming you keep your user info in a database - have a column with the image name. Since you have to retrieve info from your user table anyway, check to see if that column is NULL or blank. If it is, the user has not uploaded an image yet.
Then, in the page you display the user photo, you might have code something like this:
$userPhoto = ($photoName)? $photoName : 'placeholder';
echo '<img src="uploads/'.$userPhoto.'.png" />
Assuming the filepaths are correct, here's what you do...
<?php $filename = "uploads/".$username;
$imgSrc = file_exists($filename) ? $filename : "uploads/noprofile.png"; ?>
<img src=<?php echo $imgSrc?>
Use onerror attribute in img tag
<img onerror="this.src= 'img/No_image_available.png';" src="<?php echo $row['column_name ']; ?>" />

echo file if it exist. if not echo "default.png" php

I have a script that echo's usernames an inserts that into img src. This works great as long as the image is in the directory. How can I create an if statement that only echos the below command if the file exist? If it doesn't exist show default.png
I tried using mod_rewrite and have had zero luck with it..
<div class="contactphoto"><img src="contactphoto/<? echo ($note['user_name'] == "Support")? $note['first_name'].''.$note['last_name'] : $note['user_name'];?>.png"/></div>
The name says it all: file_exists()
I think this is what you want.
<?php
$file = ($note['user_name'] == "Support") ? $note['first_name'].''.$note['last_name'] : $note['user_name'];
$file .= '.png';
if(!file_exists($_SERVER{'DOCUMENT_ROOT'} .'/'.$file)){
$file = 'placeholder.png';
}
?>
<div class="contactphoto">
<img src="contactphoto/<?php echo $file; ?>"/>
</div>
If that fails, try a test ( this should match the path of the image ) also watch out for case sensitivity:
echo $_SERVER{'DOCUMENT_ROOT'} .'/'.$file;

check file exist with php isn't working, need help

Please advise me, what wrong with my following code:
<a href="<?php echo $_url; ?>" title="<?php echo $_name; ?>">
<?php
$logo2 = $_url.'/image/data/logo2.png';
$logo = $_url.'/image/data/logo.png';
if (file_exists($logo2)) {
echo "<img src=".$logo2." alt=\"Logo\" style=\"border: none;\" />";
} else {
echo "<img src=".$logo." alt=\"Logo\" style=\"border: none;\" />";
} ?>
</a>
both images of $logo2 and $logo exists in the same directory, but the code only shows $logo (logo.png)
I need pointers and thanks in advance
UPDATED:
the value of $_url is
$this->data['_url'] =
$this->config->get('config_url');
and when i <?php echo $_url;?> that will show e.g. http://www.mysite.com
by using code at above only show logo.png
file_exists can be used for URL wrapper.
In your case, if you really need to perform URL wrapper checking (will be very slow), make sure URL wrapper is enabled (default is enabled).
And also, your $_url = http://www.mysite.com///image/data/logo2.png, take note the extra slash may affecting web server rewrite.
If the file is located at the same server as your web server, you should replace the $_url to document_root (path to the folder).
For function wise, file_exists return true for directory too. You should replace that to is_file
You are applying file_exists() to a URL which doesn't work.
You need to apply it to a filesystem path.
file_exists expects a local path, not a url.
Contrary to some answers here, file_exists can take an URL as a parameter and it will check whether it exists or doesn't. However, you're still better off using a filesystem path for file_exists instead of the URL.
Anyway, two reasons immediately come to mind:
Do both files have the same permissions? (I.e., logo.png might have the necessary read permissions and logo2.png might not have them)
Are the file names really the same as in the script? For example, everything might work fine on your development platform - a Mac or Windows which ignores letter case for filenames but not on a Linux server where the filename must be in the same case.
Use getimagesize() as file_exists will return false.
<a href="<?php echo $_url; ?>" title="<?php echo $_name; ?>">
<?php
$logo2 = $_url.'/image/data/logo2.png';
$logo = $_url.'/image/data/logo.png';
if (getimagesize($logo2)) {
echo "<img src=".$logo2." alt=\"Logo\" style=\"border: none;\" />";
} else {
echo "<img src=".$logo." alt=\"Logo\" style=\"border: none;\" />";
} ?>
</a>

php - Decide whether an image exist and if it does show it

I have a code that shows a different image depending where on the page I am, but some places don't have an image so it displays a "no image" icon. I want to add a condition that checks if there really is an image in the given path and if returns false don't do anything. I have no idea how to do it.
This is the original code:
<?php
$search=get_search_query();
$first=$search[0];
if ($first=="#"){
echo "<html>";
echo "<img src='http://chusmix.com/Imagenes/grupos/".substr(get_search_query(), 1). ".jpg'>";
}
?>
What I need to know is which function do I use to get a true/false of that image path. Thanks
Use file_exists
$image_path = 'Imagenes/grupos/' . substr(get_search_query(), 1) . '.jpg';
if (file_exists($image_path)) {
echo "<img src='http://chusmix.com/Imagenes/grupos/".substr(get_search_query(), 1). ".jpg'>";
} else {
echo "No image";
}
http://php.net/manual/en/function.file-exists.php
You can use file_exists

Categories