?
Solved

Send only HTTP-Request - Don't need the answer

Posted on 2011-10-09
7
Medium Priority
?
424 Views
Last Modified: 2012-06-27
Hi,

I am programming a little script in PHP that sends HTTP-Requests with GET-Parameters to a server. This server needs a few of seconds to answer.
Then the server answers with HTTP 200 in the header and with lot of data in the body.

Now my question is: Is it possible to:

1) don't wait for the answer from the server... So my script doesn't need to wait for the HTTP 200 OK... This would safe time...


or if this isn't possible...

2) don't receive the big body part of the http-answer? This would safe MUCH traffic...

I don't need an answer from the server. If the request doesn't work it doesn't matter...

Suggestions?

Appendix: My PHP-Script doesn't output HTML-Code. It's a server application that runs 24h a day in a while true and communicates with the backup server...
The backup-server can't be changed.

At the moment I use curl to send the HTTP-request...
0
Comment
Question by:sourceweb
7 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 36939499
I would look at using cURL http://www.php.net/curl and the curl_setopt function. In particular

CURLOPT_CONNECTTIMEOUT       The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.

CURLOPT_NOBODY       TRUE to exclude the body from the output. Request method is then set to HEAD. Changing this to FALSE does not change it to GET.

CURLOPT_HTTPGET       TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.

0
 
LVL 11

Expert Comment

by:f_o_o_k_y
ID: 36940786
HI,
You can also use fsockopen() and create your own request and just send it without receiving and data back from the server.
Example function below.

And example usage:
send_data('http','somesite.com','80','filename.php',array('name'=>'somename','password'=>'passwordData'));

Best Regards
Fooky

PS.
The example code is from: http://stackoverflow.com/questions/2433868/how-to-create-a-tcp-client-to-send-commands-to-a-server-using-php
function send_data($type,$host,$port='80',$path='/',$data='') { 
    $_err = 'lib sockets::'.__FUNCTION__.'(): '; 
    switch($type) { case 'http': $type = ''; case 'ssl': continue; default: die($_err.'bad $type'); } if(!ctype_digit($port)) die($_err.'bad port'); 
    if(!empty($data)) foreach($data AS $k => $v) $str .= urlencode($k).'='.urlencode($v).'&'; $str = substr($str,0,-1); 

    $fp = fsockopen($host,$port,$errno,$errstr,$timeout=30); 
    if(!$fp) die($_err.$errstr.$errno); else { 
        fputs($fp, "POST $path HTTP/1.1\r\n"); 
        fputs($fp, "Host: $host\r\n"); 
        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); 
        fputs($fp, "Content-length: ".strlen($str)."\r\n"); 
        fputs($fp, "Connection: close\r\n\r\n"); 
        fputs($fp, $str."\r\n\r\n"); 

        while(!feof($fp)) $d .= fgets($fp,4096); 
        fclose($fp); 
    } return $d; 
}

Open in new window

0
 
LVL 13

Accepted Solution

by:
F Igor earned 1497 total points
ID: 36942061
You need a socket based query, so you dont need to wait for the response (decreasing socket timeout)
and dont need to download the content (only the headers, or even nothing)



$host="my.site.com";
$timeout=5;
$query="/path/to/my/page.php?param1=value1&param2=value2";
$sock = fsockopen($host,80,$err_number,$err_message,$timeout);
if ($sock){
        //Send a simple query URL
        fputs($fp, "GET $query HTTP/1.0\r\n"); 
        fputs($fp, "Host: $host\r\n");
        fputs($fp, "Connection: close\r\n\r\n"); 
       //Get only the first 512 bytes (almost headers only)
       $data=fgets($fp,512);
       //if you need to check the HTTP response code
       $responseOk=(strpos($data,"200 Ok")!==false);
       if ($responseOk) {
          //code for successfull query
      }
}else{
        die("Error: $err_number $err_message");
}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36942063
Your answer is either CURL or FSockOpen, or perhaps both as shown in this example.  Your choice will depend on the exact design of the application.  One of the applications that makes requests but does not require a response is a "monitor" that looks to see if a remote service is working.  A response means it is working, and the absence of a response means that it is not working or is working too slowly.  Here is a script that I have used to monitor another web site.  Please read it over and post back if you have any questions.  You can test it on my server here.
http://www.laprbass.com/RAY_monitor_website.php

Best regards, ~Ray
<?php // RAY_monitor_website.php
error_reporting(E_ALL);


// DEMONSTRATE HOW AN INDIVIDUAL WEB SITE MONITOR WORKS


// A WEB SITE TO MONITOR
$url = 'www.degage.com';

// COMMONLY USED PORT NUMBERS
// SEE: http://www.iana.org/assignments/port-numbers
// SEE: http://browntips.com/cpanel-and-whm-port-numbers/
$ports["HTTP"]     =    80;
$ports["FTP"]      =    21;
$ports["SSH"]      =    22;
$ports["TELNET"]   =    23;
$ports["SMTP"]     =    25;
$ports["DNS"]      =    53;
$ports["MYSQL"]    =  3306;
$ports["CPANEL"]   =  2082;
$ports["CPANEL-S"] =  2083;
$ports["WHM"]      =  2086;
$ports["WHM-S"]    =  2087;
$ports["POP3"]     =   110;
$ports["IMAP"]     =   143;
$ports["BOGUS"]    = 11111; // THIS IS EXPECTED TO FAIL

// THE RESULTS SET
$errno = $errstr = array();

// THE TIME TO ALLOW FOR CONNECTION
$timex = 1;

// TEST EACH OF THE PORTS - SEE http://php.net/manual/en/function.fsockopen.php
foreach ($ports as $port_name => $port_number)
{
    $fp
    = @fsockopen // @MAKE ERRORS SILENT
    ( $url
    , $port_number
    , $errno[$port_name]
    , $errstr[$port_name]
    , $timex
    )
    ;
}

// REPORT WHAT HAPPENED IN EASY-TO-READ FORMAT
echo "<pre>";

// OPTIONAL
// echo 'WHO: ' . exec('whoami') . PHP_EOL;

echo "URL: $url TIME: $timex" . PHP_EOL;
foreach ($errno as $port_name => $error_number)
{
    if (!$error_number)
    {
        echo PHP_EOL . "OK: $port_name $ports[$port_name]";
    }
    else
    {
        echo PHP_EOL . "ERROR $error_number: $port_name $errstr[$port_name] ON PORT $ports[$port_name]";
    }
}

// TEST WWW RESPONSE WITH CURL
$x = my_curl('http://' . $url . '/anything_will_do_here');
if (!$x)
{
    echo PHP_EOL . "ERROR WWW Response: FAIL";
}
else
{
    echo PHP_EOL . "WWW RESPONSE OK";
}

// A FUNCTION TO RUN A CURL-GET CLIENT CALL TO A FOREIGN SERVER
function my_curl($url, $timeout=4, $error_report=FALSE)
{
    $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;
}

Open in new window

0
 
LVL 9

Expert Comment

by:parparov
ID: 36942816
If you can fork or thread off your query into a separate process, you won't have to wait at all in your main loop.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36943231
@parparov: Good point.  Both CURL and FSockOpen will not wait unless they are told to wait.
0
 

Author Closing Comment

by:sourceweb
ID: 37383242
Thanks for your help.
curl is an acceptable solution...
0

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

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

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
Suggested Courses
Course of the Month16 days, 13 hours left to enroll

862 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