Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file_exists not working

Tags:

php

I'm trying to make profile photos show up against a list of reviews on a site I'm working on. If they don't have a profile photo I have a standard image to show instead, unfortunately the image always goes to the standard image rather than the profile even if it exists. Heres the code:

$reviewerPic = 'http://www.[URL].co.uk/images/members/' . $reviewPosterId . '/profilePic.jpg';
$default_pic = 'http://www.[URL].co.uk/images/background.jpg';
    if(file_exists($reviewerPic)){
        $reviewer_pic = '<img src="' . $reviewerPic . '" width="100px" style="float: left; margin: 20px;" />';
    }else {
        $reviewer_pic = '<img src="' . $default_pic . '" width="100px" style="float: left; margin: 20px;" />';
}

Pretty generic code but it doesn't seem to work! It just keeps showing the background image...

Any ideas on why file_exists wouldn't be working?

like image 647
JackWillDavis Avatar asked Jun 06 '12 11:06

JackWillDavis


People also ask

How do you check if a file already exists in PHP?

The file_exists() function checks whether a file or directory exists.

How create file if not exist in PHP?

PHP Create File - fopen() The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

How do you check whether a file exists or not?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .


1 Answers

The function you are using, file_exists, uses physical paths, the parameter you need to provide should be the address on that server where the file can be found, and not an url

Sou you should have something like

/home/var/www/images/

instead of

http://www.[URL].co.uk/images/

So you need to check if the file exists on the server locally and after that you can use an url to make it available to the public (in img src)

You can see on the man page that this function only works with some URL wrappers, so it is better to use paths and not urls (I guess it depends on allow url fopen setting)

like image 107
mishu Avatar answered Oct 16 '22 19:10

mishu