开发者

Having trouble receiving data back from post using php fopen with a stream context

开发者 https://www.devze.com 2023-02-07 03:14 出处:网络
I\'ve been trying to figure out where my error is in this particular function. It\'s very similar to a posted function online with a few minor tweaks.Anyway, I have a specific url in the variable $PAY

I've been trying to figure out where my error is in this particular function. It's very similar to a posted function online with a few minor tweaks. Anyway, I have a specific url in the variable $PAYMENTPAGE->ipa_url. I'm trying to post to this and simply have the return data be a die('test') to verify the connection is going through properly. Instead I keep getting a blank page.

I have managed to get it working using the curl extension but would prefer to simply use streams as they work out of the box with any extensions. I know the connection is being ma开发者_StackOverflow中文版de, because I was receiving exception errors which I fixed, but now I'm just having trouble figuring out why no information is being returned from the post.

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);
    $get_stream = true;
    try{
        $fp = @fopen($url, 'rb', false, $ctx);
        if (!$fp) {
             throw new Exception("Problem creating stream from $url, \n\t".implode("\n\t", error_get_last()));
        }
        $response = @stream_get_contents($fp);
        if ($response === false) {
           throw new Exception("Problem reading data from $url, \n\t".implode("\n\t", error_get_last()));
        }
        $get_stream = false;
    } catch(Exception $e){
        mcFatal("Error(".date('Y-m-d h:i:s').'):'.$e->getMessage()."\n");
    }


    if($get_stream){
        return false;
    }

    return $response;
}


If you are using Ubuntu: This is a bug in the PHP version Ubuntu ships. See https://bugs.launchpad.net/ubuntu/+source/php5/+bug/650779 for more details.


Is there any reason why you are not using an http protocol library, such as cURL? It handles the streams for you, and can produce information in the event of an error.

function doPostRequest($url, $data, $optional_headers = null) 
{
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

   //include array of additional headers
   if (count($optional_headers)) {
      curl_setopt($ch, CURLOPT_HTTPHEADER, $optional_headers);
   }

   return curl_exec($ch);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消