2

I have the following code that works on PHP5 to send a HTTP POST without using cURL. I would like this to work on PHP 4.3.0 and above:

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Type: application/json\r\n",
        'content' => $query
    )
);
$context  = stream_context_create($opts);
$result = file_get_contents($url, false, $context);

HTTP context is only supported on PHP5. Is there anyway to make this work with PHP 4.3.0 - I need a fallback method if PHP5 or cURL is not installed.

Luke
  • 6,195
  • 11
  • 57
  • 85
  • What exactly doesn't work? Do you get any specific error? – gpmcadam Mar 19 '10 at 14:39
  • file_get_contents doesn't allow the context on PHP 4 I receive an error that file_get_contents only accepts 2 parameters. – Luke Mar 19 '10 at 14:52
  • Coding a solution that will work reliably in PHP4 is more effort than it's worth - get your customers to upgrade. OTOH, assuming you are stark raving mad, you may want to look at http://sourceforge.net/projects/snoopy/ – symcbean Mar 19 '10 at 15:01
  • Thank you, the snoopy project was helpful for a reference as well as a HTTP debugger. – Luke Mar 19 '10 at 15:31

2 Answers2

0

You shouldn't be using PHP 4. It is discontinued and so doesn't receive any security patches.

If you want to take a look writing something yourself, you want to start with fsockopen(). There is a basic example that may do what you want and it shouldn't be too hard to convert it to a POST request. I used a packet sniffer (Wireshark) to get HTTP samples that I could (in essence) copy and paste into my PHP application however the specifications and a lot of samples are available online.

Yacoby
  • 54,544
  • 15
  • 116
  • 120
  • 1
    Word of caution: use appropriate line endings for the system you'll open a socket to or spend days wondering wth your code doesn't work. Do I speak from experience? I wish I wasn't. – Manos Dilaverakis Mar 19 '10 at 15:19
  • 1
    Unfortunately we don't have control over the systems that are running PHP 4.3.0. However I do have control of the system that I am calling the POST, so the line endings won't change. – Luke Mar 19 '10 at 15:29
0

Something like the following will do the trick if anyone needs help with this.

        $headers = "POST $url 1.1\r\n"; 
        $headers .= "Content-type: application/x-www-form-urlencoded\r\n";
        $headers .= "Content-Type: application/json\r\n";
        $headers .= "Accept: application/json\r\n";
        if (!empty($body)) {
            $headers .= "Content-length: " . strlen($body) . "\r\n";
        }
        $headers .= "\r\n";

        $body = $query;

        if ($fp = fsockopen($host, 80, $errno, $errstr, 180)) {
            fwrite($fp, $headers . $body, strlen($headers . $body));
            fclose();
        }
Luke
  • 6,195
  • 11
  • 57
  • 85