File_exist在Symfony 2上一直返回false

Im trying to check if a file exist on my /uploads folder of symfony 2.

    $file = $this->getAssetUrl('/uploads/hd/'.$gift->getImage());
     if(file_exists($file)) return $this->getAssetUrl('/uploads/hd/'.$gift->getImage());
     else return $this->getAssetUrl('/uploads/large/'.$gift->getImage());

This is always returning false, i debugged all the strings and the paths are correct, checked by hand that the file exist. Any ideas?

getAssetUrl will only print the URI of whatever resource it is you're printing, not the actual location.

If you placed your project at /var/www/myProject, the path file_exists expects is /var/www/myProject/web/uploads/hd/, but it will only get /uploads/hd. It'll look for a folder called "uploads" in your root directory. The first slash ("/") means "system root dir" for PHP, while it means "root URI" for your browser.

I believe if (file_exists($this->get('request')->getBasePath() . "/uploads/hd/" . $gift->getImage())) should do the trick.

getAssetUrl is not returning a valid filename. It will give you a URL instead.

You must provide file_exists with a path (relative or absolute), so, you should use something like:

$file = dirname(__FILE__).DIRECTORY_SEPARATOR.'..'
              .DIRECTORY_SEPARATOR.'..'
              .DIRECTORY_SEPARATOR.'uploads'
              .DIRECTORY_SEPARATOR.'hd'
              .DIRECTORY_SEPARATOR.$gift->getImage();

Of course, adapt the path to your needs.