So, I made a PHP page/link checker, which should not allow an user to visit/redirect to a page if isn't passed certain minutes from last visit/redirect.
The problem is, the user is being redirected to the page ALWAYS even if he already did it 1 min ago and the timer is 7 min (example). The timer is setted into MySQL as minutes.
can't figure out what is wrong in the code
this is the first page:
<?php
session_start();
$sql = "SELECT * FROM table_records";
$result = mysql_query($sql);
$records = array();
while ($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
foreach ($records as $record) {
$now = new DateTime();
if (!array_key_exists($record, $_SESSION['records']) || ($now->getTimestamp()-$_SESSION['records'][$record]) <= 600) {
echo "<td><center>".$record['id']."</center></td>";
echo "<td><center>".$record['name']."</center></td>";
echo "<td><center>".$record['link']."</center></td>";
echo "<td><center>".$record['delay']."</center></td>";`
} else {
// link disabled
}
}
?>
and this is the page the users are redirected to, to check the timer, and in case redirect them to the link.
$waiting_time = $delay * 60; //calculate delay time in seconds
if (!array_key_exists($id, $_SESSION['records'])) {
$_SESSION['records'][$id] = $now->getTimestamp();
header("Location: $link");
exit();
} elseif (array_key_exists($id, $_SESSION['records']) && ($now->getTimestamp()-$_SESSION['records'][$id]) >= $waiting_time) {
echo "Looks like you already visited this page";
} elseif (array_key_exists($id, $_SESSION['records']) && ($now->getTimestamp()-$_SESSION['records'][$id]) < $waiting_time) {
$_SESSION['records'][$id] = $now->getTimestamp();
header("Location: $link");
exit();
}
The problem is, the user is being redirected to the $link ALWAYS, even if he already visited, and the time of delay isn't passed.
What is wrong with the code?
DRY, you can write your if/elseif statements much easier:
if (array_key_exists($id, $_SESSION['records']) && ($now->getTimestamp()-$_SESSION['records'][$id]) < $waiting_time) {
echo "Looks like you already visited this page";
} else {
$_SESSION['records'][$id] = $now->getTimestamp();
header("Location: $link");
exit();
}
Now, if you look at it you'll see there are two things to check at first:
Is $_SESSION['records'] not empty (maybe session wasn't intialized on second page?) - var_dump ($_SESSION['records']) - what's in there?
what's the result of ($now->getTimestamp()-$_SESSION['records'][$id]) and what's in $waiting_time variable - var_dump it
Don't forget to call exit() after dumping the code and before redirection or simply comment location () lines, otherwise you'll see nothing
Third possibility (you'll know this is the case if you don't see var_dump printout) is that your browser remembers 301 redirection and when you go second time to same address it redirects automatically without calling your script - restart your browser or try different one.
Related
I'm making a login attempt checker, so if user inputs wrong key (witch was send via email) then It add +1 on the attempt meter. I stored it in a session did quite a lot of research but it just doesn't work. here is my PHP code.
session_start();
$_SESSION['poskusi'] = 0;
$kljuc = $_SESSION['rand_kljuc'];
if(isset($_POST['vpis_kljuc'])){
$vpis_kljuc = $_POST['vpis_kljuc'];
if($vpis_kljuc == $kljuc){
echo "You are in";
}
else {
echo "Wrong key";
$_SESSION['poskusi']+1;
if($_SESSION['poskusi'] == 3){
echo "locked";
}
}
}
You are setting the counter to 0 every time the page loads.
Try this:
if(!isset($_SESSION['poskusi'])) {
$_SESSION['poskusi'] = 0;
}
You are also incrementing it wrong. It should be
$_SESSION['poskusi']++; or
$_SESSION['poskusi']+=1; if you prefer.
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 have this piece of php code that looks up the account prompt function on my website. basically if a user has violated a term and condition on the site, at login they are redirected to a prompt page that says you are very naughty and here's a warning.
My code is this:
<?php
$account_prompt = account_prompt();
while ($prompt = mysql_fetch_array($account_prompt))
if ($prompt['account_prompt'] == '1') {
redirect_to("prompt.php");
}
?>
My question is how can i get it to only redirect once?
Thanks
He just redirects 1ce unless you are stucked in an endless loop...
Try this
if (isset($prompt['account_prompt']) && $prompt['account_prompt'] == '1') {
header("Location: prompt.php");
exit;
}
Use a flag which is set to 1 according to your condition, and take the redirect out of the loop.
$flag = 0;
while ($prompt = mysql_fetch_array($account_prompt)) {
if ($prompt['account_prompt'] == '1') $flag = 1;
}
if ($flag == 1)
redirect_to("prompt.php");
I have this php script it's not inside a function
$num = mysql_num_rows($result);
if ($num == 0)
{
header("Location:index.php#captcha");//Location:#errorlogin.html");
$_POST[password]="";
exit;
}
It always seems to continue executing everything after this part regardless of $num being equal to 0 I have already tried exit("message"), die, return etc. Sorry if it's a noobish question haha
You're redirecting the page.
An example to notice from this page:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
$_POST[password]="";
That should probably be (note the '):
$_POST['password'] = "";
The function exit() definitely stops execution when it is executed. There must be something wrong with your if condition.
In PHP multiple values "equal" to zero (if you use ==). Try var_dump($num) to see what's really in there.
exit would not working because it is has 2 dependency
A. if ($num == 0) if $num is not zero exit would not work
B. header("Location:index.php#captcha"); If your location works exit would not wort
try
$num = mysql_num_rows ( $result );
if ($num == 0) {
$_POST ['password'] = null;
header ( "Location: http://yoursite.com/index.php#captcha" ); // Location:#errorlogin.html");
exit();
}
else
{
echo "Found $num in the database";
}
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.