File_get_contents($ url):无法打开流

时间:2014-08-18 16:38:29

标签: php

我有一个脚本,我使用以下方法读取文件:

file_get_contents(urlencode($url));

我收到此错误:

failed to open stream: HTTP request failed! HTTP/1.0 400 Bad request

我试过了this,但我仍然得到错误。 我试过这个:

ini_set('default_socket_timeout', 120);

此:

$opts = array('http'=>array('timeout' => 120));
         $context = stream_context_create($opts);
         $resul = file_get_contents($url,0,$context);

而且:

$opts = array('http'=>array('timeout' => 120,'header'=>'Connection : close'));
         $context = stream_context_create($opts);
         $resul = file_get_contents($url,false,$context);

你能帮我解决一下我收到错误的原因吗?

1 个答案:

答案 0 :(得分:1)

你只需要编码"查询字符串",提取查询并加入这个,在附加了enconded查询之后你会" url"。

  

注意:file_get_contents在" php.ini"中需要allow_url_fopen=On,请尝试使用curl

示例(在代码中阅读我的评论)

  

注意:此示例在连接和http错误

中出错
<?php
//Set your page example
$uri = 'http://localhost/path/webservice.php?callback=&id=153&provenance=153&ret=a:1:{s:5:"infos";a:8:{s:8:"civilite";s:3:"Mme";s:5:"lname";s:0:"";s:5:"fname";s:8:"Nathalie";s:5:"email";s:17:"tometnata@free.fr";s:3:"tel";s:0:"";s:7:"adresse";s:0:"";s:6:"date_n";s:14:"10:"01/06/1969";s:2:"cp";s:0:"";}}';

//extract url
$parsed_url = parse_url($uri);

//Create fixed url
$fixed_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'];

//If exists query
if (isset($parsed_url['query'])) {
    $output = array();
    $result = array();

    //Extract querystring
    parse_str($parsed_url['query'], $output);

    //Encode values in querystring
    forEach($output as $k => $v) {
        $result[] = $k . '=' . rawurlencode($v);
    }

    //Append encoded querystring
    $fixed_url .= '?' . implode('&', $result);
}

echo 'GET url: ', $fixed_url, '<br>';

//Get result in page
$ch = curl_init();
$timeout = 30; //set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $fixed_url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$file_contents = curl_exec($ch);

$errornum = curl_errno($ch);

$info = curl_getinfo($ch);

$status = (int) $info['http_code'];

if ($errornum !== 0) {
    echo 'Error: ', curl_error($ch);
    $file_contents = NULL;
} else if ($status !== 200) {
    echo 'http_error: ', $status;
    $file_contents = NULL;
} else {
    echo 'Result:<hr>';
    echo $file_contents;
}

curl_close($ch);
?>

启用curl