Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP execute external script without waiting, while passing variables

Tags:

shell

php

I'm making a function for my users where they can upload large XML files to synchronize with my database.

When a user uploads a file to upload.php, I want to start processing the data in the background with process.php, preferably from a shell command, and redirect the user to status.php, which shows the process of the synchronization.

I need to pass some variables to the process.php script while executing it, either at least one variable with the user id and put the other variables into a text file, (Would probably prefer this so I wont have to put to much data into the exec() command.) or the user id and a bunch of $_POST variables.

One solution I had in mind is executing the PHP script like this:

exec("php -f ./process.php > /dev/null 2>/dev/null &"); 

This allows me to lock away process.php from http access, which is good since it's a process taking script. The only thing I need here is to pass a variable somehow, but i don't know how to do it.

So my main question is:

How do i pass a variable in the above solution?

Or do any of you have a better solution to doing this? Possibly one where i wont have to go through exec()? Keep in mind that i do not want the user to wait for the script to execute, and i need to pass at least one variable.

Update: For future reference, remember to use escapeshellarg() when passing arguments through exec() or likewise functions.

like image 578
Kristoffer la Cour Avatar asked Oct 18 '25 15:10

Kristoffer la Cour


1 Answers

You test use it

exec("php -f ./process.php var1 var2 > /dev/null 2>/dev/null &"); 

And if you like get these variables values can acces with global variable $argv. If you print this var show same:

print_r($argv);


Array
(
    [0] => process.php
    [1] => var1
    [2] => var2
)
like image 73
jbalde Avatar answered Oct 21 '25 04:10

jbalde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!