繁体   English   中英

在 php 中重定向 url 的最佳方法?

[英]Best way of redirecting the url in php?

我正在研究 web 应用程序(在 php 中),我需要使用一些参数重定向 url。我写了这样的代码

header("Location:http://www.xyz.com?code=2345");

这将重定向到相应的 url 但我的数据在浏览器中可见,我不希望我的数据在浏览器中可见。如何隐藏数据? 这是重定向的安全方式吗? 重定向的最佳方式是什么?

使用 CakePHP 的内置重定向 function进行重定向,但变量在 URL 中仍然可见。

然后,您需要使用 POST,如果您不想显示它,则不是 GET

如果重定向到同一主机,则可以将数据存储在 session 中,并通过 cookie 传输 session ID。

或者,您存储数据并发送 session ID。 目标系统读取session ID,根据session ID向原服务器请求原始数据。

在重定向之前如何在 session 中设置变量:

session_start();
$_SESSION['code'] = 2345;
header("Location: http://www.xyz.com");

与其在 URL 中使用 GET 参数,不如为session设置一些数据? 然后您可以正常重定向,但数据对用户不可见,它存储在服务器端。

可以将已发送到当前请求的POST字段重定向(通过使用307重定向),但人为创建它们很棘手,并且取决于用户是否启用了 javascript。 我使用这个 function,但如果用户禁用 javascript,你不应该依赖它工作。

<?php

function createHiddenFields( $value, $name = NULL )
{
    $output = "";
    if( is_array( $value ) ) {
        foreach( $value as $key => $value ) {
            $output .= self::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;
}

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();
}

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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