PHP header() redirect with POST variables

This question already has an answer here:

  • PHP Redirection with Post Parameters 9 answers

  • If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.

    // form.php
    
    <?php
    
        if (!empty($_POST['submit'])) {
            // validate
    
            if ($allGood) {
                // put data into database or whatever needs to be done
    
                header('Location: nextpage.php');
                exit;
            }
        }
    
    ?>
    
    <form action="form.php">
        <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
        ...
    </form>
    

    This can be made more elegant, but you get the idea...


    // from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
    function do_post_request($url, $data, $optional_headers = null)
    {
      $params = array('http' => array(
                  'method' => 'POST',
                  'content' => $data
                ));
      if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
      }
      $ctx = stream_context_create($params);
      $fp = @fopen($url, 'rb', false, $ctx);
      if (!$fp) {
        throw new Exception("Problem with $url, $php_errormsg");
      }
      $response = @stream_get_contents($fp);
      if ($response === false) {
        throw new Exception("Problem reading data from $url, $php_errormsg");
      }
      return $response;
    }
    

    It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.

    You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.

    链接地址: http://www.djcxy.com/p/74362.html

    上一篇: 代码点火器POST变量

    下一篇: PHP header()用POST变量重定向