Reputation: 162
I have a PHP script which opens a socket connection to a machine on the same network and waits for a response for up to 60 seconds then returns the result. This script is called upon using an ajax request on the "main" page which displays a message containing the result.
Problem is I want to be able to end the socket connection from the "main" page at any time, is this something that can be done? Or can anyone else think of a better way of doing this?
Thanks!
Upvotes: 0
Views: 97
Reputation: 30893
Here is a really lite weight and untested theory.
open.php
<?php
session_start();
$_SESSION['fp'] = fsockopen($_GET['url'], 80, $errno, $errstr, 60);
// Do listen for 60 seconds, get data
while (!feof($_SESSION['fp'])) {
echo fgets($_SESSION['fp'], 128);
}
fclose($_SESSION['fp']);
unset($_SESSION['fp']);
?>
close.php
<?php
session_start();
if(isset($_SESSION['fp'])){
fclose($_SESSION['fp']);
unset($_SESSION['fp']);
}
?>
JavaScript
$(function(){
$("#go").click(function(){
$.get("open.php", { url: $("#url").val() }, function(results){
console.log(results);
});
});
$("#stop").click(function(){
$.get("close.php");
});
});
The idea here is that the File Pointer is stored in a session variable, so it can be called upon by other scripts. Since you didn't provide an example, I cannot say if this will work for you. I have never tested it since I've never wanted a script to close the connection prematurely. I've wanted to remain open until I got all my data and then close at EOF.
Alternatively, you can do something similar with the Process ID. Each PHP Script gets a PID when running. Discussed more here: How to kill a linux process using pid from php?
Upvotes: 1