views:

157

answers:

4

Hi! 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!

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

Citizen
At first I thought the same, but it is not the question he's asked :)
Col. Shrapnel
Hi! Nope, no errors or anything appears if the @ is removed. The fsocksopen call just fails silently :(
Industrial
+1  A: 

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.

Chad Birch
This seemed very probably except he's not doing `fsockopen('udp://localhost'`...
Josh
It's a TCP call actually, so maybe it is the same for TCP?
Industrial
A: 

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;
}
Josh
Nope, same errors as before :(
Industrial
@Industrial: What specifically is the error?
Josh
A: 

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

Stoic