PHP Redirect with POST data

后端 未结 13 1605
不思量自难忘°
不思量自难忘° 2020-11-22 06:22

I did some research on this topic, and there are some experts who have said that it is not possible, so I would like to ask for an alternative solution.

My situation

13条回答
  •  遥遥无期
    2020-11-22 07:11

    /**
      * Redirect with POST data.
      *
      * @param string $url URL.
      * @param array $post_data POST data. Example: ['foo' => 'var', 'id' => 123]
      * @param array $headers Optional. Extra headers to send.
      */
    public function redirect_post($url, array $data, array $headers = null) {
      $params = [
        'http' => [
          'method' => 'POST',
          'content' => http_build_query($data)
        ]
      ];
    
      if (!is_null($headers)) {
        $params['http']['header'] = '';
        foreach ($headers as $k => $v) {
          $params['http']['header'] .= "$k: $v\n";
        }
      }
    
      $ctx = stream_context_create($params);
      $fp = @fopen($url, 'rb', false, $ctx);
    
      if ($fp) {
        echo @stream_get_contents($fp);
        die();
      } else {
        // Error
        throw new Exception("Error loading '$url', $php_errormsg");
      }
    }
    

提交回复
热议问题