最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】PHP代码运行出错:Warning: fsockopen() [function.fsockopen]: unable to connect to xxx:-1 (Unable to find the socket transport "http" – did you forget to enable it when you configured PHP?) in xxx.php on line xx

PHP crifan 6620浏览 0评论

【问题】

写了几行PHP代码:

/**
 * add newline for print
 */
function printAutoNewline($contentToPrint) {
    print_r($contentToPrint."<br />");
}

/**
 * get url reponse html
 */
function getUrlRespHtml($url) {
    printAutoNewline("input url=".$url);

    $respHtml = "";
    
    //resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )
    $res = fsockopen($url);
    printAutoNewline($res);
    
    return $respHtml;
}

$yellEntryUrl = "http://www.yell.com/";
$yesllRespHtml = getUrlRespHtml($yellEntryUrl);
printAutoNewline("yesllRespHtml=".$yesllRespHtml);

结果运行出错:

Warning: fsockopen() [function.fsockopen]: unable to connect to http://www.yell.com/:-1 (Unable to find the socket transport "http" – did you forget to enable it when you configured PHP?) in xxx.php on line 27

【解决过程】

1. 参考了:

fsock: Unable to find the socket transport “http”

看到其解释说fsockopen不支持Laye5+,所以不能直接给url地址,而只能给ip地址。

然后其建议用curl extension。

2.所以去找找php的curl extension。

然后找到:

Client URL Library

好像是用其实现url的访问,很是麻烦,需要类似于这样的代码:

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, TRUE);
            curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $head = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch); 

3.重新参考官网的解释:

fsockopen

去把代码改改为:

$fp = fsockopen($url, 80);

结果还是同样错误:

Warning: fsockopen() [function.fsockopen]: unable to connect to http://www.yell.com/:80 (Unable to find the socket transport "http" – did you forget to enable it when you configured PHP?) in xxx.php on line 27

4.把代码改为:

    $testHostname = "www.yell.com";
    $fp = fsockopen($testHostname, 80);

然后就可以了。

然后可以看到打印输出了:

Resource id #2

 

【总结】

把对应的url地址:

http://xxx.xxx.com

改为

xxx.xxx.com

然后再去调用fsockopen,记得port设置为80(默认是-1),就可以正常访问了:

    $testHostname = "www.yell.com";
    $fp = fsockopen($testHostname, 80);

 

总之,使用fsockopen去获得网页内容,极其的不方便。还是尽量去想别的办法去获得网页内容吧。

转载请注明:在路上 » 【已解决】PHP代码运行出错:Warning: fsockopen() [function.fsockopen]: unable to connect to xxx:-1 (Unable to find the socket transport "http" – did you forget to enable it when you configured PHP?) in xxx.php on line xx

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.174 seconds, using 22.14MB memory