获取唯一的URL代码并放入PHP会话中


Take unique URL code and place into PHP session

当用户访问我的网站并在页面中使用时,我正试图从URL中检索"活动"代码。然后,此活动代码将存储在会话中,用于访问的其余页面,因此如果用户环顾网站,它不会丢失。当然,当访问的用户在URL中没有"活动"代码(比如他们来自谷歌)时,我想给他们分配一个默认代码。我想我已经掌握了以下内容,因为它似乎在我的服务器上运行,但不确定它是否代码太重和/或存在安全风险。

<?php
session_start(); // starts the PHP session data
if ( isset( $_GET['campaign'] ) ) // check if there is a 'campaign' code in the URL as a variable
{
    $campaign = $_GET['campaign']; // first, if there is a 'campaign' code in the URL use that$campaign = 
}
elseif ( isset( $_SESSION['campaign'] ) ) // if no campaign code is in the URL but there is session data for the 'campaign' code use that - usually on other pages on the same server
{
    $campaign = $_SESSION['campaign'];
}
else // Otherwise, if no campaign code is either in the URL or session data, use the default 'campaign' code
{
    $campaign = "test1";
}
//save the 'campaign' value in a session
$_SESSION['campaign'] = $campaign; // store session data
?>

然后,无论我想在页面中添加活动代码的哪里,我都会使用:

<?php echo $campaign; ?>

提前感谢您的回答。

这取决于您以后使用该值的目的。例如,如果您将会话存储在数据库中,并且您也有该值的字段,那么您将需要首先对其进行转义。该代码没有任何其他可能的风险。