开发者

Get the right path to the file

I store user images in "images" forlder and the full path is something like this:

http://example.com/images/imagename.jpg

When I t开发者_如何转开发ry to get the image path like this:

$path = 'images/imagename.jpg';

it works fine on home page, but since I have different permalink structure it doesn't work on other pages. It becames something like http://example.com/something/images/imagename.jpg

Of course I can write:

$path = 'http://example.com/images/imagename.jpg';

but in this case

file_exists($path)

always returns false even if the file exists. It's a problem!

Can anyone please help?


Try $path = '/images/imagename.jpg; that way you're are referencing from the document root path.


I would use parse-url and get the "path" argument as following:

<?php
  $url_tab = parse_url($path);
  echo $url_tab['path'];
?>

So you can keep the full version and get the path argument.

Otherwize, you can keep the absolute path, and use the $_SERVER['SERVER_NAME'] to concatenate the path and get the full url.


file_exists should check for existance of file in filesystem, while html images should use url (whether they are relative or absolute). There should be no confusion between to, and as you noticed it using same variable for both could lead to issues.

You can use some constants to define you application root path. If you use a front controller at the root dir of your project

define('APP_PATH', dirname(__FILE__));

Or you can use little helper functions to get your image path and url separately, something to use in your view/template files

get_image_path($fileName);
get_image_uri($fileName);

this way you can easily move images files elsewhere and keep your existants url the same, or change urls without actually moving files in file system.


You've almost got it. path ought to be absolute (i.e. starting from /) from the web root.
so, to check existence of the file, you have to extend it's path to absolute from the filesystem root.

$path = '/images/imagename.jpg';
if (file_exists($_SERVER['SERVER_NAME'].$path)) {
  echo "<img src=\"$path\">";
}

So, this would work for any part of the site and pass existence check. Always stuck with absolute paths, it will never fail you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