开发者

PHP fsockopen doesnt return anything

开发者 https://www.devze.com 2022-12-30 20:54 出处:网络
I am modifying a PHP db wrapper for the redis database. Here\'s how my function looks: public function connect() {

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 (开发者_JAVA百科$this->connect() !== FALSE) {
      // Do stuff
 }

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

Thanks!


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.


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


@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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号