tags:

views:

99

answers:

6
<?
$user_image = '../images/users/' . $userid . 'a.jpg';
if (file_exists($user_image)) 
{
    echo '<img src="'.$user_image.'" alt="" />';
} 
else 
{
    echo '<img src="../images/users/small.jpg" alt="" />';
}
?>

Hello all, this code is supposed to check for a file and if it doesnt work, display another. For some reason it is ALWAYS displaying the placeholder and never finds the initial file even though it is there. Is there something obviously not right here? Thanks for reading!

+4  A: 

the PHP is running in a different directory. try echo getcwd();

just somebody
+2  A: 

If your relative path points outside of the htdocs subdirectories, then the image will not be sent by the webserver

Mark Baker
+4  A: 

file_exists does not work with relative paths. Try something like this:

$user_image = $_SERVER{'DOCUMENT_ROOT'}.'/../images/users/' . $userid . 'a.jpg';
if (file_exists($user_image))
// blah blah

But, as Artefacto suggests, it's better to use the real path:

$user_image = '/path/to/your/files/images/users/' . $userid . 'a.jpg';

It's easier to maintain since you can use that code on different PHP scripts located on different directories without having to change anything.

Cristian
http://www.php.net/manual/en/function.file-exists.php#93572
DeaconDesperado
thanks... I'm adding that example right now.
Cristian
why not `realpath`?
Artefacto
I'll read that cheers
Luke
"file_exists does not work with relative paths": that's simply wrong, and easily refuted with `var_dump(file_exists("."));`
just somebody
A: 

I mean I'm not always the smartest with php, but is your concat location correct? Because right now, won't it resolve to /images/users/userida.jpg ? is this really what you want?

cwill747
No, it will resolve to: '../images/users/123a.jpg' if $userid is '123'
Blair McMillan
right, that's exactly what I was saying. just forgot the ..
cwill747
That's what he wants though.
Blair McMillan
A: 

I think you should check to see what realpath('../images/users/' . $userid . 'a.jpg') returns. I get the feeling it has something to do with the relative path

Dennis Haarbrink
+1  A: 

Try using realpath and dirname instead.

<?
$user_image = '../images/users/' . $userid . 'a.jpg';
if (file_exists(realpath(dirname(__FILE__) . $user_image))) 
{
    echo '<img src="'.$user_image.'" alt="" />';
} 
else 
{
    echo '<img src="../images/users/small.jpg" alt="" />';
}
?>
Blair McMillan
Cheers bud, this works.
Luke