SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2012
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    POST headers in file_get_contents

    PHP Code:
    // Create a stream
    $opts = array(
      
    'http'=>array(
        
    'method'=>"POST",
        
    'header'=>"Accept-language: en\r\n" .
                  
    "Cookie: foo=bar\r\n"
      
    )
    );

    $context stream_context_create($opts);

    // Open the file using the HTTP headers set above
    $file file_get_contents('http://www.example.com/'false$context); 
    The above code shows how to put headers in a file_get_contents, but I'm not sure how to include the POST field values. Anyone know how it works?

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,061
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    There's a good example in the manual:

    PHP Code:
    <?php
    $data 
    = array ('foo' => 'bar''bar' => 'baz');
    $data http_build_query($data);

    $context_options = array (
            
    'http' => array (
                
    'method' => 'POST',
                
    'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                    
    "Content-Length: " strlen($data) . "\r\n",
                
    'content' => $data
                
    )
            );

    $context context_create_stream($context_options)
    $fp fopen('https://url''r'false$context);
    ?>
    Where $data is the POST data to send to the server.

    Any particular reason you're not using cURL btw? It's lot easier and more readable than working with streams IMO.
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  3. #3
    SitePoint Enthusiast
    Join Date
    Apr 2012
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ScallioXTX View Post
    Any particular reason you're not using cURL btw? It's lot easier and more readable than working with streams IMO.
    I'm not sure how to use curl well and file_get_contents is so easy. Thanks for the info Scallio!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •