简体   繁体   中英

PHP Redirect, Keep POSTs

I have an html page with a checkbox form. The form has its action pointing to a PHP script. The PHP script collects the POST variables just fine but obviously a blank screen displays because it goes to www.example/script.php once executed.

How I do get PHP to go to another URL for more form submission information while keeping those POSTs intact?

header() and metaredirect seem to overrule everything and not collect the data... How do I collect that data into POSTs and then automatically go to another html page for another form with a PHP script attached as its action?

Thanks and sorry if I worded this in a confusing manner.

您可以将$_POST变量存储在$_SESSION ,然后在表单的最后部分完成时提交它们,或者您可以让中间页面将这些值存储为隐藏输入并将它们提交到最终页面。

I've found that this code works almost all the time (except in some cases where you want to forward using custom post data and the client doesn't support javascript).

This is done by abusing the 307 Temporary Redirect which seems to forward POST data, or by creating a self submitting javascript form.

This is a hack though, only use it if you MUST forward the POST data.

<?php

function redirectNowWithPost( $url, array $post_array = NULL )
{
    if( is_null( $post_array ) ) { //we want to forward our $_POST fields
        header( "Location: $url", TRUE, 307 );
    } elseif( ! $post_array ) { //we don't have any fields to forward
        header( "Location: $url", TRUE );
    } else { //we have some to forward let's fake a custom post w/ javascript
        ?>
<form action="<?php echo htmlspecialchars( $url ); ?>" method="post">
<script type="text/javascript">
//this is a hack so that the submit function doesn't get overridden by a field called "submit"
document.forms[0].___submit___ = document.forms[0].submit;
</script>
<?php print createHiddenFields( $post_array ); ?>
</form>
<script type="text/javascript">
document.forms[0].___submit___();
</script>
        <?php
    }
    exit();
}

function createHiddenFields( $value, $name = NULL )
{
    $output = "";
    if( is_array( $value ) ) {
        foreach( $value as $key => $value ) {
            $output .= createHiddenFields( $value, is_null( $name ) ? $key : $name."[$key]" );
        }
    } else {
        $output .= sprintf("<input type=\"hidden\" name=\"%s\" value=\"%s\" />",
            htmlspecialchars( stripslashes( $name ) ),
            htmlspecialchars( stripslashes( $value ) )
        );
    }
    return $output;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM