Solved

Asynchronous PHP (that old chestnut)

Posted on 2013-06-07
9
277 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 108

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
 

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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 108

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 108

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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

706 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now