2010-01-20 23 views
1

我需要在我正在構建的web應用程序中實現一個簡單的PHP代理(其基於Flash並且目標服務提供程序不允許對其crossdomain.xml文件進行編輯)構建一個簡單的php url代理

任何PHP大師能提供關於以下2個選項的建議嗎?另外,我認爲,但我不確定,我還需要包含一些標題信息。

感謝您的任何反饋!

選項1

$url = $_GET['path']; 
readfile($path); 

選項2

$content .= file_get_contents($_GET['path']); 

if ($content !== false) 
{ 

     echo($content); 
} 
else 
{ 
     // there was an error 
} 
+0

哇。我認爲我的眼睛受傷了。請轉義'$ _GET'參數。 – Franz 2010-01-20 17:04:26

回答

5

首先,永遠不包括僅基於用戶輸入的文件。試想一下,如果有人打電話給你這樣的腳本會發生什麼:

http://example.com/proxy.php?path=/etc/passwd

然後到這個問題:什麼樣的數據,你進行代理?如果有任何形式的話,那麼你需要從內容中檢測出內容類型,並將其傳遞給接收方,以便知道接收到的內容。如果可能的話,我會建議使用類似HTTP_Request2或類似Pear的東西(請參閱:http://pear.php.net/package/HTTP_Request2)。如果您可以訪問它,那麼你可以做這樣的事情:

// First validate that the request is to an actual web address 
if(!preg_match("#^https?://#", $_GET['path']) { 
     header("HTTP/1.1 404 Not found"); 
     echo "Content not found, bad URL!"; 
     exit(); 
} 

// Make the request 
$req = new HTTP_Request2($_GET['path']); 
$response = $req->send(); 
// Output the content-type header and use the content-type of the original file 
header("Content-type: " . $response->getHeader("Content-type")); 
// And provide the file body 
echo $response->getBody(); 

請注意,此代碼沒有經過測試,這只是給你一個起點。

+0

真的很感激反饋!將作爲一個起點,讓你知道它是如何發展的。 我不是一個php編碼器,但會認爲有很多情況下,需要這種類型的代理... – 2010-01-20 21:25:43

+0

只是1語法錯誤我發現,缺少關閉括號上的if(!.... line 我還發現需要在我的服務器上安裝一個缺少的HTTP_Request2 php類 – 2010-01-20 22:49:05

+0

您也使用'new HTTP_Request2($ _ GET ['path'])''這是否有一些內部驗證,或者是否應該添加類似內容, – Franz 2010-01-20 23:13:17

0

這是另一種使用捲曲的解決方案 任何人都可以評論?

$ch = curl_init(); 
$timeout = 30; 
$userAgent = $_SERVER['HTTP_USER_AGENT']; 
curl_setopt($ch, CURLOPT_URL, $_REQUEST['url']); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); 

$response = curl_exec($ch);  
if (curl_errno($ch)) { 
    echo curl_error($ch); 
} else { 
curl_close($ch); 
echo $response; 
}