I have a script to scrape a page. When the script runs, it takes 3 hours to complete. I want to build a button en when pressing it, the script must stop running.
Someone an idea?
I have a script to scrape a page. When the script runs, it takes 3 hours to complete. I want to build a button en when pressing it, the script must stop running.
Someone an idea?
The script that is running is a webpage?
Basically all you can do with the stop button, is send another request to the webserver (just stopping loading the webpage won't stop the request running on the server). This other request (being handled by another PHP thread/process) needs to let the first process know it needs to stop. One easy way of inter-process(/thread) communication is to have the second script create a file in the /tmp/ directory, and have the first process look for this file every now and then. If the first process sees that the file exists, it should abort processing and remove the file. Just to be a bit more robust, it should also delete the file on startup if it exists. Note: looking whether a file exists (in linux) in very fast. It will not hit the harddisk (because it will be cached). You won't even notice the extra delay until you really start doing it 1000+ times a second.
Obviously this will only work if the second process loops in PHP. If the second process does a single SQL query that takes 3 hours, it can't look for the file every second or so. In that case you need to do something with signals, killing the first process, see http://php.net/manual/en/function.posix-kill.php.
It can be done by ajax. Put this code to html head:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script language='javascript' type='text/JavaScript'>
{
function stop_script() {
$.post('stopScript.php');
}
}
</script>
and add button to your html body
<button onclick="stop_script()">Stop</button>
and it is your stopScript.php
<?php
session_start();
$_SESSION["stop_flag"] = "true";
?>
and check the session in your php script loop
session_start();
if(isset($_SESSION["stop_flag"]) && $_SESSION["stop_flag"] == "true")exit(0);
Or you could use the mysql datatable instead session. I used the datatable and it works well for me.
You CAN'T stop the PHP script from running. You CAN stop the client's browser to wait for the response, but the PHP/Apache process will still run in background until it finishes or encounters an error.
If you only want to stop the browser, then Sandeep Bansal's answer should do the trick.