Hướng dẫn can php run asynchronously?

How can I run PHP code asynchronously without waiting? I have a long run (almost infinite) that should run while server starts and should process asynchronously without waiting.

Nội dung chính

  • Not the answer you're looking for? Browse other questions tagged php or ask your own question.
  • Can PHP run asynchronously?
  • Is PHP synchronous or asynchronous?
  • How do I run a PHP script?
  • How do I run a PHP script from the command line?

The possible options I guess are:

  1. Running the code in a web page and keep it open to do that task
  2. Calling the script from some command line utility (I am not sure how) which would process in the background.

I am running the PHP scripts on my local server which will send emails when certain events occur, e.g. birthday reminders.

Please suggest how can I achieve this without opening the page in a browser.

asked May 6, 2011 at 1:20

Hướng dẫn can php run asynchronously?

6

If you wanted to run it from the browser (perhaps you're not familiar with the command line) you could still do it. I researched many solutions for this a few months ago and the most reliable and simplest to implement was the following from How to post an asynchronous HTTP request in PHP

 &$val) {
      if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key.'='.urlencode($val);  
    }
    $post_string = implode('&', $post_params);

    $parts=parse_url($url);

    $fp = fsockopen($parts['host'],
        isset($parts['port'])?$parts['port']:80,
        $errno, $errstr, 30);

    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out.= "Content-Length: ".strlen($post_string)."\r\n";
    $out.= "Connection: Close\r\n\r\n";
    if (isset($post_string)) $out.= $post_string;

    fwrite($fp, $out);
    fclose($fp);
}

Let's say the file above is in your web root directory (/var/www) for example and is called runjobs.php. By visiting http://localhost/runjobs.php your myjob.php file would start to run. You'd probably want to add some output to the browser to let you know it was submitted successfully and it wouldn't hurt to add some security if your web server is open to the rest of the world. One nice thing about this solution if you add some security is that you can start the job anywhere you can find a browser.

answered May 6, 2011 at 3:09

Todd ChaffeeTodd Chaffee

6,64630 silver badges41 bronze badges

3

Definitely sounds like a job for a cron task. You can set up a php script to do your task once and have the cron run as often as you like. Here's a good writeup on how to have a php script run as a cron task; it's very easy to do.

answered May 6, 2011 at 2:57

eykanaleykanal

25.5k19 gold badges79 silver badges111 bronze badges

1

This isn't really what PHP is designed for. You have to use the PECL threading library to spin off threads that run asynchronously, and I don't recommend it. The new hotness in the async department is node.js - I recommend you look into that and see if you can utilize it. It's designed for light weight, asynchronous network operations, and can be used to fire PHP scripts.

answered May 6, 2011 at 1:49

David FellsDavid Fells

6,5801 gold badge21 silver badges34 bronze badges

1

How Can I run PHP code asynchronously without waiting. I have a long run (almost inifinite) that should run while server starts and should process asynchrously without waiting.

Assuming a typical LAMP system, you can start a PHP daemon from the command line with

root# php yourscript.php &

where yourscript.php contains something similar to


Embellishments: To make your script directly executable: chmod +x yourscript.php and add #!/usr/bin/php to the beginning of yourscript

To start with apache, you should add that command to your apache startup script (usually apachectl) and be sure to add code to kill it when apache stops.

The check if you are already running involves a file with your PID in /var/locks/ and something like system('/bin/ps '.$thePID); It also makes the kill instruction easier to write.

answered May 6, 2011 at 2:50

MagicianeerMagicianeer

2,1901 gold badge16 silver badges12 bronze badges

thanks Todd Chaffee but it is not working for me so i edited your code i hope you will not mind and may be it will also help others with this technique

cornjobpage.php //mainpage

     


         &$val) {
              if (is_array($val)) $val = implode(',', $val);
                $post_params[] = $key.'='.urlencode($val);  
            }
            $post_string = implode('&', $post_params);

            $parts=parse_url($url);

            $fp = fsockopen($parts['host'],
                isset($parts['port'])?$parts['port']:80,
                $errno, $errstr, 30);

            $out = "GET ".$parts['path']."?$post_string"." HTTP/1.1\r\n";//you can use POST instead of GET if you like
            $out.= "Host: ".$parts['host']."\r\n";
            $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
            $out.= "Content-Length: ".strlen($post_string)."\r\n";
            $out.= "Connection: Close\r\n\r\n";
            fwrite($fp, $out);
            fclose($fp);
        }
        ?>

testpage.php

     testValue
    ?>

answered Dec 19, 2016 at 14:51

Hassan SaeedHassan Saeed

5,1771 gold badge30 silver badges34 bronze badges

Not the answer you're looking for? Browse other questions tagged php or ask your own question.

Can PHP run asynchronously?

What Is Asynchronous PHP? Asynchronous PHP refers to PHP code that is written using the asynchronous model. In other words, asynchronous applications can multi-task. This is critical because traditionally, there's a lot of time when a CPU sits idle while a PHP application manages I/O tasks.

Is PHP synchronous or asynchronous?

PHP serves requests synchronously. It means that each line of code executes in the synchronous manner of the script. After getting the result from one line it executes next line or wait for the result before jumping to the execution of the next line of code.

How do I run a PHP script?

To locally run a PHP Script:.

Click the arrow next to the Run button. on the toolbar and select Run Configurations -or- go to Run | Run Configurations. A Run dialog will open..

Double-click the PHP Script option to create a new run configuration..

How do I run a PHP script from the command line?

You just follow the steps to run PHP program using command line..

Open terminal or command line window..

Goto the specified folder or directory where php files are present..

Then we can run php code using the following command: php file_name.php..