Solved

Asynchronous PHP (that old chestnut)

Posted on 2013-06-07
9
280 Views
Last Modified: 2013-06-10
Hi.

I have a client calling my server script, doing stuff, and replying...

But one of the things it's doing it taking a while, and so I don't want the main process to wait before it replies, instead I want it to fire off a little PHP script to get on with it, so it can reply to the user as soon as possible.

How to do this?

I have quickly tried exec, and fsocketopen, but my child php is not executing, and I don't know how to trap the error.  There is nothing in my error logs.

Can someone give me the statements to do this, so I can get on writing the code that gets executed.

Thanks,

Cris.
0
Comment
Question by:CrisThompsonUK
  • 6
  • 3
9 Comments
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39229665
Give us a little more detail, please.  Please tell us about this:
I have a client calling my server script, doing stuff, and replying...
Since your child PHP script has no browser output, you can't rely on echo to send the messages that you can see.  You will want to use error_log() or something similar to see the messages from the script.  You might write these messages into a plain-text file.  One other technique that I've found useful goes something like this code snippet.
<?php
ob_start();
echo 'Hello World';
$msg = ob_get_clean();
mail('You@Your.org', 'ASYNC SCRIPT MESSAGES', $msg);

Open in new window

Here is an example of a script that starts an asynchronous task.
<?php // RAY_curl_post_example.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO USE CURL POST TO START AN ASYNCHRONOUS PROCESS


function curl_post($url, $post_array=array(), $timeout=2, $error_report=FALSE)
{
    // PREPARE THE POST STRING
    $post_string = NULL;
    foreach ($post_array as $key => $val)
    {
        $post_string .= $key . '=' . urlencode($val) . '&';
    }
    $post_string = rtrim($post_string, '&');

    // PREPARE THE CURL CALL
    $curl = curl_init();
    curl_setopt( $curl, CURLOPT_URL,            $url         );
    curl_setopt( $curl, CURLOPT_HEADER,         FALSE        );
    curl_setopt( $curl, CURLOPT_POST,           TRUE         );
    curl_setopt( $curl, CURLOPT_POSTFIELDS,     $post_string );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout     );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE         );

    // EXECUTE THE CURL CALL
    $htm = curl_exec($curl);
    $err = curl_errno($curl);
    $inf = curl_getinfo($curl);

    // ON FAILURE
    if (!$htm)
    {
        // PROCESS ERRORS HERE
        if ($error_report)
        {
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            echo "<pre>\n";
            var_dump($inf);
            echo "</pre>\n";
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS
    curl_close($curl);
    return $htm;
}


// USAGE EXAMPLE CREATES ASSOCIATIVE ARRAY OF KEY=>VALUE PAIRS
$args["name"]  = 'Ray';
$args["email"] = 'Ray.Paseur@Gmail.com';

// ACTIVATE THIS TO SEE THE ARRAY OF ARGS
// var_dump($args);

// SET THE URL
$url = "http://LAPRBass.com/RAY_bounce_post.php";

// CALL CURL TO POST THE DATA
$htm = curl_post($url, $args, 3, TRUE);

// SHOW WHAT CAME BACK, IF ANYTHING
if ($htm)
{
    echo "<pre>";
    echo htmlentities($htm);
}
else
{
    echo "NO RESPONSE YET FROM $url -- MAYBE BECAUSE IT IS RUNNING ASYNCHRONOUSLY";
}

Open in new window

You may want to set up a "slow" test script so you can see the effects of a cURL timeout.  IIRC you get something like cURL ERRNO=28.  You would be able to trap this error and ignore it.

Does that help?
0
 

Author Comment

by:CrisThompsonUK
ID: 39230605
Thanks Ray,

Looks great.  I'll check it out monday,

Regards,

Cris
0
 

Author Comment

by:CrisThompsonUK
ID: 39234206
Morning.

This is starting to work, but I'm getting a CURL connection error 7.

I have tried connecting to google using this code, and it works fine, so it's my URL...

I'm developing on a system with a domain reference so it's:
 
http://79.170.40.236/twm-test.co.uk/procedures/P4.1-NADTHREAD-0.1.php

This is not going to be stopping anything is it?

What else is going to cause the connection error?

Cris.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:CrisThompsonUK
ID: 39234230
Here's the error:

CURL FAIL: http://79.170.40.236/twm-test.co.uk/procedures/P4.1-NADTHREAD-0.1.php TIMEOUT=3, CURL_ERRNO=7 : couldn't connect to host

array(22) {
  ["url"]=>
  string(69) "http://79.170.40.236/twm-test.co.uk/procedures/P4.1-NADTHREAD-0.1.php"
  ["content_type"]=>
  NULL
  ["http_code"]=>
  int(0)
  ["header_size"]=>
  int(0)
  ["request_size"]=>
  int(0)
  ["filetime"]=>
  int(-1)
  ["ssl_verify_result"]=>
  int(0)
  ["redirect_count"]=>
  int(0)
  ["total_time"]=>
  float(0)
  ["namelookup_time"]=>
  float(0.000167)
  ["connect_time"]=>
  float(0)
  ["pretransfer_time"]=>
  float(0)
  ["size_upload"]=>
  float(0)
  ["size_download"]=>
  float(0)
  ["speed_download"]=>
  float(0)
  ["speed_upload"]=>
  float(0)
  ["download_content_length"]=>
  float(-1)
  ["upload_content_length"]=>
  float(-1)
  ["starttransfer_time"]=>
  float(0)
  ["redirect_time"]=>
  float(0)
  ["certinfo"]=>
  array(0) {
  }
  ["redirect_url"]=>
  string(0) ""
}
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39234450
From my computer, the Internet DNS allows me to connect to:
http://79.170.40.236/twm-test.co.uk/procedures/P4.1-NADTHREAD-0.1.php

... where I see:
DEBUG: Connection Status: 1
array(0) { }

I expect that there is something in your local DNS that could be causing the attempt to resolve to fail, but I can't imagine what it might be.  You might consider putting the cURL scripts on two separate servers, addressable by two separate URLs.  This would cause the DNS resolution to have to go to the internet DNS.  That would eliminate the chance that a local DNS setting is causing the problem.

http://79.170.40.236/ yields a blank page
http://79.170.40.236/twm-test.co.uk/ yields a test menu page
http://79.170.40.236/twm-test.co.uk/procedures/ yields a 403 Forbidden
0
 

Author Comment

by:CrisThompsonUK
ID: 39234496
Thanks Ray,

You see what it's currently doing...

My host said that the domain reference will refuse the loopback call, and suggested I use the secure server connection location on the CURL.

This is just a test setup, the actual implementation will be done by someone else...

Will post results...
0
 

Author Closing Comment

by:CrisThompsonUK
ID: 39234607
It's working now.

My host didn't like the CURL being on the same server - 'causing a loopback', so I'm using the secure server version of the location of the file for the call.

thanks again Ray.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39234617
Glad to help.  Thanks for the points, ~Ray
0
 

Author Comment

by:CrisThompsonUK
ID: 39234771
gonna love async. php...
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question