very confuse with fsockopen

Discussion in 'PHP' started by prashcom, Feb 14, 2008.

  1. #1
    Hello friends,

    I am in big problem and i need help from you guys...

    My problem is i want to run a php file for forever....

    I used fsockopen for this and its seems its working all fine but i think somehow i am doing somewhere silly mistake...

    This is my code:

    The file name is "list-items.php", same as what i am going to call again using this socket connection.

    mail('example@abc.com','hi','helllo');
    sleep(5);
    if($_SERVER['SERVER_ADDR'] != '127.0.0.1')
    {
    $socket = fsockopen("www.example.com", 80, $errno, $errstr, 10);
    if (!$socket)
    {
    //echo "$errstr ($errno)<br />\n";
    echo "Error in socket connection.............";
    }
    else
    {
    $out = "GET list-items.php HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    if (fwrite($socket, $out) === FALSE)
    {
    echo "error.........";
    }
    fclose($socket);
    }
    }

    I am really confuse after seeing the output of this code....

    This code is opening lots of threads with same instance...

    Will anyone pls tell me how this will work...

    My only job is to open a file in php such a way so will call itself after performing the desired task, in every 2-3 second...

    Is there anyway i can achive the task?
    I think cron is not good as will not run in such frequently.... my server support atleast 2minute gap....

    so i think socket can do this job but why this example opening multiple threads instead of only one socket connection?
     
    prashcom, Feb 14, 2008 IP
  2. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This is why it's opening multiple connections:

    -list-items.php completes and opens an fsock connection to the same file
    --this is an entirely new list-items.php run, not reusing the current script, so it is going to use a new thread

    I'm sort of confused what you mean by keep running it and why you'd want to however, here is a simple method.

    set_time_limit(0);
    while(true) {
      sleep(5);
      mail('example@abc.com','hi','helllo');
      //Whatever other code you want to constantly repeat
    }
    PHP:
    This will first set it so the script does not time out on you. Then, it will initialize a loop that will never end, while pausing for 5 seconds at a time, and running the code you want it to keep running. You do not need your fsock stuff here since it does not have to reload itself; the loop will easily cause it to keep running.

    I really hope I did not just help you make some sort of mail bomber..
     
    zerxer, Feb 15, 2008 IP