PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, September 14, 2022

[FIXED] How to run a background process by PHP in windows?

 September 14, 2022     background-process, environment, exec, php, windows     No comments   

Issue

I try to run a Python script as a background process from PHP on Windows using exec() on this way:

<?PHP
    $python    = 'C:\\Users\\User\\anaconda3\\python.exe';
    $py_script = 'C:\\wamp\\www\\lab\\ex\\simple_test.py';
    $py_stdout    = '> temp\\'.session_id()."_std.txt";
    $py_stderror  = '2> temp\\'.session_id()."_stde.txt";

    exec("$py_bg $python $py_script $py_stdout $py_stderror &");

The script called and worked correctly, but PHP still waiting for the script. I removed the end & as I foundout it's only work on Linux and after searching other Q&A find this sulotion:

    exec("start /B $py_bg $python $py_script $py_stdout $py_stderror");

But same result. How can I solve this problem?

=== UPDATE:

I used start /B in the wrong way, I changed my code to this:

<?PHP
    $python    = 'C:\\Users\\User\\anaconda3\\python.exe';
    $py_script = 'C:\\wamp\\www\\lab\\ex\\simple_test.py';
    $py_stdout    = '> temp\\'.session_id()."_std.txt";
    $py_stderror  = '2> temp\\'.session_id()."_stde.txt";
    $py_cmd = "$python $py_script $py_arg_1 $py_std $py_stde";

    pclose(popen("start /B ". $py_cmd, "a"));

But now a Warning in PHP for popen():

Warning: popen(start /B ...,a): No error in C:\wamp\www\lab\start.php on line 50

and an other for pclose():

Warning: pclose() expects parameter 1 to be resource, bool given in ...


Solution

I checked PHP: popen - Manual and see there a is not a valid mode, but I see this on several answers around here!

however:

The mode. Either 'r' for reading, or 'w' for writing.

By changing mode to r, the script call and run in the background correctly and there is not an error or warning on PHP or Py.

<?PHP
    $python    = 'C:\\Users\\User\\anaconda3\\python.exe';
    $py_script = 'C:\\wamp\\www\\lab\\ex\\simple_test.py';
    $py_stdout    = '> temp\\'.session_id()."_std.txt";
    $py_stderror  = '2> temp\\'.session_id()."_stde.txt";
    $py_cmd = "$python $py_script $py_arg_1 $py_std $py_stde";

    pclose(popen("start /B ". $py_cmd, "r"));


Answered By - Milad Abooali
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing