PHP: fsockopen() – Sending POST data with HTTP request

I have come across many occurrences where I have needed to pass data to a websites form via POST, this is simple enough if doing via a browser as all you need to do is duplicate / copy the original form parse it with your default data possibly from a database and a bit of JavaScript code to initiate the form sending process. But what if you want to make it fully automatic via a cronjob? The code I am going to show you simply sends a POST request to the target web server and waits for the response. I have previously used this code to secretly post data to a website process the result and display the output in a different format (so it’s all hidden and the users on the website never know or see the other website). I have written a previous post found here related to the fsockopen function.

The Header String

This is the first bit of data we send to the web server it basically tells the web server the format of our information and any other related data, if we don’t send this the server might refuse the request or return something complexly different. I will go into this section in more detail now.

The Code

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.


  1. Gopalakrishnan

    Dear Mr Shane,

    Iam new to php and programming in general. I have a “PAW” webserver installed on my Android Phone. I would like to connect to other remote webservers thru php script running on the PAW server.I use php version is 5.4.2.

    I get “Warning: fsockopen(): php_network_getaddresses: gethostbyname failed. errno=111” . Iam not able to ping the remote server also thru php and system call .But Using android app(network Utility) I am able to ping google on port 80 from the same phone where the “PAW” is installed. Can you tell me what could be the problem? Very many thanks in Advance.

    • Are you using a host name or ip address? Maybe the host name is not returning an ip address?

  2. Udenewu Kingsley

    Hi thanks for the tutorial it was well explained but the my question is after a data has been posted how can you retrieve the data back.

    Thank you.

    • On line 29

      $contents .= fgets($socket, 4096);

      we read any data back from the socket into a variable called $contents. When you post any response should be in this variable. On line 32 we have


      You want to put your code below this, for example to process the response from the post request.