Home » Php » PHP exec to run a file

PHP exec to run a file

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying for last 3 hours to tell PHP to run a simple file. I am using wamp server for windows in local host (Windows 8)

I’ve tried with exec() working with:

 echo exec('whoami');

I got response nt authority.

Also tested with:

if(function_exists('exec')) {
echo "exec is enabled";
}

So it probably works?

I am trying to run a file called tester.php

When I include it, its working, when I require it its working. I need to execute it in background. When I refresh file, code is working without any error, it writes to the database normally.

When i try to exec it its not working.

I tried :

       exec("php http://localhost/diplomski/program/defender/tester.php");
       exec("php-cli http://localhost/diplomski/program/defender/tester.php");
       exec("http://localhost/diplomski/program/defender/tester.php");

Not working, also tried:

        exec("php http://127.0.0.1/diplomski/program/defender/tester.php");
        exec("php-cli http://127.0.0.1/diplomski/program/defender/tester.php");
        exec("php-cli d:\wamp\www\diplomski\program\defender/tester.php")

Not working also tried:

        exec("php tester.php");
        exec("php-cli tester.php");
        exec("tester.php");

Also tried:

         $WshShell = new COM("WScript.Shell");
         $oExec = $WshShell->Run("D:\wamp\bin\php\php5.3.13\php-win.exe -f d:\wamp \www\diplomski\program\defender/tester.php", 0, false);

Tried this, its refreshing infinitely and not working:

        exec("php d:\wamp\www\diplomski\program\defender/tester.php");
        exec("php-cli d:\wamp\www\diplomski\program\defender/tester.php");
        exec("d:\wamp\www\diplomski\program\defender/tester.php");

I’m starting to pull my hair out here. First time I’m trying to use exec() and I’m not very good with it or with the commands.

How to&Answers:

Give the full path to the PHP executable and the full path to the PHP script. You can save the output in $output to see what the script produced:

exec("d:/path/to/php.exe d:/wamp/www/diplomski/program/defender/tester.php", $output);
print_r($output);

Answer:

1) What version of php? If it is older then 5.4.0 php can be in safe mode, when safe mode is enabled, you can only execute files within the safe_mode_exec_dir.

2)Note to this function in php.net
Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

3) So you can try this How to make php script run another php script you can try this

 <?php
 $somearg = escapeshellarg('blah');
 exec("php file2.php $somearg > /dev/null &");

4) You can create a scheduled task How to run a PHP file in a scheduled task (Windows Task Scheduler)