【问题标题】:building a 'simple' php url proxy构建一个“简单”的 php url 代理
【发布时间】:2010-01-20 16:27:15
【问题描述】:

我需要在我正在构建的 Web 应用程序中实现一个简单的 PHP 代理(它基于 Flash,并且目标服务提供商不允许编辑他们的 crossdomain.xml 文件)

任何 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
 }

【问题讨论】:

  • 哇。我觉得我的眼睛很痛。请转义 $_GET 参数。

标签: php proxy php4 proxy-classes


【解决方案1】:

首先,永远不要包含仅基于用户输入的文件。想象一下如果有人这样调用你的脚本会发生什么:

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();

请注意,此代码尚未经过测试,这只是为您提供一个起点。

【讨论】:

  • 非常感谢您的反馈!!将用作起点,让您知道它是如何进行的。我不是 php 编码器,但会认为有很多情况需要这种类型的代理...
  • 我只发现了 1 个语法错误,if(!.. 行缺少右括号而且我还发现需要在我的服务器上安装缺少的 HTTP_Request2 php 类
  • 你也在使用new HTTP_Request2($_GET['path'])'。这是否有一些内部验证,或者你是否也应该添加类似的东西。
  • Franz:首先用 preg_match 评估路径,看它是否真的是一个 URL,见脚本的第一行。
  • 我只想指出,正则表达式应该以 ^ 开头以将其锚定到字符串的开头 - 否则有人仍然可以通过将“http”部分隐藏在附近的某个地方来读取文件文件名的结尾(可能在“:”或空格之后)。
【解决方案2】:

这是另一个使用 curl 的解决方案 有人可以评论吗?

$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;
}

【讨论】:

    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多