How do I send a POST request with PHP?

前端 未结 13 1584
暗喜
暗喜 2020-11-21 05:40

Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not t

相关标签:
13条回答
  • 2020-11-21 05:55

    I was looking for a similar problem and found a better approach of doing this. So here it goes.

    You can simply put the following line on the redirection page (say page1.php).

    header("Location: URL", TRUE, 307); // Replace URL with to be redirected URL, e.g. final.php
    

    I need this to redirect POST requests for REST API calls. This solution is able to redirect with post data as well as custom header values.

    Here is the reference link.

    0 讨论(0)
  • 2020-11-21 05:59

    Another alternative of the curl-less method above is to use the native stream functions:

    • stream_context_create():

      Creates and returns a stream context with any options supplied in options preset.

    • stream_get_contents():

      Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

    A POST function with these can simply be like this:

    <?php
    
    function post_request($url, array $params) {
      $query_content = http_build_query($params);
      $fp = fopen($url, 'r', FALSE, // do not use_include_path
        stream_context_create([
        'http' => [
          'header'  => [ // header array does not need '\r\n'
            'Content-type: application/x-www-form-urlencoded',
            'Content-Length: ' . strlen($query_content)
          ],
          'method'  => 'POST',
          'content' => $query_content
        ]
      ]));
      if ($fp === FALSE) {
        return json_encode(['error' => 'Failed to get contents...']);
      }
      $result = stream_get_contents($fp); // no maxlength/offset
      fclose($fp);
      return $result;
    }
    
    0 讨论(0)
  • 2020-11-21 06:01

    CURL-less method with PHP5:

    $url = 'http://server.com/path';
    $data = array('key1' => 'value1', 'key2' => 'value2');
    
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { /* Handle error */ }
    
    var_dump($result);
    

    See the PHP manual for more information on the method and how to add headers, for example:

    • stream_context_create: http://php.net/manual/en/function.stream-context-create.php
    0 讨论(0)
  • 2020-11-21 06:01

    I use the following function to post data using curl. $data is an array of fields to post (will be correctly encoded using http_build_query). The data is encoded using application/x-www-form-urlencoded.

    function httpPost($url, $data)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    

    @Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.

    I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That's why I use http_build_query().

    0 讨论(0)
  • 2020-11-21 06:01

    [Edit]: Please ignore, not available in php now.

    There is one more which you can use

    <?php
    $fields = array(
        'name' => 'mike',
        'pass' => 'se_ret'
    );
    $files = array(
        array(
            'name' => 'uimg',
            'type' => 'image/jpeg',
            'file' => './profile.jpg',
        )
    );
    
    $response = http_post_fields("http://www.example.com/", $fields, $files);
    ?>
    

    Click here for details

    0 讨论(0)
  • 2020-11-21 06:03

    If you by any chance are using Wordpress to develop your app (it's actually a convenient way to get authorization, info pages etc even for very simple stuff), you can use the following snippet:

    $response = wp_remote_post( $url, array('body' => $parameters));
    
    if ( is_wp_error( $response ) ) {
        // $response->get_error_message()
    } else {
        // $response['body']
    }
    

    It uses different ways of making the actual HTTP request, depending on what is available on the web server. For more details, see the HTTP API documentation.

    If you don't want to develop a custom theme or plugin to start the Wordpress engine, you can just do the following in an isolated PHP file in the wordpress root:

    require_once( dirname(__FILE__) . '/wp-load.php' );
    
    // ... your code
    

    It won't show any theme or output any HTML, just hack away with the Wordpress APIs!

    0 讨论(0)
提交回复
热议问题