validation user using $_SESSION in PHP - php

I have a php page that should only be accessed by admin. I am using a php $_SESSION to validate the user. I have this code segment on top of my page which should only be accessed by the admin
if (!isset($_SESSION["uname"])) {
header("Location:../error.html");
exit;
}
if ($_SESSION["uname"] != "admin") {
header("Location:../error.html");
exit;
}
uname variable is getting pass to the page correctly, I am sure about that. But my validating process does not work as I expected. any user can access the page.
Is there anything wrong I have done here.

Did you output anything before doing these checks, even a single empty line is enough to prevent redirecting the page using
hearder()
As others stated I'd make sure you do
session_start();
But I have to assume you have the correct session values as you put
"uname variable is getting pass to the page correctly, I am sure about
that. But my validating process does not work as I expected. any user
can access the page. Is there anything wrong I have done here."
So that leads me to the header error, one way to tell is adding.
ini_set('display_errors', 1);
above your "validation checks" this should show any errors like "unable to send headers output already sent" etc.

Did you call session_start() function at beginning.
It would not work unless we call session_start before using any SESSION data.
http://www.php.net/manual/en/function.session-start.php

You probably forgot to call session_start() at the very beginning of the restricted page as well as the page where $_SESSION['uname'] is being set. Also make sure that $_SESSION['uname'] does not contains the value of 'admin' for other logged in users.
Note: You can debug values of super globals like $_SESSION using the print_r() or var_dump() functions.

See the example given below;
Start your session in your index or the desire page
sesstion_start();
Create this function to validate and redirect automatically
function isValidate($value, $autoRedirect = true){
if(empty($_SESSION['uname']) || $_SESSION['uname'] != $value){
if($autoRedirect){
header("Location:../error.html");
exit;
}else {
return false;
}
}
else {
return true;
}
}
Now simply call this method to validate the session by name. For example;
isValidate("admin");
isValidate("user");

Related

Session variable clears itself (PHP)

