繁体   English   中英

如何将信息传递给使用 header() 调用的 php 脚本?

[英]How can I pass information to a php script called with header()?

运行 php 脚本时遇到问题,使用header()调用第二个脚本。

主脚本 (a.php) 在运行时调用第二个脚本 (b.php)。

使用此表单时,一切都按预期进行(执行 ActionA 和 ActionB):

https://example.com/a.php

使用这种其他形式时,不会发生预期的行为(ActionAX 和 ActionBX)。 而是执行 ActionAX 和 ActionB:

https://example.com/a.php?V=X

换句话说,b.php 没有得到V=X位的信息。

文件 a.php 如下所示:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<META HTTP-EQUIV="content-type" CONTENT="text/html; CHARSET=UTF-8">
<TITLE>MyWebApp</TITLE>
<STYLE>
INPUT[type='Submit'] {font-size: 19px;}
</STYLE>
</HEAD>
<BODY bgcolor="#A1E3D2">

<?php
session_start();
.....
function getVarStr()
{/* Beginning of getVarStr */
if ($_GET['V'] == 'X') performActionAX();
else  performActionA();
}/* End of getVarStr */
.....
getVarStr();
.....
if ($_GET['V'] == 'X') header("Location: ./b.php?V=X");
header("Location: ./b.php");
.....
?>
</BODY>
</HTML>

文件 b.php 如下所示:

<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,  initial-scale=1">
        <title>Extra Page</title>
        <STYLE>
                INPUT[type='Submit'] {font-size: 19px;}
        </STYLE>
</head>
<body>

<?php
session_start();
.....
function getVarStr()
{/* Beginning of getVarStr */
if ($_GET['V'] == 'X') performActionBX();
else  performActionB();
}/* End of getVarStr */
.....
getVarStr();
.....
?>
</BODY>
</HTML>

谁能指出我犯的错误?

我也尝试使用 session 变量来处理这个问题,但我遇到了完全相同的问题。

在这种情况下,我将 b.php 中的 getVarStr() 更改为:

function getVarStr()
{/* Beginning of getVarStr */
if ($_SESSION['V'] == 'X') performActionBX();
else  performActionB();
}/* End of getVarStr */

如果通过“使用 header() 调用的 php 脚本”你指的是代码中的header("Location....行,那么你对这里真正发生的事情有一个完全不正确的了解。

位置 header 只是添加到 http 响应中的字符串; header()或多或少与echo相同,除了它打算在更早的时候发生,在任何 http 回复的正文被写入之前(稍后会详细介绍)。


从功能上讲,位置header 的真正作用只是让用户 web 浏览器知道,您希望他们改为访问另一个页面/url,(在大多数情况下)它将遵守。 这与发送一个

   <script> window.location = 'https://....';</script>

在您的 html 回复中; 除了 http header 不依赖于启用的 java 脚本。


现在,实际的问题是您构建代码的方式。 在您尝试将 header 添加到 http 回复之前,您不能编写任何output。 这样做可以防止 PHP 被允许/能够添加 header。

您的header()session_start() (也间接使用header()放置 cookie)在您的代码中位于太远,无法正确定位到 function。

事实上,在您的a.phpb.php文件中,第一行( <.DOCTYPE... )已经产生了 output,这是一个大的。

always put php source above html specially if they modify cookies or session to prevent encountering "Warning: Cannot Modify Header Information – Header Already Sent" issue also you might as well put this anywhere so you know the data you applying are actually being applied


echo "SESSION NAME: " . session_name();
echo "<br>";
echo "SESSION ID: " . session_id();
echo "<br>";
echo "TIME: " . time();

暂无
暂无

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

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