0

Doing a PHP call without cURL (as found here: http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/), but the response will take about 10-15 seconds to come back. It currently just comes up with an error. Any idea how to get this working? I've tried set_time_limit to no avail.

Code:

function DoPostRequest($url, $data, $optional_headers = null)
{
    $params = array('http' => array('method' => 'POST', 'content' => $data));
    if($optional_headers != null) {
        $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    try {
        $fp = fopen($url, 'rb', false, $ctx);
        $response = stream_get_contents($fp);
    } catch (Exception $e) {
      echo 'Exception: '.$e->getMessage();
    }
    return $response;
}

And the error:

Notice: fopen(): Content-type not specified assuming application/x-www-form-urlencoded in <php url> on line 81 Warning: fopen(http://localhost:59396/Update.ashx): failed to open stream: HTTP request failed! HTTP/1.1 100 Continue in <php url> on line 81 Warning: stream_get_contents() expects parameter 1 to be resource, boolean given in <php url> on line 82 bool(false)
2
  • 1
    What is the error that appears? Commented Apr 27, 2012 at 15:23
  • Please see edit. I've slightly changed the code to show full error. Commented Apr 27, 2012 at 15:33

1 Answer 1

6

Try

function DoPostRequest($url, $data, $optional_headers = null) {
    $params = array (
            'http' => array (
                    'method' => 'POST',
                    'content' => $data,
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
                    "Content-Length: " . strlen ( $data ) . "\r\n" 
            ) 
    );
    if ($optional_headers != null) {
        $params ['http'] ['header'] = $optional_headers;
    }
    $ctx = stream_context_create ( $params );
    try {
        $fp = fopen ( $url, 'rb', false, $ctx );
        $response = stream_get_contents ( $fp );
    } catch ( Exception $e ) {
        echo 'Exception: ' . $e->getMessage ();
    }
    return $response;
}

Change Content-Type to what you want .. JSON, XML anything

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.