How to capture full HTTP request data (headers and body) with PHP?

前端 未结 3 687
一向
一向 2021-02-06 01:32

I have a problem implementing an API that works with Java, but fails to work with cURL. We\'ve gone through everything so far and there must be something that is different betwe

3条回答
  •  臣服心动
    2021-02-06 01:54

    Old question, but for anyone needing to do this in the future... The best (probably only) way would be to take full control of the server by being the server.

    Set up a socket server listening on port 80 (if this is all you need the server to do), or any other port if 80 is not available.

    That way you can capture the request completely unmodified. Examples of basic socket servers are plentiful, here is a simplified version of the latest one I implemented, which will print the full request:

    30) {
            dlog("socket_bind() failed 30 times giving up...");
            exit;
        }
    }
    
    //Start listening
    while (@socket_listen($sock, 5) === false) {
        dlog("socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)));
        sleep(1);
    }
    
    //Makes it possible to accept several simultaneous connections
    socket_set_nonblock($sock);
    
    //Keeps track of active connections
    $clients = array();
    
    dlog("server started...");
    
    while(true) {
        //Accept new connections
        while (($msgsock = @socket_accept($sock)) !== false) {
            //Prevent blocking
            socket_set_nonblock($msgsock);
    
            //Get IP - just for logging
            socket_getpeername($msgsock, $remote_address);
    
            //Add new client to array
            $clients[] = array('sock' => $msgsock, 'timeout' => time()+30, 'ip' => $remote_address);
    
            dlog("$remote_address connected, client count: ".count($clients));
        }
        //Loop existing clients and read input
        foreach($clients as $key => $client) {
            $rec = '';
            $buf = '';
            while (true) {
                //Read 2 kb into buffer
                $buf = socket_read($clients[$key]['sock'], 2048, PHP_BINARY_READ);
    
                //Break if error reading
                if ($buf === false) break;
    
                //Append buffer to input
                $rec .= $buf;
    
                //If no more data is available socket read returns an empty string - break
                if ($buf === '') break;
            }
            if ($rec=='') {
                //If nothing was received from this client for 30 seconds then end the connection
                if ($clients[$key]['timeout'] $client) {
        socket_close($client['sock']);
    }
    @socket_close($sock);
    exit;
    

    To start the server on port 8080 just run php filename.php 8080 from a shell.

提交回复
热议问题