As a part of a very simple login script, I create a session variable (or at least that is what I think it's called) with the username, and use that as a check of whether or not a user is logged in. The variable is set in the login script, using the following code:
if($count==1) {
session_start();
$_SESSION['ed_user'] = $ed_user;
header("location:main.php");
} else {
echo "Incorrect user or password, please try again.";
}
I know that the first part of this if-statement is run, since I am not presented with the error message. On the page it directs to (main.php) the first lines of code should check if $_SESSION['ed_user'] is set, and return to index.php, if this is not the case. This is done with the code:
if(!$_SESSION['ed_user']){
header("location:index.php");
}
However, it seems to always return me to index.php after login. I have tried to check if the variable exists, using the following line:
<p><?php echo"Current user: ".$_SESSION['ed_user'];?></p>
Which indicates that the variable is empty. What am I doing wrong here?
You need to call
session_start();
On every page.
On your main.php file...
session_start();
if(!isset($_SESSION['ed_user'])){
header("location:index.php");
}
You need to call session_start() to access session variables.

Populate text with PHP Session information

I have a page where, after a user logs in, the session starts and there is a welcome message with the User's Name - like so:
<h2>Welcome, <?php echo $_SESSION["User"]; ?>, to the site!</h2>
Or something along those lines - haven't decided, yet.
But the problem is, is that it doesn't show up.
I have the code that authenticates the user and all that, and that portion works.
They authenticate and they have a session - it DOES exist (if not, the page would redirect them to the login or the error page depending on how many tries).
When they authenticate, the form posts to a "login.php" where all the other code happens, including this:
if (isset($_POST['submit']) && ($allowEntry == yes))
{
session_start();
session_register ("Logged_In");
session_register("User");
$_SESSION["Logged_In"] = 'true';
$_SESSION["User"] = $user;
if ($_SESSION["User"]=='SOMEUSER')
{
header( 'Location: /somepage.php' );
exit;
}
elseif ($_SESSION["User"]=='SOMEOTHERUSER')
{
header( 'Location: /someOtherPage.php' );
exit;
}
}
So, does anyone know how to make that text appear in the "" element above?
I'm not sure I completely understand the question, but I gather that you're setting the session in one script and trying to obtain a value from it in another? If so, it's most likely because you haven't called session_start() in the second. Note from the docs
session_start() creates a session or resumes the current one based on
a session identifier passed via a GET or POST request, or passed via a
cookie.

Session variable not being saved from $_REQUEST

I think i'm missing something obvious. I have a session started at the very top of my page. Below that i have the following code. The var dump out puts "one" when it is displayed from the requested page. After refresh the var dump out puts NULL. Why is this not getting saved?
if($_REQUEST["page"] == 1) {
$_SESSION["one"] = true;
}
var_dump($_SESSION["one"]);
If you have session_start() at the top of your page, as you claim, then your code should look something like this:
session_start();
if($_REQUEST["page"] == 1) {
$_SESSION["one"] = true;
}
var_dump($_SESSION["one"]);
This should 100% work, no question. There IS something else stopping this from working in your code that you have not supplied. My first guess would be a session destroy of some kind.
First, you need to ensure you start the session before attempting to use it. Secondly, it is recommended that you specify either POST or GET instead of generally using REQUEST. If you want to support either GET or POST, you might do something like this:
// Begin Session Management
session_start();
// Check both GET and POST for the parameter
if($_GET['page'] == 1 || $_POST['page'] ) {
// Modify the session
$_SESSION["one"] = true;
}
// See what we ended up with in the session.
var_dump($_SESSION["one"]);
This works for me, but I'm using memcache as my session session handler. Verify your own session handler in php.ini, and ensure that the session handler is working properly. Also, ensure you are closing the session properly if you are redirecting, setting a new location, or exiting in unusual ways.

Clear session variable after use

Is it possible to use a session variable, then unset it directly after?
Example:
//====
//Process Form
if ($_POST['Submit']) {
$update = $userSettings->update($_POST);
//If there are form errors
if (!$update) {
//Load the errors into an array
$errors = $update[1];
} else {
//Set the session
$_SESSION['showUpdated'] = true;
//Redirect to this page
header("Location: http://www.mysite.com/settings");
}
}
//==================
if ($_SESSION['showUpdated']) {
echo "Settings Updated";
unset($_SESSION['showUpdated'];
}
So after the form is submitted, if there are no errors:
Set a session to say the form submission was okay
Reload the page (to prevent re-submitted POST data)
If the 'showUpdated' session variable is set, display the "Updated" message
Unset the session variable (so we don't see the message on next reload)
Currently the problem is, if you unset the session variable straight after; It is as if you have un-set it before the "if exists" part.
Any solutions? Is this even the best way to do it?
Many thanks!
I noticed a small error in the original example that might cause other problems.
unset($_SESSION['showUpdated'];
needs to be
unset($_SESSION['showUpdated']);
Not including that end ) in the unset will cause an error.
That looks like it should work. Make sure you call session_start() before trying to use the session, and always exit() or die() after a redirect header.
I accomplish what you're doing a little differently. I keep a 'message' element in the session. I'll stick text in like 'Your data was saved', error messages, etc. Then, on each page (actually in a page template class), I check to see if the $_SESSION['message'] is set and not empty. If there's something there, I display the message and set the value to an empty string or null.
I do this from time to time. I never have any problems with it. But what I would add to yours is an exit() function call after the header redirect.
EDIT: The reason for the exit() is that it will prevent it from processing any further code and will eliminate the possibility of unset before you wanted to check after the redirect.
The header call without an exit after will continue running the page.
header("Location: http://www.mysite.com/settings");
exit;
Using that instead, should kill the page and not unset the session variable on the same page call.
Just check to see if it exists. This is safe to do before it has been defined and will tell you your answer after it has been defined.
if(!empty($_SESSION['showUpdated'])) {
Or you can just set it to false.
if ($_SESSION['showUpdated']) {
echo "Settings Updated";
$_SESSION['showUpdated'] = false;
}
And it looks like you use smaller version of PHP than 5.3, because in 5.3 you'll get notice when you use uninitialized value. So you should use isset function:
if (isset($_SESSION['showUpdated']) && $_SESSION['showUpdated']) {
echo "Settings Updated";
$_SESSION['showUpdated'] = false;
}

preventing direct access to a php page, only access if redirected

I want to make my php page only accessible from another page redirect and prevent my user from accessing it directly.
I mean, let's say I have a page called "main.php" and another PHP file that I want to prevent direct access to, called "noaccess.php".
I want to make noaccess.php accessible only if I redirect from main.php
Any suggestions?
UPDATE: Session is a good idea, but the problem is I have to use JavaScript to redirect the page, so the question is, can I use ajax to set a PHP session?
UPDATE 2: OK I found the solution, I don't need preventing direct access now, as I can check from mysql whether the page needs to be accessible or not.
What if everytime you were going to redirect you saved a value in the $_SESSION variable. So you have
//code
$_SESSION['fromMain'] = "true";
header("Location: noaccess.php");
Then in noaccess.php put
if($_SESSION['fromMain'] == "false"){
//send them back
header("Location: foo.php");
}
else{
//reset the variable
$_SESSION['fromMain'] = "false";
}
I really don't know if this would work or not, but this is what I would try off the top of my head.
try this
if (!isset($_SERVER['HTTP_REFERER'])){
echo "uh?"; }
else {
// The script
}
I think you're probably coming at the problem from the wrong direction, but if you really want to implement this I'd most likely do it with a session variable. Just have main.php set a flag indicating that they're now able to access noaccess.php and then redirect there. noaccess.php checks for the flag, and only functions if it's been set.
To prevent access to pages, the best practice is to use session variables say $_SESSION['username'] and $_SESSION['password'] to check against your database table record assuming your table name is "users", the fields 'username' and 'password' in order for users to gain access to the page, else they are redirected to the log in page for them to supply the correct username and password through the input field.
Below is an anatomy of Preventing Direct Access to a PHP Page.
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$query="select * from users where username='$_SESSION[username]' and password='$_SESSION[password]'";
$result=mysql_query($query);
if($result)
{
echo "Your login was successful..";// the page you want to go to if login successful
{
else
{
header("Location:index.php?action=login");//any page you want to return to if log in failed
}
I know this has already been answered. Although the answers are good, I was just facing the same situation so I thought I would put my two bit in.
I would not use HTTP_REFERER It is not reliable and not every browser even shows it.
I would not use a session variable as that is stateful and you will have to write more lines of code to check it on every request leading to unnecessary bloat.
Ideally I would create a controller class with two functions main and no access
Or If you dont want to go through that trouble, I would create a variable which is globally accessible in noccess.php with a simple true false.
This is what I would do:
class Access{
protected $access = false;
public function main(){
//Authenticate and set
include_once 'main.php';
$this->access = true;
}
public function no access(){
if($this->access === true){
include_once 'no access'.php;
}else{
header('location: main.php');
}
}
}
Or if you dont want to go through that trouble You could create a simple function or set a simple variable which is accessible from noaccess.php:
//main.php
$access = false;
header('location: noaccess.php');
//noaccess.php
include 'main.php';
if($access){
//Continue
}else{
header('location: main.php');
}
Im sure you could simplify this, but this would be the simplest and safest approach rather than relying on server variables.
I would not use a $_SESSION or $_POST as that means unnecessarily posting a form when all you want to do is secure access
You can use $_SERVER["HTTP_REFERER"]. Put the following code in the beginning of your php file and set $url to be equal of your desired url for example http://a.com/main.php
if ($_SERVER['HTTP_REFERER'] != $url) {
header('Location: noaccess.php');
exit();
}
Why not to just include instead of redirect?
The other folks are right there are issues with $_SERVER["HTTP_REFERER"] so I guess the best way will be to have a variable set into a $_SESSION or $_POST and you will need to check if that variable exists, if not it means it is a direct access.
You tried on this Iva. Below is the code that works:
$url != 'your-url-which-you-do-not-what-direct access';
if ($_SERVER['HTTP_REFERER'] == $url) {
header('Location: otherurl.php'); //redirect to some other page
exit();
}
Ensure this appears at the top of the page where you do not want direct access to.
I think I am late to answer this but my way would be
<?php
$page = basename($_SERVER['PHP_SELF']);//gets current URL
if ($page == "nonaccesspage.php") //any page u don't want to be accessed directly
header('Location:index.php');
else if($page == "nonaccesspage2.php") //page 2 which is not accessible
header('Location:index.php');
?>
If you want to authorize the user for accessing the page (I mean there is a page which is not included but can be accessed with the URL) just use $_POST or $SESSION for authorizing the user with ID and password or something like that.

Categories