Nasıl dosya PHP uzantısı olmadan olup olmadığını kontrol etmek?

4 Cevap php

Ben link ". Php" dosya uzantısı belirtmek istemiyorum. Ama ne zaman ben başarılı bir bağlantı belirtilen dosya var olup olmadığını görmek için kontrol edemez. PHP'nin "File_exists" işlevi inşa dikkate. Php uzantısını alır çünkü bu. Ve hatta bu işe yaramazsa:

(".. php" $ dosya) File_exists;

Neyse, html bağlantıları php uzantısı speciding olmadan şu işi yapmak için bir yol var:

<a href="?file=dude">Some File</a>

<?php

$file = $_GET['file'];

if(file_exists($file.".php"))
{
     include($file.".php");
}
else
     include("404.php");


?>

4 Cevap

Sizin örnek (I unstriked the previous again as per EDIT 2), dosya (ben sadece şu andan itibaren CWD'sindeki bu kısaltmak edeceğiz) geçerli çalışma dizini koşuluyla sadece iyi çalışması gerekir.

EDIT
Sorry, what was I thinking. Your example doesn't work of course, because file_exists() should be provided with the full path to the file. So prepend the file with the directory you want to pull the files out of the directory. My warning about sanatizing and whitelisting, etc. still count nonetheless though.
END EDIT

EDIT 2
Wow, sorry, I'm messing up bigtime. file_exists() should work just fine with relative paths. Looking at the documentation, it does however warn about safe mode restrictions. Maybe these apply to your situation, I don't know.
END EDIT 2

Sen getcwd() ile cwd ne olduğunu test edebilirsiniz. Normal şartlar altında cwd uygulamanın giriş noktası olarak aynıdır. Örneğin /usr/www/your_site_root/index.php giriş noktasıdır Yani, eğer, o zaman /usr/www/your_site_root/ cwd olduğunu.

O halde size örneklerle eklemeyi deneyin dosyalar bulunması gereken dizin söyledi.

A word of advice though:
You may be aware of this already, but your example is not very secure. You don't sanitize the input from the user in any way ($_GET[ 'file' ] in this case). This way, the visitor will be able to include all sorts of php files with unwanted results.

Eğer getirilen izin dosyaların bir beyaz liste tutmak için bunun I'ld tavsiye. Gibi bir şey:

<?php

$whiteList = array(
    'dude',
    'chick',
    'mom'
);

// and just to be safe, you should probably strip stuff like ../ etc. here too.
$requestedFileBaseName = $_GET[ 'file' ];

if( !in_array( $requestedFileBaseName, $whileList ) )
{
    include( '404.php' );
}
else
{
    include( $requestedFileBaseName . '.php' );
}

. Url yeniden yazma ile deneyin, htaccess dosyasına ekleyin:

RewriteCond %{DOCUMENT_ROOT}/$1.php -f 
RewriteRule ^/(([^/]+/)*[^.]+)$ /$1.php [L]

. Php uzantısını belirterek önlemek için PHP'nin glob işlevini kullanın. Ancak bu bir güvenlik sorunu neden olabilir:

http://ar2.php.net/glob

glob($file . ".*")

kullanın:

$file = dirname(__FILE__).'/../relativepathfromcurrentscript/'.$_GET['file'].'.php';