We help IT Professionals succeed at work.

file_get_content timeout with ajax

jmsloan
jmsloan used Ask the Experts™
on
I have a test script that connects to a webpage via ajax and returns a response.  All is working accept if the network is down.  The timeout takes to long to return a response.  I would like to manually dial the timeout to 10 seconds instead of the default.  Below is my test.html page.  Attach is my php script that gets called by ajax.    I have tried adding option to the file_get_contents but is doesn't seem to work.

//options
$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 5,
        'ignore_errors' => true
        )
    )
);
//////////////////////


<html>
<head>
function getXmlHttpRequestObject() {
   if (window.XMLHttpRequest) {
      return new XMLHttpRequest();
   } else if(window.ActiveXObject) {
      return new ActiveXObject("Microsoft.XMLHTTP");
   } else {
      alert("Please upgrade your browser to gain full functionality.");
   }
}
 
//Our XmlHttpRequest object
var AJAXObject = getXmlHttpRequestObject();
 
function ajaxcall(url,functionname){
   if (AJAXObject.readyState == 4 || AJAXObject.readyState == 0) {
      AJAXObject.open("GET", url, true);
      AJAXObject.onreadystatechange = functionname;
      AJAXObject.send(null);
   }
}
 
function testScript(){
  var url = "test.php";
  ajaxcall(url,checkTestScript);
}
 
function checkTestScript(){
   if(AJAXObject.readyState == 4){
      alert(AJAXObject.responseText);
   }
}
 
</script>
 
</head>
<body>
<input type='button' onClick="testScript();" value="Click Here for Test"> Please Click The Button
</body>
</html>
<?php

$url = "https://www.testwebsite/";
 
$str = file_get_contents($url);
 
$field1 = substr($str,0,strpos($str," "));
$field2 = substr($str,strpos($str," ")+1);
 
if (preg_match("/APPROVED/i", "$str")) {
   $field1 = substr($str,0,strpos($str," "));
   $field2 = substr($str,strpos($str," ")+1);
   echo "1|$field1|$field2";
}else{
   echo "0|$str";
}

?>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Have you checked the allow_url_fopen directive is turned on in your INI settings?

Author

Commented:
It is on
Yeah, my bad just reread your post - I misread your question. My apologies.
Most Valuable Expert 2011
Top Expert 2016
Commented:
Instead of file_get_contents() try using a CURL function like this one.  You can set the timeout and diagnostic returns.

HTH, ~Ray
<?php // RAY_curl_example.php
error_reporting(E_ALL);



// A FUNCTION TO RUN A CURL-GET CLIENT CALL TO A FOREIGN SERVER
function my_curl
( $url
, $get_array=array()
, $timeout=3
, $error_report=TRUE
)
{
    // PREPARE THE ARGUMENT STRING IF NEEDED
    $get_string = '';
    foreach ($get_array as $key => $val)
    {
        $get_string
        = $get_string
        . urlencode($key)
        . '='
        . urlencode($val)
        . '&';
    }
    $get_string = rtrim($get_string, '&');
    if (!empty($get_string)) $url .= '?' . $get_string;

    // START CURL
    $curl = curl_init();

    // HEADERS AND OPTIONS APPEAR TO BE A FIREFOX BROWSER REFERRED BY GOOGLE
    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE BLANK

    // SET THE CURL OPTIONS - SEE http://php.net/manual/en/function.curl-setopt.php
    curl_setopt( $curl, CURLOPT_URL,            $url  );
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  );
    curl_setopt( $curl, CURLOPT_HTTPHEADER,     $header  );
    curl_setopt( $curl, CURLOPT_REFERER,        'http://www.google.com'  );
    curl_setopt( $curl, CURLOPT_ENCODING,       'gzip,deflate'  );
    curl_setopt( $curl, CURLOPT_AUTOREFERER,    TRUE  );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE  );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE  );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout  );

    // RUN THE CURL REQUEST AND GET THE RESULTS
    $htm = curl_exec($curl);

    // ON FAILURE HANDLE ERROR MESSAGE
    if ($htm === FALSE)
    {
        if ($error_report)
        {
            $err = curl_errno($curl);
            $inf = curl_getinfo($curl);
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            var_dump($inf);
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS RETURN XML / HTML STRING
    curl_close($curl);
    return $htm;
}




// USAGE EXAMPLE - PUT YOUR FAVORITE URL HERE
$url = "http://finance.yahoo.com/d/quotes.csv";

// PUT YOUR ARRAY OF KEY=>VALUE PAIRS HERE
$arg = array
( 's' => 'lulu'
, 'f' => 'snl1c1ohgvt1'
)
;

// MAKE THE CALL
$htm = my_curl($url, $arg, 2, TRUE);
if (!$htm) die("NO $url");

// SHOW WHAT WE GOT
echo "<pre>";
var_dump($arg);
echo PHP_EOL . $url;
echo PHP_EOL . htmlentities($htm);
echo PHP_EOL;




// TRY ANOTHER URL WITHOUT ARGUMENTS
$url = 'http://twitter.com';
$htm = my_curl($url);
echo PHP_EOL . $url;
echo PHP_EOL . htmlentities($htm);
echo PHP_EOL;

Open in new window

Author

Commented:
I get the following error when I try to use the CURL Function above

CURL FAIL: https://mytestwebsite.com:8443/testdir/webAuth.do?id=1234acct=1234?s=lulu&f=snl1c1ohgvt1 TIMEOUT=2, CURL_ERRNO=60array(19) { ["url"]=> string(147) "https://mytestwebsite.com:8443/testdir/webAuth.do?id=1234acct=1234?s=lulu&f=snl1c1ohgvt1" ["http_code"]=> int(0) ["header_size"]=> int(0) ["request_size"]=> int(0) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(-8179) ["redirect_count"]=> int(0) ["total_time"]=> float(0) ["namelookup_time"]=> float(0.294436) ["connect_time"]=> float(0.339184) ["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) } NO https://mytestwebsite.com:8443/testdir/webAuth.do?id=1234acct=1234


Does it matter that I'm actually connecting with https: to a specific port and using GET variables?

https://mytestwebsite.com:8443/testdir/webAuth.do?id=1234&acct=1234

Author

Commented:
I guess my question is.  

What is the best way to send a GET request via https to a specific port and echo the response?  Also a timeout of no more than 10 seconds must be in included.

Most Valuable Expert 2011
Top Expert 2016

Commented:
The curl error #60 appears to be related to the use of SSL.
http://php.net/manual/en/function.curl-errno.php

What is the actual URL of your test script on the HTTPS site?  I'll try to read it and show you my code.  Thanks, ~Ray
Most Valuable Expert 2011
Top Expert 2016

Commented:
This page might have something useful...
http://www.php.net/manual/en/function.curl-setopt.php

Author

Commented:
I can't give it out because it is a bank site with account info.
Most Valuable Expert 2011
Top Expert 2016

Commented:
You can't give us a test site?  How can we test?

Author

Commented:
I added

curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );

to you script and it worked.

Author

Commented:
Thank you for educating me in the art of CURL
Most Valuable Expert 2011
Top Expert 2016

Commented:
Great!  Congratulations.  I'll have to see if it works with non-SSL sites, then if so I can leave that in the code.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Yes, that line has no effect on non-HTTPS sites.  Thanks for sharing! ~Ray