I’m trying to retrieve a ‘campaign’ code from the URL when a user visits my site and use it in the page. This campaign code is then stored in a session for the rest of the pages visited, so it isn’t lost should users look around the site. Of course, when users who visit don’t have a ‘campaign’ code in the URL (say they come from Google), then I want to assign them a default code. I think I’ve grasped it with the following as it appears to work on my server but am unsure if it’s too code heavy and/or a security risk.
<?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
?>
Then wherever I want to add the campaign code in the page, I will use:
<?php echo $campaign; ?>
Thanks in advance for your answers.
It depends on what for you use this value later on. If you for example store your sessions in database and you have a field for that value also, then you will need to escape it first. Don’t see any other possible risk from, that code.