Index always refreshing - php

I'm making a dynamic site, and I'm making a reset password through email, and I have this flag in my database so when the user resets his password the value is true, and the next time that user logs in, he will be redirected to the change password page.
I'm working with a single index page with a switch.
<?php
session_start();
$lig=mysql_connect("localhost", "root", "") or
die ("Problema na ligação ao servidor MYSQL");
mysql_select_db("demo",$lig);
if (isset($_REQUEST['cmd'])) $cmd=$_REQUEST['cmd']; else $cmd='home';
?>
<div class="col-md-12">
<div class="row">
<?php
switch($cmd) {
case 'home': require('home.php');break;
case 'pw': require('users/pw.php');break;
}
?> </div> </div>
I made this code so when reset is different than NULL he redirects the user to the pw.
if(isset($_SESSION['user'])){
if(is_null($_SESSION['reset'])){
}
else{ echo "<meta http-equiv=refresh content=0;URL=index.php?cmd=pw>";
}
}
but the page seems to be in an infinite loop of refreshing.
I placed this in the index.php page, but if
I put it in the home page for example it works just fine, I wanted to be able to make this in the index, so I don't have to put it in every single page of my website...
Making the time for the content=0; bigger is not a reliable option..
Thanks!!

Use session_destroy() to destroy the session after the user changes the password, so you only need to check if $_SESSION is setted. This routine I put to orient you towards users that is already logged into page.
function changePass(){
//YOUR ROUTINE
if ($queryExecuted == true){
session_destroy();
}
}
//checking session
if(!isset($_SESSION)){
echo "<meta http-equiv=refresh content=0;URL=index.php?cmd=pw>";
}
Your meta is always running because is in else statement, taking ALL OTHER CONDITIONS while $_SESSION['reset'] is not null. Other important thing it's avoid use echo metas, use header instead:
header("Refresh:0");
//or refresh and redirect
header("Refresh:0; url=page2.php");
After user login, don't redirect to index page and to all those validation, just validate inside the own user login routine and redirect to users/pw.php
If you don't want to change all your routine checking, the page always refreshing because is not checking where the user is:
if(isset($_SESSION['user']) && !is_null($_SESSION['reset']) && (isset($_GET['cmd']) && $_GET['cmd'] != 'pw')){
header("Refresh:0; url=index.php?cmd=pw");
}

Related

restrict page without variable , only open if coming from a page or site

