Created
          May 10, 2017 12:08 
        
      - 
      
 - 
        
Save igoralves1/aa4657b20e48c87ce6188e24fd4e4ebd to your computer and use it in GitHub Desktop.  
    Three Ways to Make a POST Request from PHP
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <?php | |
| #https://lornajane.net/posts/2010/three-ways-to-make-a-post-request-from-php | |
| #POSTing from PHP Curl | |
| #---------------------- | |
| #First we initialised the connection, then we set some options using setopt(). | |
| #These tell PHP that we are making a post request, and that we are sending some | |
| #data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl | |
| #to give us the output as the return value of curl_exec rather than outputting it. | |
| #Then we make the call and close the connection - the result is in $response. | |
| $url = 'http://api.flickr.com/services/xmlrpc/'; | |
| $ch = curl_init($url); | |
| curl_setopt($ch, CURLOPT_POST, 1); | |
| curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); | |
| curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); | |
| $response = curl_exec($ch); | |
| curl_close($ch); | |
| #POSTing from Pecl_Http | |
| #---------------------- | |
| #This extension has a method to expressly post a request, and it can | |
| #optionally accept data to go with it, very simple and easy. | |
| #Pecl_Http has two interfaces - one procedural and one object-oriented; | |
| #we'll start by looking at the former. This is even simpler than in curl, | |
| #here's the same script translated for pecl_http: | |
| $url = 'http://api.flickr.com/services/xmlrpc/'; | |
| $response = http_post_data($url, $xml); | |
| #POSTing from Pecl_Http: the OO interface | |
| #---------------------- | |
| #Finally let's see what the OO verison of the extension looks like. | |
| #Exactly the same call as both the above examples, but using the | |
| #alternative interface, means our code looks like this: | |
| $url = 'http://api.flickr.com/services/xmlrpc/'; | |
| $request = new HTTPRequest($url, HTTP_METH_POST); | |
| $request->setRawPostData($xml); | |
| $request->send(); | |
| $response = $request->getResponseBody(); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment