3

I want to send a web page to the browser. At the same time, it will run another php script in the server without affecting the browser web page.

Is there any way to achieve this by php and jquery only?

ps1 My script is a heavy task, so I am not sure if it will delay the web page sending or not.

BLAdam
  • 45
  • 4
  • 2
    http://stackoverflow.com/questions/222414/asynchronous-shell-exec-in-php Keep in mind that running PHP through the command line is different from running it in Apache - the PHP executable can be different, the php.ini file can be different, etc. – DCoder Sep 06 '13 at 04:11

3 Answers3

4

i would do it like this

exec("nohup php otherphpscript.php  >/dev/null 2>&1 &");
0

You can use curl() to access the script in the background

<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://domain.com/script.php?s=email&m=message");
curl_exec ($curl);
curl_close ($curl);

script.php

<?php
// send an email confirming script.php was accessed (with params)
$subject = strip_tags($_GET['s']);
$message = strip_tags($_GET['m']);
mail('email@email.com',$subject,$message);

http://us2.php.net/curl

You can also do this asynchronously via ajax on document load

I'm not a javascript guy, so somebody may chime in with an issue doing it via ajax, however it's working for me in testing...

<script src="//code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function() {
$.ajax({
    type: 'POST',
    url: 'script.php',
    data: 's=subject&m=message',
    cache: false,
    success: function(data){
        // put success stuff here
        alert(data); // for testing
    }
});
return false;
 });
</script>

script.php

<?php
if($_SERVER['REQUEST_TYPE'] == 'POST') {
    $subject = strip_tags(trim($_POST['s']));
    $message = strip_tags(trim($_POST['m']));

    if(mail('email@email.com',$subject,$message)) {
        echo 'true';
    } else {
        echo 'false';
    }
}

Edit: updated answer per OP's question in comments. Edit: added ajax example

timgavin
  • 4,972
  • 4
  • 36
  • 48
0

It's possible. Just ping the URL:

// 'ping' the url http://localhost/browser/path/to/script2.php
$host = 'localhost';
$path = '/browser/path/to/script2.php';

$fp = fsockopen($host, 80);
if($fp !== false)
{
  $out  = "GET $path HTTP/1.1\r\n";
  $out .= "Host: $host\r\n";
  $out .= "Connection: Close\r\n\r\n";

  fwrite($fp, $out);
  fclose($fp);
}

And then in script2.php:

ignore_user_abort(true);

// your code goes here
// ...
  • far more overhead than necessary if the script is local. –  Sep 06 '13 at 04:29
  • True. Every version has its downsides. I just like this one, because it works on all platforms, is less overhead than curl, doesn't depend on the user and solves @DCoder's concerns. – lucido-media.de Sep 06 '13 at 04:42