Home  >  Article  >  Backend Development  >  PHP file stream simulation POST, GET value transfer_PHP tutorial

PHP file stream simulation POST, GET value transfer_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:22807browse

If we develop a social game on Facebook, we need to call its interface to obtain the user’s friend information on Facebook. At this time, we have to access an address provided by Facebook. Of course, when you access it, it needs to verify your access to prevent illegal requests. At this time, you have to post|get some parameters to it.

Such as the address below:

$url_with_get= "http://api.facebook.com/restserver.php?method=facebook.friends.get&session_key=&api_key=1232121311&v=1.0";
$post = array('sig'=>12312123234353);

How to get data from this address, briefly introduce the following code:

if(function_exists('curl_init'))
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url_with_get);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $result = curl_exec($ch);
  curl_close($ch);
}
else
{
  $content = http_build_query($post)
  $content_length = strlen($content);
  $context =
        array('http' =>
              array('method' => 'POST',
                    'user_agent' => $user_agent,
                    'header' => 'Content-Type: ' . $content_type . "\r\n" .
                                'Content-Length: ' . $content_length,
                    'content' => $content));
    $context_id = stream_context_create($context);
    $sock = fopen($url_with_get, 'r', false, $context_id);
    $result = '';
    if ($sock)
  {
    while (!feof($sock)) 
          $result .= fgets($sock, 4096);
        fclose($sock);
    }
    return $result;
  }
}

The above code uses two methods to adjust the Facebook interface. The first method determines whether the user's environment has the curl library enabled. If the library is enabled, this method is used to obtain the request. You can refer to the manual for detailed parameter explanations. Here is a reminder, since we usually need to get the return result of the calling interface, we need to set the value of CURLOPT_RETURNTRANSFER and return the result to the variable.

The second method is intuitive, converting url requests into file streams for processing.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752492.htmlTechArticleIf we develop a social game on Facebook, we need to call its interface to obtain the user's friend information on Facebook. At this time we have to access an address provided by facebook, of course...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn