Search code examples
phpapisocketswebsocketserversocket

How to get only the result of php socket request?


I try to get result without HTTP headers from socket request, but the script return the whole HTTP header like below :

$api_pause = parse_url('http://server/api.php');            

$requestArray_pause = array('user' => 'someuser', 'pass' => 'somepasse', 'source' => 'PAUSE','function' => 'field_info','field_name' => 'status','user_id'=> $user_id );
    $sock_pause = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_connect($sock_pause, $api_pause['host'], ((isset($api_pause['port'])) ? $api_pause['port'] : 80));
    if (!$sock_pause) {
        throw new Exception('Connexion echouee!');
    }
    $request_pause = '';
    if (!empty($requestArray_pause)) {
        foreach ($requestArray_pause as $k_p => $v_p) {
            if (is_array($v_p)) {
                foreach($v_p as $v2_p) {
                    $request_pause .= urlencode($v_p).'[]='.urlencode($v2_p).'&';
                }
            }
            else {
                $request_pause .= urlencode($k_p).'='.urlencode($v_p).'&';
            }
        }
        $request_pause = substr($request_pause,0,-1);
    }
    $data_pause = "POST ".$api_pause['path'].((!empty($api_pause['query'])) ? '?'.$api_pause['query'] : '')." HTTP/1.0\r\n"
    ."Host: ".$api_pause['host']."\r\n"
    ."Content-type: application/x-www-form-urlencoded\r\n"
    ."User-Agent: PHP\r\n"
    ."Content-length: ".strlen($request_pause)."\r\n"
    ."Connection: close\r\n\r\n"
    .$request_pause."\r\n\r\n";
    socket_send($sock_pause, $data_pause, strlen($data_pause), 0);
    $result_pause = '';
    do {
        $piece_pause = socket_read($sock_pause, 1024);
        $result_pause .= $piece_pause;
    }
    while($piece_pause != '');
    socket_close($sock_pause);
   
   
   echo $result_pause;  

The result of the code is :

HTTP/1.1 200 OK
Date: Wed, 16 Sep 2020 10:51:35 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Cache-Control: no-cache, must-revalidate
Pragma: no-cache
Content-Length: 1
Connection: close
Content-Type: text/html; charset=utf-8

A

In my case i wanna get just the last value "A" in this example without headers informations.


Solution

  • Socket will give you any data which is received, whatever protocol it is. Thus you're obligated to handle all the HTTP headers yourself.

    The HTTP headers are separated from the body by two line feeds (an empty line). You can just cut all the data before two empty lines:

       $body = preg_replace('/^.*?\r?\n\r?\n/s', '', $result_pause);
    

    If you want to communicate using HTTP protocol, consider using for example cURL instead of plain sockets