English 中文(简体)
Check if files with absolute and relative path exists
原标题:
  • 时间:2009-11-13 16:57:47
  •  标签:
  • php
  • path

Is there a way to check whether files (with either an absolute or relative path) exists? Im using PHP. I found a couple of method but either they only accept absolute or relative but not both. Thanks.

最佳回答

file_exists($file); does the trick for both relative and absolute paths.

What s more useful, however, is having absolute paths without hardcoding it. The best way to do that is use dirname(__FILE__) which gets the directory s full path of the current file in ether UNIX or Windows format. Then we can use realpath() which conveniently returns false if file does not exist. All you have to do then is specify a relative path from that file s directory and put it all together:

$path = dirname(__FILE__) .  /include.php ;
if (realpath($path)) {
    include($path);
}
问题回答

You can use realpath to check if a file exists to the given path and retrieve the expanded path to that file:

$absPath = realpath($path);
if ($absPath === false) {
    // invalid path
}

file_exists($path) will check absolute path or relative to the script location. If you want to check relative to document root you could try file_exists("{$_SERVER[ DOCUMENT_ROOT ]}path");

If you want a function that will take both relative and absolute paths something like this should work (untested):

function check_file($path) {
    return ( file_exists($path) || file_exists("{$_SERVER[ DOCUMENT_ROOT ]}path") );
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签