When I navigate to a page which is locked (in other words when the box which states you have to Continue appears, I am getting undefined $_SESSION variables. Before I included the if (allowed_in()=== "Allowed"){ statement, I was not getting any undefined $_SESSION variables but as now need that if statement, Im starting to get those variable errors.
For the $_SESSION undefined errors, is it because I am placing the $_SESSION variables in the wrong place?
Below is an example QandATable.php order of code looks like:
<?php
ini_set('session.gc_maxlifetime',12*60*60);
ini_set('session.gc_divisor', '1');
ini_set('session.gc_probability', '1');
ini_set('session.cookie_lifetime', '0');
require_once 'init.php';
//12 hours sessions
session_start();
include('steps.php'); //exteranlised steps.php
?>
<head>
<?php
if (isset($_POST['id'])) {
$_SESSION['id'] = $_POST['id'];
}
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
?>
</head>
<body>
<?php
//once session is expired, it should log the user out, but at mo this isn't happening
if ((isset($username)) && (isset($userid))){ //checks if user is logged in
if (allowed_in()=== "Allowed"){
//QandATable.php code:
}else{
$page = allowed_in()+1;
?>
<div class="boxed">
Continue with Current Assessment
<?php
}
}else{
echo "Please Login to Access this Page | <a href='./teacherlogin.php'>Login</a>";
//show above echo if user is not logged in
}
?>
Below is the full steps.php:
<?php
$steps = array(1 =>'create_session.php',2 => 'QandATable.php',3 => 'individualmarks.php',4 => 'penalty.php',5 => 'penaltymarks',6 => 'complete.php');
function allowed_in($steps = array()){
// Track $latestStep in either a session variable
// $currentStep will be dependent upon the page you're on
if(isset($_SESSION['latestStep'])){
$latestStep = $_SESSION['latestStep'];
}
else{
$latestStep = 0;
}
$currentStep = basename(__FILE__);
$currentIdx = array_search($currentStep, $steps);
$latestIdx = array_search($latestStep, $steps);
if ($currentIdx - $latestIdx == 1 )
{
$currentIdx = $_SESSION['latestStep'];
return 'Allowed';
}
return $latestIdx;
}
?>
session_start() must go before any content.
Note:
To use cookie-based sessions, session_start() must be called before
outputing anything to the browser.
http://php.net/manual/en/function.session-start.php
Related
I'm trying to create a counter in PHP that will count how many times within a set timeframe an IP can visit a page and when it hits a download counter within that timeframe it re-directs. The approach I've seen recommended was doing this with a session after referencing several Q&As:
PHP function to increment variable by 1 each time
How to not increase page/post view count with refresh?
php increment variable value with 1 when submit
I also looked at:
How do I count unique visitors to my site?
adding counter to php page to count the unique visitors
I do not have much experience with cookies and sessions so I believe that is where I fault in my code. If you have any suggestions on better implementation than what I am doing please advise.
The code:
$jsonFile = 'foobar.json';
$theJSON = file_get_contents($jsonFile);
$jsonArray = json_decode($theJSON, true);
$theIP = "123.123.123"; // $_SERVER['REMOTE_ADDR']
$thisTime = date("H:i");
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$downloadHits = 5; // set value for testing purposes
$timeLater = date("H:i", strtotime($thisTime)+(($addMin*60)+($addHour*60*60)));
if (!empty($theIP) && !empty($jsonArray)) {
foreach ($jsonArray as $value) {
if (in_array($theIP, $value, true)) {
echo "yes"; // header('Location: https://www.url/darthvader.com');
exit();
} else {
if ($thisTime <= $timeLater) { // where my issue starts
echo $timeLater; // for testing
session_start();
$counter = $_SESSION['promo_number'];
$counter++;
if ($counter == $downloadHits && file_exists($jsonFile)) {
$currentData = file_get_contents($jsonFile);
$currentArray = json_decode($currentData, true);
$theStuff = array(
'ip' => "123.123.123", // $_SERVER['REMOTE_ADDR']
'date' => date("H:i"),
'time' => date("m.d.y")
);
$currentData[] = $theStuff;
$finishData = json_encode($currentData);
} else {
echo 'bar'; // for testing
session_unset();
session_destroy();
}
}
}
}
} else {
echo '<span style="color:red; font-weight:bold;">empty file</span>';
}
What I am trying to do is count the times an IP visits a post within a set time and if it hits that count redirect the IP. I do know that the IP can be spoofed and I am not worried about that plus I would prefer to not use a database at this time. So how can I properly set a session to count the hits and if the IP hits the post in set count it redirects the IP?
EDIT:
After doing some reading and the help from the comment and answer I've made an edit that I hope explains what I am trying to do. After researching further I ran across:
session_destroy() after certain amount of time in PHP
How do I expire a PHP session after 30 minutes?
which led me to code:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$addMin = 2; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$targetedHits = 1; // set value for testing purposes
$timeLater = time() + ($addMin*60) + ($addHour*60*60);
$_SESSION['expire'] = $timeLater;
if (!empty($theIP) && !empty($jsonArray)) {
//look for the $theIP
if (in_array($theIP,array_column($jsonArray,'ip'))) {
echo 'IP found in json';
exit;
}
// look at the time the session was set, add to counter or delete session
if ($_SESSION['count'] = isset($_SESSION['count']) && time() < $_SESSION['expire'] ) {
echo 'adding to count';
$_SESSION['count'] + 1;
// limit reached. Add IP to blacklist
if ($_SESSION['count'] > $targetedHits) {
echo 'session count reached max';
$jsonArray[]=[
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
// save changes
file_put_contents($jsonFile,json_encode($jsonArray));
session_destroy();
exit;
}
} elseif (time() > $_SESSION['expire']) {
echo 'nuking session and counter';
session_destroy();
} else {
echo 'setting count to 1';
$_SESSION['count'] = 1;
}
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
But sadly now the $_SESSION['count'] + 1; no longer increments.
Darth_Vader you're almost there. There are a couple of issues with your script.
You never save the count in session, so you have no way to retrieve it later
You start your session late in the script. This is poor practice because it will break as soon as you echo something higher up or forget and try to use $_SESSION higher up
You read your JSON file and decode it twice unnecessarily, wasting system memory
You never save the changes you make to the JSON
You call session_unset() and session_destroy() after a successful download, so the count would be lost even if you were trying to save it properly
My modifications:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$thisTime = time();
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$downloadHits = 5; // set value for testing purposes
$timeLater = $thisTime + ($addMin*60) + ($addHour*60*60);
if(empty($theIP)){
echo 'empty file';
exit;
}
//look for the $theIP in the 'ip' column
if(in_array($theIP,array_column($jsonArray,'ip'))){
echo 'IP found in json';
exit;
}
if($thisTime > $timeLater){//not sure what you want to do here
exit;
}
//increment the count, or set it to 1 to begin
$_SESSION['count'] = isset($_SESSION['count'])? $_SESSION['count']+1 : 1;
if($_SESSION['count']>=$downloadHits){//limit reached. Add IP to blacklist
$jsonArray[]=[
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
//save changes
file_put_contents($jsonFile,json_encode($jsonArray));
exit;
}
echo 'good to go!'; //allow the download
Happy coding.
Figured it out after spending some time under the session tag. These two questions were helpful:
How do check if a PHP session is empty?
How can I clear my php session data correctly?
Which led me to code:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$targetedHits = 5; // set value for testing purposes
$timeLater = time() + ($addMin*60) + ($addHour*60*60);
if (empty($_SESSION['count'])) {
$_SESSION['expire'] = $timeLater;
}
if (!empty($theIP) && !empty($jsonArray)) {
// look for the $theIP
if (in_array($theIP,array_column($jsonArray,'ip'))) {
$_SESSION['count'] = 0;
session_destroy();
echo 'IP found in json';
exit;
}
if (time() < $_SESSION['expire']) {
echo 'below the time ';
$_SESSION['count'] = isset($_SESSION['count'])? $_SESSION['count'] + 1 : 1;
if ($_SESSION['count'] > $targetedHits) {
echo 'session count reached max ';
$jsonArray[] = [
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
// save changes
file_put_contents($jsonFile,json_encode($jsonArray));
unset($_SESSION['count']);
session_destroy();
exit;
}
} elseif (time() > $_SESSION['expire']) {
echo 'nuking session and counter';
$_SESSION['count'] = 0;
unset($_SESSION['expire']);
}
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
I hope the above helps the next person because I didn't really know anything about sessions and it has been an adventure getting this to work this evening.
I am writing code for math problems -- they follow a format, with randomly generated variables, and then I lock in the variables per the code below. What isn't working -- form03 allows the user to finish the page of math problems and to reset for another. I need to destroy the session on that condition. But even when I enter data in form03, so that it isset, the old session values remain.
???
require_once 'random.php';
require_once 'forms-functions.php';
if (isset($_SESSION['z'])) {
$_SESSION['y'] = "";
session_start();
session_destroy();
}
session_start();
if (isset($_SESSION['y'])) {
echo "hello isset<br>";
$x01 = $_SESSION['x01'];
$x02 = $_SESSION['x02'];
$output01b = $_SESSION['output01b'];
$output02b = $_SESSION['output02b'];
} else {
echo "hello else<br>";
ob_start();
random1();
$output01 = ob_get_clean();
$output01b = "single string: ".$output01."";
$x01 = $x;
ob_start();
random1();
$output02 = ob_get_clean();
$output02b = "single string: ".$output02."";
$x02 = $x;
$_SESSION['x01'] = $x01;
$_SESSION['x02'] = $x02;
$_SESSION['output01b'] = $output01b;
$_SESSION['output02b'] = $output02b;
$y = "1";
$_SESSION['y'] = $y;
}
echo $output01b;
$user_input01 = form01('user_input01');
echo $output02b;
$user_input02 = form02('user_input02');
$user_input03 = form03('user_input03');
if(isset($user_input03)) {
$z = 1;
$_SESSION['z'] = $z;
echo "hello \$z";
}
You need to call session_start() before you try to access the session variable z. And you need to set the new session variable y after you destroy the old session and start a new one.
session_start();
if (isset($_SESSION['z'])) {
session_destroy();
session_start();
$_SESSION['y'] = "";
}
Surprisingly, I couldn't find anything relevant on the internet/stackoverflow, while I would think it's often used.
My form is basically a file upload form, and I want to set a minimum time between form submits using Javascript or PHP (PHP prefered), to protect the form from bots etc.
The only thing I could came up with was a cookie/session, but those can be deleted/cleared/modified.
storing the submitter ip you can use:
memcache key which expires after minimum time
temp file "flag"
make life harder for the bot using captcha
In the end, I used a simple MySQLi table.
The MySQLi table contained three columns,
'ID' (the User's Login ID),
TimesUploaded (Times uploaded within a specified, default 15, amount of minutes),
TimeLastUploaded (The time the user uploaded its first of the maximum, TimesUploaded, documents)
The Code:
1.Function getuploaduse()
function getuploaduse(){
require('connect.php'); //Connect with the MySQL database
$theid = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `UploadUse` WHERE ID=\"".$_SESSION['id']."\""));
if($theid[0] == 0){
return 'makenew'; //Make a new row
} else {
return mysqli_fetch_array(mysqli_query($link, "SELECT TimesUploaded,TimeLastUploaded FROM `UploadUse` WHERE ID=\"".$_SESSION['id']."\"")); //Pass on TimesUploaded and TimeLastUploaded
}
}
2.PHP in Upload Page
//Set variables
$block = 'false';
$mintime = 15; //A minimum of 15 minutes between $maxuploads
$maxuploads = 3;
$contents = getuploaduse();// [0] => TimesUploaded, [1] => TimeLastUploaded
if(isset($_POST['thetitle'])){ //If users uploads
if($contents != 'makenew'){
if($contents[0] == $maxuploads){
$block = (time() - $contents[1]);
if($block < ($mintime * 60)){
$block= 'false';
mysqli_query($link, "UPDATE `UploadUse` SET `TimesUploaded`=1,`TimeLastUploaded`='".time()."' WHERE `ID`='".$_SESSION['id']."'"); //Reset
} else {
$block = $mintime - round($block / 60);
}
} else {
$block = (time() - $contents[1]);
if($block >= ($mintime * 60)){
$block= 'false';
mysqli_query($link, "UPDATE `UploadUse` SET `TimesUploaded`=1,`TimeLastUploaded`='".time()."' WHERE `ID`='".$_SESSION['id']."'"); //Reset
} else {
$increased = ($contents[0] + 1);
mysqli_query($link, "UPDATE `UploadUse` SET `TimesUploaded`='".$increased."' WHERE `ID`='".$_SESSION['id']."'"); //Increase
if($increased == $maxuploads){
$block = $mintime - round($block / 60);
} else {
$block = 'false';
}
}
}
} else {
mysqli_query($link, "INSERT INTO UploadUse(ID,TimesUploaded,TimeLastUploaded) VALUES('".$_SESSION['id']."','1','".time()."')");
}
//Place your upload script here and set $success to something to show your success and not the 'Maximum uploaded'
}
//Block if user doesn't upload (so when he tries to access the upload page)
if($contents != 'makenew' && $block == 'false'){
$contents = getuploaduse();// [0] => TimesUploaded, [1] => TimeLastUploaded
if($contents[0] == $maxuploads){
$block = (time() - $contents[1]);
if($block < ($mintime * 60)){
$block = $mintime - round($block / 60);
} else {
$block = 'false';
}
}
}
3.With your uploadform
<? if($block == 'false'): ?>
<!-- Your upload form here -->
<?php elseif(isset($success)): ?>
<!-- Success here-->
<?php else: ?>
<div class="alert alert-block alert-danger fade in">
<h4>You exceeded the maximum uploads per <?php echo $mintime; ?> min.</h4>
<p>You may upload maximum <?php echo $maxuploads ?> documents per <?php echo $mintime; ?> minutes. You have to wait for <span class="label label-danger"><span id="updatemin"><?php echo $block; ?></span> minute<? if($block > 1){echo 's';} ?></span>.</p><br />
</div>
<? endif; ?>
4.In my HTML Header (So when the users is blocked, it will update the minutes remaining)
<?php if($block != 'false'):?><meta HTTP-EQUIV="REFRESH" content="60; url=/Upload"><? endif; ?>
If you think this code is useful, please vote my (own) answer up, as I did spend time on this code. (I'm a beginner, and to me, this code is something to be proud of, especially since I haven't used tutorials or other answers)
I am trying to create something like a lock and unlock pages feature. The user has to go thorugh the pages in this order:
$steps = array(1 =>'create_session.php',2 => 'QandATable.php',3 => 'individualmarks.php',4 => 'penalty.php',5 => 'penaltymarks',6 => 'complete.php');
So what should happen is that if the user is on a page a they SHOULD BE on, then that page shold be unlocked (or in other words the if statement is met where it shows the page's code), if the user accesses a page which they should not be on, then that page beocmes locked (the else statement is met where it displays the div with the Continue hyperlink`).
The problem is that even though the user is on the correct page, the page is still "locked" when it should be unlocked so the user can use the page. At moment all pages accessed are locked so my question is that how can I unlock a page when the user is on a correct page?
Below is an example create_session.php:
<?php
session_start();
include ('steps.php'); //exteranlised steps.php
?>
<head>
...
</head>
<body>
<?php
if ((isset($username)) && (isset($userid))) { //checks if user is logged in
if (allowed_in() === "Allowed") {
//create_session.php code:
} else {
$page = allowed_in() + 1;
?>
<div class="boxed">
Continue with Current Assessment
<?php
}
} else {
echo "Please Login to Access this Page | <a href='./teacherlogin.php'>Login</a>";
//show above echo if user is not logged in
}
?>
Below is the full steps.php:
<?php
$steps = array(1 =>'create_session.php',2 => 'QandATable.php',3 => 'individualmarks.php',4 => 'penalty.php',5 => 'penaltymarks',6 => 'complete.php');
function allowed_in($steps = array()){
// Track $latestStep in either a session variable
// $currentStep will be dependent upon the page you're on
if(isset($_SESSION['latestStep'])){
$latestStep = $_SESSION['latestStep'];
}
else{
$latestStep = 0;
}
$currentStep = basename(__FILE__);
$currentIdx = array_search($currentStep, $steps);
$latestIdx = array_search($latestStep, $steps);
if ($currentIdx - $latestIdx == 1 )
{
$currentIdx = $_SESSION['latestStep'];
return 'Allowed';
}
return $latestIdx;
}
?>
Something like this, though this probably won't work as is:
$allowed_page = $_SESSION['latestStep'];
if ($steps[$allowed_page] == $_SERVER['SCRIPT_NAME']) {
... allowed to be here ...
}
Basically, given your array of "steps", you store the index of the allowed page in the session as you. As they complete a page and "unlock" the next page, you increment that index value in your session and redirect to the next page in the sequence.
if ($page_is_done) {
$_SESSION['latestStep']++;
header("Location: " . $steps[$_SESSION['latestStep']]);
}
Keep it simple, seems that you are over complicating the goal. It seems like you simply want to ensure that the user completes previous steps of a process before they can continue on to the next. Why not try something more like...
// General Idea
$completedArr = array('1' => false, '2' => false ...);
$pageMap = array('page1.php' => '1', 'page2.php' => '2' ...);
// On Page1
$completedArr = $_SESSION['completedArr'];
$locked = true;
$currentStep = $pageMap[$_SERVER['SCRIPT_NAME']]; // '1'
if($currentStep > 1)
{
if($completedArr[$currentStep - 1] === true)
$locked = false;
}
else
{
$locked = false;
}
$completedArr[$currentStep] = true;
$_SESSION['completedArr'] = $completedArr;
Use this as needed for continuous pages also. The idea is that the pageMap you would define to give index numbers to script names. Then you would simply check to see that the previous index was marked as completed before "unlocking" this page.
I need to set, automatic session time out after some fixed time in my site.
I used the script below but it's not working properly.
I set the some time but it automatically times out before that time.
if((empty($Session_UserId)) || (empty($Session_Username)))
header("Location:index.php");
if($_SESSION['session_count'] == 0) {
$_SESSION['session_count'] = 1;
$_SESSION['session_start_time']=time();
} else {
$_SESSION['session_count'] = $_SESSION['session_count'] + 1;
}
$session_timeout = $logout_sec; // 30 minute (in sec)
$session_duration = time() - $_SESSION['session_start_time'];
if ($session_duration > $session_timeout) {
session_unset();
session_destroy();
session_start();
session_regenerate_id(true);
$_SESSION["expired"] = "yes";
header("Location:index.php"); // Redirect to Login Page
} else {
$_SESSION['session_start_time']=time();
}
I think what people are trying to say is, try the code below. which is a copy/paste of your code just without the last else statement.
if((empty($Session_UserId)) || (empty($Session_Username)))
header("Location:index.php");
if($_SESSION['session_count'] == 0) {
$_SESSION['session_count'] = 1;
$_SESSION['session_start_time']=time();
} else {
$_SESSION['session_count'] = $_SESSION['session_count'] + 1;
}
$session_timeout = $logout_sec; // 30 minute (in sec)
$session_duration = time() - $_SESSION['session_start_time'];
if ($session_duration > $session_timeout) {
session_unset();
session_destroy();
session_start();
session_regenerate_id(true);
$_SESSION["expired"] = "yes";
header("Location:index.php"); // Redirect to Login Page
}
The problem with your code is the last if/else construct. Because if the session has not been timed out, the session start time is set to the current time. So this is rather a “last activity” time stamp. If you drop the else block, the session will not be usable longer than your time out.