PHP redirect refresh - php

I have a system where the user logs in and is immediately directed to a PHP page that runs some queries which it inputs into session variables. After the PHP has finished executing, it redirects the user to the main page. I would like to know how I can set it up, so that when the user refreshes the main page, it redirects them to the preceding page where the calculations can run again before the main page is displayed. I simply cannot have the two pages merged together. Does anyone know how I can accomplish this?
EDIT: PHP include is the closest to what I need, but the problem is that when I use AJAX to submit a form, the session variables in the first file update with new data from the database. Those variables need to stay static until an actual page refresh by the user. Does anyone know how I can include the form but make it invisible to Jquery?

You could store a value to the $_SESSION and every other load, forward to the other page.
// Start session
session_start();
// If the session variable is set...
if (isset($_SESSION['loadCount']) {
// Increase the count
$_SESSION['loadCount']++;
// If it is even...
if ($_SESSION['loadCount'] % 2) {
// Reidrect
header('Location: /calculate-again.php');
die();
}
} else {
$_SESSION['loadCount'] = 1;
}

In the login form, make it submit to page_with_awesome_calculations_and_queries_to_session_variables.php. Assuming no input is sent in that page, make your calculations queries and sessions there, and then send a Location header to the new page.
header('Location: 'index.php');
This will cause the address bar in the browser to actually change to index.php, and a refresh will make the user stick there.
You should also secure your page_with_awesome_calculations_and_queries_to_session_variables.php to not allow access unless the correct $_POST variables are set.

Have mainpage.php receive one url parameter t which is the epoch timestamp.
Whenever calculation.php redirects to mainpage.php it will pass the epoch timestamp. If mainpage.php finds the epoch timestamp is older than five seconds, it will redirect back to calculation.php and exit.
mainpage.php
if (time() - $_GET['t'] > 5)
{
header('Location: calculation.php');
die();
}
else
{
// proceed normally
}
calculation.php
// perform calculation
header('Location: calculation.php?t=' . time());

Add
<?
require 'calculations.php';
// Mainpage goes here
?>
to the top of the mainPage. This makes it an extension of the mainPage which is run before the main page is loaded.

Related

How to prevent a user from directly accessing my html page by writing URL?

i want a hard coded Login Page (login.html), with no database.
If a person writes correct username and password, it redirects to (page2.html).
Now my problem is that if a person write the URL directly for page2.html , he will be able to access it, without any login.
Ideal Case => www.example.com/login.html => if Correct => www.example.com/page2.html
Problem Case => www.example.com/page2.html => page2.html , NO LogIN :(
You can control all this with a php session like this
//set the session on the login page
$_SESSION['loggedIn'] = true;
//on the second page you check if that session is true, else redirect to the login page
if($_SESSION['loggedIn'])
//allow
else
//redirect to the login page
header('Location: /login.html');
A session is a way to store information (in variables) to be used across multiple pages. By default, session variables last until the user closes the browser.
To make things simple, you can change your pages into php (e.g login.php).
Line 1: In your login.php page, you will first check if the username and password are correct, if they are, set the $_SESSION['loggedIn'] = true
Line 2: In your second page (page2.php), you will first check that the user did login by checking if the session have a value if($_SESSION['loggedIn']) {//allow processing}
Line 3: If that session variable is empty, then this means the user did not login, redirect him to the login page else { header('Location:/login.php');}
To start off: I have no idea how you would like to compare the password and username with something and check whether it's correct or not, but for now I would do something like this (again, this is without database).
You have 2 options: Either use a session as stated above, or the bit easier way: Just use theisset() function.
<form action="page2.php" method="POST">
<input type="text" name="userName" required>
<input type="password" name="password" required>
<button type="submit" name="submit">Send!</button>
</form>
page2.php will contain the next code:
if(!isset($_POST['submit']) {
//direct back to a certain page, could look like this:
header('Location: xxx.php');
exit();
//exit() prevents the code from running, it litterly EXITS the code as soon as it hits that line.
} else {
//direct to page2.php
}
Let's break it down: Why did I use the extension .php? Because you cannot do this purely with HTML.
Why did I use (!isset()) instead of isset()? Because a good practice is to think in security first, you don't access an important area and THEN check whether someone has lethal weapons or not. You check first and then you allow him either in or denie access. This is a quite simple and common way to prevent someone from accessing your page with the URL, however a SESSION is better and a bit more experienced practice.
This problem cannot be solved with a pure HTML solution. Your question is tagged as php so I'll base my answer on that:
Post your form to a php script (such as login.php)
Script checks the login details and sets a cookie
page2.html must be php instead, and checks for the cookie before displaying the HTML
Another option is using HTTP authentication, see this article for a tutorial.
You could block that page's access from external locations in your server securtiy settings,
then send the html of that page to the browser on successful login with fil_get_contents('page2.htm') in php. the php is run on the server so the file request won't be from an external source. you could overwrite html on the page using javascript or you could echo the contents on an if in php that will show the normal page on else
eg
if(isset($_GET['Login'])
{
//check login details
//if(....) //put your login check logic here
{
echo file_get_contents('page2.html');
}
else
{
//normal page's code goes here
}
}
Note:how to set the file to disallow external access is outside the scope of my answer
I had the same problem and found this and it works perfectly: (in javascript)
Just put it at the top of the document.
var x = document.referrer;
if (x == "page2.html") {
console.log(x);
} else {
window.location.href = "login.html";
};
change the default path for your website by using complete path to login.php. Next time when any of the user will type your url, they will be redirected to the given path which is yourpath>login.php
Hope it will help.
If you are using Asp.net, perhaps you can use TempData. They stay with the session between pages.
if (/*username and password are correct*/){
TempData["LoggedIn"] = "True";
} else {
TempData["LoggedIn"] = "False";
}
Then, when your controller tries to load page2 you just check the value of TempData.
var validate = TempData.Peek("LoggedIn");
if (validate == null || validate.ToString() == "False"){
return RedirectToAction("login");
} else {
/*allow access to page*/
}
Using .Peek keeps the TempData, as it would normally be marked for deletion if it was accessed. You also want to check it for null as it may have never been assigned if the user does not first go through the login page.
You can prevent that by checking if the user is already logged in
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
header('Location: login.php'); //here you put your login page
exit;
}

php session always created on refresh

I am new to PHP so have a very basic question
I creating a page I am creating a page initially with user id and password, once user id and password are entered and submit is clicked, AJAX is called to validate that against database.
once validation done I want to refresh the page which show more option to user
I was thinking to use session
but every time I refresh the page a new session is created
I put this at the top of the page as a test and always when F5 is press I see "new session" on top of the page
<?php
if (!isset($_SESSION)){
session_start();
echo("new session");
}
else
{
echo("old session");
}
?>
session_start must be called always before anything related to a session. After calling it, you can get or set values of the $_SESSION variable.
Reference.
Your code should be:
<?php
session_start(); // always call this at top
if (!isset($_SESSION['has_been_here'])){
$_SESSION['has_been_here'] = true;
echo("new session");
}
else
{
echo("already been here");
}
?>
From php.net:
session_start — Start new or resume existing session
That means you have to start your session with
session_start();
on every page, in the first line, which will start or resume it. Check the php.net manual, it will help you understand how to handle and check sessions correctly.

$_SESSION variable in php (page to page)

Whenever I go to a page i.e. login page or any other page, I want to save the name of the page in a $_SESSION variable.
login page:
<?php
session_start();
$_SESSION['page'] = 'login.htm';
?>
It works only for the login page and doesnt overwrite in other pages for e.g. home page:
<?php
session_start();
$_SESSION['page'] = "home.htm";
?>
I need the sesssion variable 'page' to hold the last page I was, can anyone help please?
Why not just use $_SERVER['HTTP_REFERER']? This will give you the previous page in PHP, without having to add anything to sessions.
when you navigate to a new page first retrive the saved "back" variable (and use it in a back link/breadcrumbs or something), and then overwrite the sessions "back" variable with the curent page, to have it ready for the next move =)
If all you need is default "back" functionality you should let the browser handle it.
If what you want is something to be used as a breadcrumb following some internal order (or path in a tree) my advice is to let each page "know" the path that leads to it.
If you really need to know from what page the user came from save it to a previous variable before you write over the current variable.
// Make sure user didnt just refresh the page
if ($_SESSION["current"] !== "currentPage.php") {
$_SESSION["previous"] = $_SESSION["current"];
$_SESSION["current"] = "currentPage.php";
}
You're using different keys.. 'page' and 'back'.

PHP session issues

I have a mobile script from detectmobilebrowsers.com that will redirect the user to my mobile site however I also wish that when the URL "http://example.com/?mobile=no" is entered a session will be created that won't redirect the user on every page of my site...
$mobile=$_GET['mobile'];
if(isset($_SESSION['mobile'])){
if($_SESSION['mobile']==="no"){
complete();
}
else{
$_SESSION['mobile']="no";
complete();
}
}
elseif($mobile==="no"){
$_SESSION['mobile']="no";
complete();
}
elseif($_SESSION['mobile']!="no"){
checkMobile();
}
function checkMobile(){
// Mobile Detection Code taken out to save space.
gotoMobile();
}
function gotoMobile(){
echo "<script>window.location='http://m.MySite.org/';</script>";
}
function complete(){
return false;
}
Sorry if I seem confusing but in short terms: Mobile Detection (which is set)... make session mobile=no if user does wishes to view full site and when that session is created it is checked on everypage (same php script) and if I set my session for no mobile I want that to stay on everypage... In my case the only thing that happens is the first page is not redirected but when I go to another page it won't display it unless I add the ?mobile=no but the whole point of the sessions here is so this only needs to be done once.
Before you can begin storing user information in your PHP session, you must first start the session:
session_start();
There must be no markup ouputted before session_start(), not even whitespace! (unless output buffering is used).
See http://php.net/manual/en/function.session-start.php.
It sounds simple, but are you sure you are using session_start() at the top of every page before checking all of your session variables?

php redirect check

Is there anyway to determine if a page has come from a php redirect?
I have a session saved of the last time the page was refreshed, but i dont want it to set if the page has come from an instantly referred one.
To give some idea of what i'm doing, i have this code on my site to stop users refreshing more than once per second:
$now = time();
if ($_SESSION['click'] > ($now-1)) {
exit("Woah, you're clicking too fast!") ;
}
$_SESSION['click'] = $now;
However, I don't want the click session to set if the page has from from a php redirect, or a form post, etc. Any solutions?
How about using referer?
if( $_SERVER['HTTP_REFERER'] == "http://mydomain.com/formmail.php" )

Categories