page-one.php code
<?php
//page-one.php
session_start();
$_SESSION['page_one'] = time();
?>
hello this is page 1 go to page 2
Page 2
page-two.php code
<?php
//page-two.php
session_start();
//Check to see if session variable exists.
if(!isset($_SESSION['page_one'])){
//Does not exist. Redirect user back to page-one.php
header('Location: 404.php');
exit;
} ?>
this is page 2
Works perfect but I have 2 questions:
what if i delete page-one bcz i want to show page 2 to all vistors who are coming on page 2 by clicking a link
or what if user is coming on page-two through google.com , in this case how page-two will pass page_one variable
This doesn't make much sense, but for your specific questions:
if(!isset($_SESSION['page_one']) &&
strpos($_SERVER['HTTP_REFERER'], 'google') === false &&
strpos($_SERVER['HTTP_X_FORWARDED_FOR'], 'google') === false &&
file_exists('page-one.php')
{
header('Location: 404.php');
exit;
}
Check if the session variable is not set
Check if HTTP_REFERER is not google
Check if HTTP_X_FORWARDED_FOR is not google
Check if page-one.php has not been deleted
$_SERVER['HTTP_REFERER'] is not reliable as it may be wrong, a proxy server or empty and $_SERVER['HTTP_X_FORWARDED_FOR'] is not guaranteed to be set or reliable.
With the previous caveats in mind, you can see if someone came from another site by checking:
if(!isset($_SESSION['page_one'] &&
!isset($_SERVER['HTTP_REFERER'] &&
!isset($_SERVER['HTTP_X_FORWARDED_FOR'])
{
header('Location: 404.php');
exit;
}
If you add a get parameter to all links then it's easier:
Page 2
Then:
if(!isset($_SESSION['page_one'] && !isset($_GET['link'))
{
header('Location: 404.php');
exit;
}

what cause the header function not redirecting on my login page?

please can anyone find and improve in my code that where i am missing when i am trying to redirect on my login page https://localhost/sms/login.php when the session is not set but page getting error like below showing the screenshot
and my code below what i am trying to achieve please check
<?php
session_start();
$ulr='';
$adminurl=ROOTdir.'admin/adminDash.php';
$loginurl=ROOTdir.'login.php';
if(!isset($_SERVER['HTTPS']) && !isset($_SERVER['HTTP'])){
//echo "both are null";
$ulr="https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}else if(empty($_SERVER['HTTPS']) || empty($_SERVER['HTTP']) ){
$ulr="https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
if(isset($_SESSION['uid']) && $ulr == "https://".$_SERVER['HTTP_HOST'].'/sms/' ){
if(isset($adminurl)){
header("location:".$adminurl);
echo "ddsa";
}
}else if(isset($_SESSION['uid'])){
header("location:".$adminurl);
}
if (!isset($_SESSION['uid'])){
if(isset($loginurl)){
//echo $loginurl;
header("Location:https://localhost/sms/login.php");
}
// echo "session is not setsss";
// header("location:".$adminurl);
}
?>
your any participation would be very helpful.
after deleting that above code and i rewrite again to session not set but the same problem occuring like previous as after redirecting on https://localhost/sms/login.php the login page not opening and getting error like
enter image description here
updated is here below
code of session.php
enter image description here
code of session.php
enter image description here
code of adminDash.php
enter image description here
i want when we go on link like https://localhost/sms/admin/adminDash.php if there the session is to be not set then after it will redirect to https://localhost/sms/login.php
it say too many redirect, probably you are into a loop.

How to display a message visible just once on a page

After a user has registered on my website, I want to display a welcome message on the next page..
I want this to be visible just once.
I tried to do this with session but the problem is - it appears every single time the user is logged in and visits that page...
$message2 = "Congrats!! Your store has been created successfully!";
$_SESSION['message2'] = $message2;
header("location: admin/welcome.php");
Am building with php....but I dont mind using jquery etc for this.
In welcome.php, after the line that prints the message, unset $_SESSION['message2'] or empty it.
Example
echo $_SESSION['message2'];
unset($_SESSION['message2']);
// OR
$_SESSION['message2'] = null;
maybe you can use GET to make it work like this:
header("location: admin/welcome.php?message=$message2");
on welcome.php page
if(isset($_GET['message']) && !empty($_GET['message'])){
echo $_GET['message'];
}
Do you use start_session();
After displaying first you could set a $_SESSION['displayed'] = true;
then checking if this variable is set, to avoid display a second time

My sessions aren't working correctly

I have the following code
<?php
if($_SESSION['loggedin']){
echo '<li id="login-btn">Logout</li>';
}
else{
echo '<li id="login-btn">Login</li>';
}
?>
This is inside of the HTML for my Navbar. I want it to where if they are logged in, it will show "Logout", if they aren't logged in, it'll show "Login", (self explanatory)
I have this in my login.php
$loggedin = "";
$_SESSION['loggedin'] = true;
For some reason, no matter what I do, my navbar keeps displaying "Login"? Help please, thank you!
Session are global variables in php...
Session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning
of each page (session_start()).
if you want to access it on different page... you have to add
<?php
session_start();
?>
at the begining .... even in your login.php page

How do I redirect to referring page/url after successful login?

I'm aware that this topic has been covered before here on Stack, and I have looked at some answers, but I'm still a bit stuck, being fairly new to PHP. Every page on my website requires a login, and so users are redirected to a login page on page load. At the top of each page then I have:
<?
require("log.php");
include_once("config.php");
include_once("functions.php");
?>
This redirects the user to log.php (with new code added):
<?
session_name("MyLogin");
session_start();
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","",""); // your MySQL connection data
$db = mysql_select_db(""); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM users WHERE login='$name'");
if (!$q_user) {
die(mysql_error());
}
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM users WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/$url"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
The login form is contained in login.php. The code for login.pho relevant to the PHP/log.php is:
<?
session_start();
if($_GET['login'] == "failed") {
print $_GET['cause'];
}
?>
and
<form name="login_form" id="form" method="post" action="log.php?action=login">
The answer that I came across stated that I should add:
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
to the top of each page, which I did, at the top of the page (above "require("log.php");"), and then add:
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
to my login page, and use the following URL for redirect on successful login:
header("Location: http://example.com/$url"); // perform correct redirect.
I am not 100% where the code which stores the referring URL should go, at the top of log.php or login.php.
I have tried adding it to both, but the login page is just looping once I have entered the username and password.
I wonder if someone could help me get this working?
Thanks,
Nick
It appears that I don't have the privilege to comment on your post, so I'll do the best that I can to answer. I apologize for all of the scenarios, I'm just doing the best I can to answer on a whim.
SCENARIO 1:
If you've truly not selected a database in your code, as demonstrated here, could that potentially be your issue? Please do note, that the code below, is the code you've posted.
$db = mysql_select_db(""); //put your database name in here
SCENARIO 2:
The code below is not something I've ever used in anything I've built, might I suggest that you try replacing that line of code with the line below it?
if(session_is_registered("name") == false) { // Current
if(isset($_SESSION['name']) == false) { // Potential Replacement
SCENARIO 3:
If you're logic for the following, exists on the login.php file as well... That could potentially be your problem. Upon visiting your site, I noticed your form appears on login.php, yet your logic is posting to log.php. I'm hoping this bit of code can help rule out that "jump", as login.php might be saving itself and overwriting the $_SESSION variable you've established
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
If it's too complex to take it out of the login.php file, if you even have it there, I've put together some code that you can use to create "internal" breadcrumbs, so you can go 2 pages back in your history.
if(!isset($_SESSION['internal_breadcrumbs']))
$_SESSION['internal_breadcrumbs'] = array();
$_SESSION['internal_breadcrumbs'][] = $_SERVER['REQUEST_URI'];
$max_breadcrumbs = 5;
while(count($_SESSION['internal_breadcrumbs']) > $max_breadcrumbs)
array_shift($_SESSION['internal_breadcrumbs']);
That will create an array with a max of $max_breadcrumbs elements, with your most recent page at the end, like the following
Array
(
[internal_breadcrumbs] => Array
(
[0] => /other_page.php
[1] => /other_page.php
[2] => /other_page.php
[3] => /user_page.php <-- desired page
[4] => /login.php <-- most recent page
)
)
So now... you can setup your url to be something more like the following...
// I'm doing - 2 to accommodate for zero indexing, to get 1 from the current page
if(isset($_SESSION['internal_breadcrumbs']))
$url = $_SESSION['internal_breadcrumbs'][count($_SESSION['internal_breadcrumbs']) - 2];
else
$url = "index.php"; // default page for
All the best, and I certainly hope this has helped in some way.
IN SCENARIO 4
From the client test the login/password which ajax XMLHttpRequest with javascript code to a dedicated script for validation (do it on mode https for secure)
If response is right send the login password to your script server.
Stips : Encoding password is better secure !
Using header() function it's a bad idea.
Manual specification say ;
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
So in your case, i suggest that to use cookies with an ID generate only for the session, at the first connection its generate, and the duration of the cookie maybe for only from 2 to 10 minutes.
Regenerate cookie each time the loging.PHP is called !
Have a nice day

Categories