2009-06-27 39 views
0

有誰知道PHP RegEx只允許相對路徑,而不是絕對路徑?例如,我有一個AJAX函數,它將這個值提交給我的PHP腳本「some-directory/another-directory/some-file.php」。我的PHP腳本然後包括該文件.... include($ some-php-document);初學正則表達式問題 - PHP RegEx僅允許相對路徑(非URL)

我不想一個黑客能夠使用我的AJAX功能提交類似:「http://www.malicious-website.com/malicious-script.php

在我的PHP文件,我想這樣做:

<php> 
$some-php-document = $_POST["some_value_submitted_via_ajax"]; 

//if $some-php-document is a URL (not a relative path to a file), 
    //then $some_php_document = null 

//how can I use a php regex to accomplish the above? 

</php> 

我怎樣才能做到這一點?

或者,讓我知道是否有更安全的解決方案。

回答

2

我會用parse_url()功能,而不是一個正則表達式,像這樣:

<?php 
$some_php_document = $_POST["some_value_submitted_via_ajax"]; 

$parsed_doc = parse_url($some_php_document); 

//if $some-php-document is a URL (not a relative path to a file), 
    //then $some_php_document = null 
if (isset($parsed_doc['scheme']) || isset($parsed_doc['host'])) { 
    $some_php_document = null; 
} 

?> 

的文件路徑將會在$ parsed_doc [「路徑」。在使用前應進行檢查,因此攻擊者不能說/請求/ etc/passwd或一些類似敏感的文件。

0

您可以在字符串中測試://如果存在,則拒絕。如果你想有一個負的正則表達式,你可以試試:

​​

如果匹配,該字符串是相對的(儘管可能是畸形)。

+0

在URL中不需要協議。 //otherserver.com/script.js是有效的。 – 2009-06-27 18:07:17

+0

你確定嗎?我只是在我的瀏覽器中輸入該地址,並自動填充文件:// – Blindy 2009-06-27 20:06:25

3

不允許上傳文件名來指定包含。相反,這樣做:

$valid_files = array(
    'file1' => 'file1.inc', 
    'file2' => 'john.inc', 
    'fred' => 'bob.inc', 
); 

$requested_include = trim(strtolower($_POST["some_value_submitted_via_ajax"]))); 
if (!array_key_exists($requested_include, $valid_files)) { 
    $requested_include = "file1"; 
} 
include WEB_ROOT_PATH . 'templates/whatever/' . $valid_files[$requested_include]; 

驗證所有輸入,無需使用正則表達式 - 這是很難得到正確,你如上面是有嚴格的安全解決方案更好。