jQuery.ajax() is "a function to be called when the request finishes". Suppose I'm making an ajax request to ajax.php:
<?php
echo 'complete';
some_functions_that_echo_nothing();
?>
Will the complete have to wait for some_functions_that_echo_nothing()? If so, is there a way to make the complete{} occur right after the echo and still have the ajax.php run through till the end?
Try calling HttpResponse::send();
I'm guessing you want to output "Complete" and let that function run in background, since it's very slow.
In that case put this function in a separate file. Let it be proc.php and use this instead:
<?php
echo "Complete';
exec ("/usr/bin/php proc.php >/dev/null &");
?>
That will return right away and fire the proc.php file to run on background. Of course it won't be able to output it's return to the user, so it should mail the user when he's done, or do his own persistence.
EDIT: ALWAYS take grea care of what you put inside exec statements. Never put user inputs into it if you are not 100% sure you are sanitizing it very carefully. Even so, you really don't have a good reason to use User input into an exec call.
Related
Can someone show a simple example on how to use fastcgi_finish_request() function?
I googled but only found some general mention of it, some people say they use it successfully but I could not find a single example with code.
For example, I have a PHP object. To send a response to a browser I generate HTML, then
returning it via getResult(). Then echo the result.
Like this:
$obj = new controller();
echo $o->getResult();
Let's say I want to take advantage of this optimization technique to send result to browser and then finish up some potentially long process like connecting to some API, like maybe Facebook API.
How would I go about doing this? I understand that basically I can call fastcgi_finish_request(); and then continue executing php script.
I just need to see example code, I'm not smart enough to figure it out by myself.
I understand that basically I can call fastcgi_finish_request(); and then continue executing PHP script.
Yes, that's all you have to do.
$obj = new controller();
echo $o->getResult();
fastcgi_finish_request();
do_facebook_thing();
To convince yourself it is working, do this:
echo "Test";
fastcgi_finish_request();
sleep(10);
If you remove the second line, then you will see that the browser has to wait 10 seconds.
I use phpseclib to SSH into my remote server from a web browser and execute a php file. Below is the code I use:
$ssh->exec('cd myfolder/; php main.php ' . $file, 'packet_handler');
function packet_handler(){
echo "Completed";
header("Location: exec_completed.php");
}
The main.php file gets executed without any issue. The problem is with returning the data after execution. I have the following questions:
I do a lot of processing in the main.php file and i need to show real time progress of what the script does. When i execute the file through exec, only the first echo in the main.php is printed and the execution stops. Is there any way to get real time data from the executing script.
I follow this example from phpseclib for callbacks although my callback function packet_handler doesn't run after exec is executed. I want to redirect to another page once the main.php I execute through SSH has completed its execution. Now if i redirect to that page i get only partial results as the main.php file has not completed its execution. I tried to use sleep(10) but my main.php may take longer times to execute at times so it didn't work. please suggest any ideas
Callback example from phpseclib:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
function packet_handler($str)
{
echo $str;
}
$ssh->exec('ping 127.0.0.1', 'packet_handler');
?>
For #1... doing $ssh->exec without the callback should work. If it doesn't I'd need to see the logs, which you can get by doing define('NET_SSH2_LOGGGING', 2) at the top and then echo $ssh->getLog() after. Posting the log at pastebin.com and then posting a link would be good. But that said, that won't get you real time output either.
For #2... the callback function is mainly intended for real-time updates and odds are very likely that what you'll get with each call of the callback function will be an incomplete output. So for your callback to output "Completed" and redirect the user to another location is, in all likelihood, incorrect.
Another approach that may work for you: use the interactive shell. Example:
http://phpseclib.sourceforge.net/ssh/examples.html#sudo,
I don't know what your output is like. Maybe you could read() until you got to certain parts of the output that are guaranteed to be output. Or maybe you could use $ssh->setTimeout(5) and get updated output every five seconds or something..
I'm creating a app that requires me to run a second php script while the first script is still running.
I'm new to php programing so I'm sure there's a simple function I can use that I'm just not aware of.
Looking forward to any help...
Shane
Since you are new to PHP I'm guessing you're looking for the include/require (and include_once/require_once) language constructs which will execute another PHP script as if it is part of the current script.
Otherwise if you want it to run as a separate process look into exec, shell_exec, or backticks. If you need the other PHP script to run as a background process make sure to redirect stdout somewhere (a file or maybe /dev/null if you don't need it) so that your currently executing script doesn't have to wait for it to finish to continue executing.
This will actually require us to use some Javascript for an ajax call to execute our PHP and return it's data.
I prefer Jquery, which will look similar to this:
function callPHP(){
$.post('./filetocall.php', {variableid: 'id'}, function (response) {
$("#div_for_return_data").val(response);
});
}
filetocall.php can look like anything. It's output will populate the #div_for_return_data
eg:
<?php echo $_GET['variableid']; ?>
Then just call the Jquery function from anywhere.
I am running a typical php-engined ajax webpage. I use echo to return a html string from the php code. My question is, if I have some other code after the echo, will those code get executed? Or echo behaves similar to exit, which immediately return and stop running the php code? Thanks.
No, echo in no way exits, you normally have more than one echo in a script. exit does take a string argument that it will output before exiting, however, so you can do:
exit("your string here");
and it will output the string and exit
No, echo would not. To exit after echoing things, you'd say
echo "Dear me, good bye!"; exit();
echo will simply return text to ajax javascript part; however the code after or before echo/echos will execute
No. PHP scripts are rendered in their entirety unless you explicitly exit them. ANY output on a script will be passed back to the ajax function if it was called through ajax.
echo 'This gets outputted<br />';
echo 'As does this';
If you must use a single file and you want your script to exit after performing ajax request with out having to add extra vars to your ajax url or evaluate vars to exit, i would suggest creating a function that performs your ajax, have the function return true on success, then do:
if(ajaxFunction($paramOne, $paramTwo)){exit();}
I'm having a little problem with the following:
When I execute this line:
echo exec(createDir($somevariable));
I get this error:
Warning: exec() [function.exec]: Cannot execute a blank command in /home/mydir/myfile.inc.php on line 32
Any ideas.
Thanks.
exec() expects a string argument, which it would pass on to your operating system to be executed. In other words, this is a portal to the server's command line.
I'm not sure what function createDir() is, but unless it's returning a valid command line string, it's probably failing because of that.
In Linux, you might want to do something like
exec('/usr/bin/mkdir '.$path);
...on the other hand, you should abstain from using exec() at all costs. What you can do here, instead, is take a look at mkdir()
With exec you can execute system calls like if you were using the command line. It hasn't to do anything with executing PHP functions.
To create a directory you could do the following:
exec( 'mkdir [NAME OF DIRECTORY]' );
I'd guess that your createDir() function doesn't return anything. Might also be worth checking that $somevariable is also set to something sensible
You're misunderstanding the purpose of exec(). If all you want to do is create a directory then you should use mkdir().
I think I've derived from other posts and comments what it is you actually want to do:
I think createDir() is a PHP function you've written yourself. It does more than just make a directory - it populates it, and that might take some time.
For some reason you believe that the next command gets run before createDir() has finished working, and you thought that by invoking createDir() using exec() you could avoid this.
Tell me in a comment if this is way out, and I'll delete this answer.
It's seems unlikely that createDir() really does keep working after it's returned (if it does, then we call that 'asynchronous'). It would require the programmer to go out of their way to make it asynchronous. So check that assumption.
Even so, exec() is not for invoking PHP functions. It is for invoking shell commands (the kind of thing you type in at a command prompt). As many of us have observed, it is to be avoided unless you're very careful - the risk being that you allow a user to execute arbitrary shell commands.
If you really do have to wait for an asynchronous function to complete, there are a couple of ways this can be done.
The first way requires that the asynchronous function has been written in an amenable manner. Some APIs let you start an asynchronous job, which will give you a 'handle', then do some other stuff, then get the return status from the handle. Something like:
handle = doThreadedJob(myParam);
# do other stuff
results = getResults(handle);
getResults would wait until the job finished.
The second way isn't as good, and can be used when the API is less helpful. Unfortunately, it's a matter of finding some clue that the job is finished, and polling until it is.
while( checkJobIsDone() == false ) {
sleep(some time interval);
}
I'm guessing createDir() doesn't have a return value.
Try exec("mkdir $somevariable");