PHP fsockopen doesnt return anything

不想你离开。 提交于 2019-12-13 03:01:16

问题


I am modifying a PHP db wrapper for the redis database.

Here's how my function looks:

public function connect() {

    $sock = @fsockopen('localhost', '6379',  $errno, $errstr, 2);

    if ($sock === FALSE) {
        return FALSE;
    }
    else {
        stream_set_timeout($sock, 2); 
        return $sock;
    }
}

What I want to do is to call this function from another part in my wrapper:

 if ($this->connect() !== FALSE) {
      // Do stuff
 }

How can I get my connect function to send a FALSE when the fsockopen isn't working?

Thanks!


回答1:


From a little ways down the fsockopen() page (have to scroll almost to the bottom):

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

I'm going to guess that's your problem, I guess you have to do a test read/write to see if it was really successful or not.




回答2:


Try the following code and see if this works as intended:

public function connect()
{
    $sock = @fsockopen('localhost', '6379',  $errno, $errstr, 2);

    if (!is_resource($sock))
        return FALSE;

    stream_set_timeout($sock, 2); 
    return $sock;
}



回答3:


@fsockopen

You've got an @ in front of your function, which is going to suppress errors. If the error is causing zero return, you're not going to get anything. Remove the @ and log or display any resulting errors or warnings.




回答4:


I know it might be way late to answer. But, fsockopen kinda has a problem with 'localhost'.. try using '127.0.0.1' n i m sure it will connect. ;)



来源:https://stackoverflow.com/questions/2876478/php-fsockopen-doesnt-return-anything

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!