PHP网页请求返回400错误请求

时间:2011-02-07 10:13:16

标签: php

我尝试过使用fopen,file-get-contents和curl请求,但我总是得到400 Bad Request返回。这是一个简单的网页请求与GET参数。这是我的代码,任何人都可以看到为什么这会导致问题?的phpinfo();显示配置允许这些类型的请求。

function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
$this->headers = array(
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, image/gif, image/x-bitmap, image/jpeg, image/pjpeg',
    'Connection: Keep-Alive',
    'Content-type: application/x-www-form-urlencoded;charset=UTF-8'
);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;
}

...

        $forwardURL = '*****/receive?from='.$_GET["from"].'&msg='.$_GET['msg'].'&username='.$_GET['username'].'&ac_password='.$_GET['ac_password'].'&to='.$_GET['to'].'&do='.$_GET['do'];
print_r($this->get_web_page($forwardURL));

如果我将$ forwardURL粘贴到我的浏览器中,它可以正常工作。

输出:

Array ( [url] => http://************/receive?from=*****&msg=*********&username=*******&ac_password=*****&to=********&do=send [content_type] => text/html; charset=us-ascii [http_code] => 400 [header_size] => 179 [request_size] => 594 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.053303 [namelookup_time] => 0.000996 [connect_time] => 0.025709 [pretransfer_time] => 0.025711 [size_upload] => 0 [size_download] => 311 [speed_download] => 5834 [speed_upload] => 0 [download_content_length] => 311 [upload_content_length] => 0 [starttransfer_time] => 0.053264 [redirect_time] => 0 [errno] => 0 [errmsg] => [content] =>
Bad Request

HTTP Error 400. The request is badly formed.

)

1 个答案:

答案 0 :(得分:4)

尝试使用http_build_query构建$forwardURL

$forwardURL = '*****/receive?' . http_build_query(array(
    'from' => $_GET['from'],
    'msg' => $_GET['msg'],
    'username' => $_GET['username'],
    'ac_password' => $_GET['password'],
    'to' => $_GET['to'],
    'do' => $_GET['do'],
));

问题可能是由于未转义字符在网址中具有特殊含义。 http_build_query安全地逃脱了他们。