1

I'm using PHP 4.3.9 and am trying to POST to a url without a form using stream_context_create like below:

function do_post_request($url, $postdata) {

    $content = "";

    foreach($postdata as $key => $value)
        $content .= "$key=$value&";

    $content = urlencode($content);

    $params = array('http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $content
    ));

    $ctx = stream_context_create($params);

    $result = file_get_contents($url, false, $ctx);
    var_dump($result);

This code is taken almost word for word from the php manual and I've seen it in several places here on stackoverflow as well.

If I do file_get_contents without $ctx, var_dump($results) will display the $url properly (but without the necessary changes $_POST would cause, of course). With $ctx, var_dump($result) is NULL. So something is wrong with $ctx but I have no idea what. Am I setting up my $params incorrectly or something?

Any insight would be appreciated. If there is another way to pass POST data to a url I wouldn't mind hearing that either. But I cannot use cURL (or anything that needs installation) and I'm using an older version of php so my choices are limited.

Thanks

jlern
  • 11
  • 2
  • Are you getting any errors in the error log? Try setting error_reporting to E_ALL and see if you get anything showing to screen. Those are typically your two options though, curl and creating a stream context. Anything else would be like curl and require an installation of another library or you could do the raw fsockopen and fput of all the http headers and stuff. – Jonathan Kuhn Oct 21 '14 at 20:57
  • If you want to try another method, if you search the manual page for [fsockopen](http://www.php.net/fsockopen) for the word "POST" you can find a few functions already written. – Jonathan Kuhn Oct 21 '14 at 21:00
  • Thanks, I'll try looking into fsockopen. – jlern Oct 23 '14 at 20:41

0 Answers0