I have two PHP scripts—we will call them script A and script B. Script A starts running when the user does a certain interaction. Script A needs to run script B in the background—thus return script A's result while script B is still running. I could do this inside script A:
exec('scriptB.php &'), however since I'm on shared hosting exec is not allowed. Also, an Ajax solution (initiate both scripts on the client-side) will not work since script B MUST run—I can't have the user maliciously stopping the script from running.
Is there any solution that does not involve using a shell command or Ajax?
Thanks in advance!
I ended up using this method:
http://w-shadow.com/blog/2007/10/16/how-to-run-a-php-script-in-the-background/
function backgroundPost($url){
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
return false;
} else {
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($parts['query'])."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
fwrite($fp, $out);
fclose($fp);
return true;
}
}
//Example of use
backgroundPost('http://example.com/slow.php?file='.urlencode('some file.dat'));
Rachael, thanks for the help.
Related
I'm trying to send a request to a remote server using the fire-and-forget approach. This is my code:
function backgroundPost($url, $data = array()){
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
return false;
} else {
$encoded_data = json_encode($data);
$output = "POST ".$parts['path']." HTTP/1.1\r\n";
$output .= "Host: ".$parts['host']."\r\n";
$output .= "Content-Type: application/json\r\n";
$output .= "Content-Length: " . strlen($encoded_data) . "\r\n";
$output .= "Connection: Close\r\n\r\n";
$output .= $encoded_data;
fwrite($fp, $output);
fclose($fp);
return true;
}
}
//Example of use
backgroundPost('url-here', array("foo" => "bar"));
but the data that arrives is simply empty.
When I spin up the application locally and send the request to my own machine instead, the data does arrive.
Am I misunderstanding something about this pattern?
Why is it working when sending a request to my own machine but not a remote one?
Thanks!
I need to run a php code in a different server (let's call it server 2) from server 1.
In server 1, I have something like this
<?php
file_get_contents('http://domain_in_server_2.com/php-script.php');
?>
The problem is, this request may take long time, and I don't need to get the output. I just want to trigger the script without having to wait or getting the output.
Is there anyway to accomplish what I want?
Thank you very much.
You can use a socket. See this example.
Edit:
Here is the code from the above link:
// Example:
// post_async("http://www.server.com/somewhere",array("foo" => 123, "bar" => "ABC"));
function post_async($url, $params)
{
// Build POST string
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
// Connect to server
$parts=parse_url($url);
$fp = fsockopen($parts['host'],isset($parts['port'])?$parts['port']:80,$errno, $errstr, 30);
// Build HTTP query
$out = "$type ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
$out.= $post_string;
// Send data and close the connection
fwrite($fp, $out);
fclose($fp);
}
I was searching on how to use curl (send http request) without waiting for the response to complete, because i just want to trigger many action and dont expect the results. After time of searching, I found a solution Here, but i have a problem.The problem is i don't know how to pass cookie that I have saved in .txt and i want to send it using this request.
function curl_post_async($url, $params)
{
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
How to send cookie from .txt files using above's code?
After research I solved how to send cookies from cookies.txt
When I search I found 2 formats of cookies
1. Netscape
# Netscape HTTP Cookie File
# https://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
#HttpOnly_.site.com TRUE / FALSE 1517538526 __cfduid dc0d1a86523f4fa68c7c9e19b084aa1651486002526
#HttpOnly_www.site.com FALSE / FALSE 1486006126 cisession a914d92115f6a6d73124ac5de4c49e070b872b98
2. Cookie default format (reference: Here)
csrf_cookie_name=cac551cc13952929efd2507797fff687; ci_session=umt92quvucfu333p1co19b83i3jaglm9;
I tried to send the cookie format no.1 using this line code
$out.= "Cookie: ".file_get_contents(getcwd().$cookie); //where getcwd().$cookie is location of the cookie.txt with format no.1
I tried that but it failed. But if the cookie.txt's cookie value is format no.2 I sent that cookie and it successfully sended and can be read.
Conclusion to send cookie:
$out.= "Cookie: csrf_cookie_name=cac551cc13952929efd2507797fff687; ci_session=umt92quvucfu333p1co19b83i3jaglm9;";
I'm trying to program yahoo messenger robot,now my robot can get messages and answer to them.
Yahoo only can send 100 pm at each time I get notification.
now I wanna answer the each pm. I use while(true){ } to it and answer first pm,then second ,then 3rd and ... .
It's so slow ,because I can make only one connection to yahoo by this(I use curlib).
how can I send some messages at same time?I think I need something like thread but in php.
you can use pcntl_fork(). http://www.php.net/manual/en/function.pcntl-fork.php
You need pcntl extension and it only works on Unix
If you use curl function you might take a look at curl_multi_init(). http://www.php.net/manual/en/function.curl-multi-init.php
I've wrote a simple function below, which launches URL, and doesn't wait for a result, so like this you can launch many URLs on your own site, it will make your loop fast, and also no need to install any extensions to your server.
function call_url_async($url, $params, $type='POST', $timeout_in_seconds = 1)
{
//call the URL and don't wait for the result - useful to do time-consuming tasks in background
foreach ($params as $key => &$val)
{
if (is_array($val))
$val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, $timeout_in_seconds);
//if ($fp == FALSE)
// echo "Couldn't open a socket to ".$url." (".$errstr.")<br><br>";
// Data goes in the path for a GET request
if ('GET' == $type)
$parts['path'] .= '?'.$post_string;
$out = "$type ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
// Data goes in the request body for a POST request
if ('POST' == $type && isset($post_string))
$out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
I am trying to send a SOAP message to a service using php.
I want to do it with fsockopen, here's is the code :
<?php
$fp = #fsockopen("ssl://xmlpropp.worldspan.com", 443, $errno, $errstr);
if (!is_resource($fp)) {
die('fsockopen call failed with error number ' . $errno . '.' . $errstr);
}
$soap_out = "POST /xmlts HTTP/1.1\r\n";
$soap_out .= "Host: 212.127.18.11:8800\r\n";
//$soap_out .= "User-Agent: MySOAPisOKGuys \r\n";
$soap_out .= "Content-Type: text/xml; charset='utf-8'\r\n";
$soap_out .= "Content-Length: 999\r\n\r\n";
$soap_put .= "Connection: close\r\n";
$soap_out .= "SOAPAction:\r\n";
$soap_out .= '
Worldspan
This is a test
';
if(!fputs($fp, $soap_out, strlen($soap_out)))
echo "could not write";
echo "<xmp>".$soap_out."</xmp>";
echo "--------------------<br>";
while (!feof($fp))
{
$soap_in .= fgets($fp, 100);
}
echo "<xmp>$soap_in</xmp>";
fclose($fp);
echo "ok";
the above code just hangs . if i remove the while it types ok, so i suppose the problem is at $soap_in .= fgets($fp, 100)
Any ideas of what is happening
Its not just a matter of opening a socket then writing 'POST....' to it - you need a full HTTP stack to parse the possible responses (e.g. what different encodings? Partial Content?). Use cURL.
The reason its currently failing is probably because the remote system is configured to use keepalives - which would again be solved by using a proper HTTP stack.
C.
I recommend, use curl for soap actions. http://www.zimbra.com/forums/developers/9890-solved-simple-soap-admin-example-php.html#post52586