将多个变量传递到 url 中的另一个页面

2022-08-30 10:54:51

我正在使用这样的会话将一个变量传递到URL中的另一个页面,但似乎我无法将另一个变量连接到同一URL并在下一页中成功检索它

页码 1

session_start();
$event_id = $_SESSION['event_id'];
echo $event_id;

$url = "http://localhost/main.php?email=" . $email_address . $event_id;     

页码 2

if (isset($_GET['event_id'])) {
$event_id = $_GET['event_id'];}
echo $event_id;

echo $event_id在第2页上显示错误,但如果我在这里只使用喜欢Undefined variableevent_id$url

 $url = "http://localhost/main.php?event_id=" . $event_id;

这工作正常,但我需要能够在url中使用这两个变量,以便页面2可以检索它们。


答案 1

使用 & 符号将变量粘合在一起:&

$url = "http://localhost/main.php?email=$email_address&event_id=$event_id";
//                               ^ start of vars      ^next var

答案 2

简短的回答:

这是您尝试做的事情,但它会带来一些安全和编码问题,因此请不要这样做。

$url = "http://localhost/main.php?email=" . $email_address . "&eventid=" . $event_id;

长答案:

查询字符串中的所有变量都需要进行 urlen 编码,以确保正确传输。您永远不应该在URL中传递用户的个人信息,因为URL非常泄漏。URL最终出现在日志文件,浏览历史记录,引用标头等中。这个清单不胜枚举。

至于正确的url编码,可以使用urlencode()http_build_query()来实现。以下任一项都应该有效:

$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);

$vars = array('email' => $email_address, 'event_id' => $event_id);
$querystring = http_build_query($vars);
$url = "http://localhost/main.php?" . $querystring;

此外,如果 在您的会话中,您实际上不需要传递它就可以从不同的页面访问它。只需调用session_start(),它应该可用。$event_id


推荐