Running a second PHP script while keeping the client on same page - php

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.

Related

Stop PHP with ajax

I have a JavaScript functions which calls a PHP function through AJAX.
The PHP function has a set_time_limit(0) for its purposes.
Is there any way to stop that function when I want, for example with an HTML button event?
I want to explain better the situation:
I have a php file which uses a stream_copy_to_stream($src, $dest) php function to retrieve a stream in my local network. The function has to work until I want: I can stop it at the end of the stream or when I want. So I can use a button to start and a button to stop. The problem is the new instance created by the ajax call, in fact I can't work on it because it is not the function that is recording but it is another instance. I tried MireSVK's suggest but it doesn't worked!
Depending on the function. If it is a while loop checking for certain condition every time, then you could add a condition that is modifiable from outside the script (e.g. make it check for a file, and create / delete that file as required)
It looks like a bad idea, however. Why you want to do it?
var running = true;
function doSomething(){
//do something........
}
setInterval(function(){if(running){doSomething()}},2000); ///this runs do something every 2 seconds
on button click simply set running = false;
Your code looks like:
set_time_limit(0);
while(true==true){//infinite loop
doSomething(); //your code
}
Let's upgrade it
set_time_limit(0);
session_start();
$_SESSION['do_a_loop'] = true;
function should_i_stop_loop(){
#session_start();
if( $_SESSION['do_a_loop'] == false ) {
//let's stop a loop
exit();
}
session_write_close();
}
while(true==true){
doSomething();
should_i_stop_loop(); //your new function
}
Create new file stopit.php
session_start();
$_SESSION['do_a_loop'] = false;
All you have to do now is create a request on stopit.php file (with ajax or something)
Edit code according to your needs, this is point. One of many solutions.
Sorry for my English
Sadly this isn't possible (sort of).
Each time you make an AJAX call to a PHP script the script spawns a new instance of itself. Thus anything you send to it will be sent to a new operation, not the operation you had previously started.
There are a number of workarounds.
Use readystate 3 in AJAX to create a non closing connection to the PHP script, however that isn't supported cross browser and probably won't work in IE (not sure about IE 10).
Look into socket programming in PHP, which allows you to create a script with one instance that you can connect to multiple times.
Have PHP check a third party. I.E have one script running in a loop checking a file or a database, then connect to another script to modify that file or database. The original script can be remotely controlled by what you write to the file/database.
Try another programming language (this is a silly option, but I'm a fan of node). Node.js does this sort of thing very very easily.

stop php execution instead of just a php script in codeigniter

I am using Codeigniter for a project and i usually call a series of models (let's say controllerA -> modelA -> modelB -> modelC) for some work. I want the php to stop executing when it reaches some exception where i invoke the exit() command. Now, if the command exit() is invoked in modelB, will it stop execution of only the script of modelB and continue executing rest of the modelA? Or will it stop the entire execution flow.
I really don't know how to put this question here. The question looks quite messy. Please let me know should i need to revise the question itself.
Yes, exit stops all script execution immediately, regardless where you call it.
The opposite is return which only stops execution of the current function (or current file when used at global level in an included file)
Read more here: https://stackoverflow.com/a/9853554/43959
Wherever you call the exit() function, all code will stop executing. This includes the other files because codeigniter just 'requires' them.
It stops the execution from that line.
I'm not sure if what you want, but maybe you can use exceptions to control PHP code execution.
http://es.php.net/manual/en/class.exception.php
Regards!
Like someone mentions above you should return from a function, or If your in a loop you could use continue or break

I want to execute more than one method at a time in php

Hi Please help me in executing more than one method at a time in PHP.
Below is example:
<?php
function writeName()
{
sleep(3);
echo "Kai Jim Refsnes";
}
function b(){
sleep(3);
echo"b";
}
b();
writeName());
?>
Here above program take 6 sec to execute.But I want to run my both method simultaneously so that program should execute with in 3 sec(Multi threading).
With common PHP its not possible, because PHP is executed sequential. You may have a look at a job-server like gearman, or you may try to use forks (pcntl_fork()). It's not multi-threading, because there is no shared memory.
Sorry, but multithreading is not supported in PHP.
But you could start a PHP script which can run in the background using exec(). Just make sure you redirect it's output elsewhere.
That should be the closest you can get to "multithreading" without additional tools. Here's what the manual says:
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.

When is jQuery.ajax() complete{}?

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.

php exec() error

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");

Categories