I have user sessions for the user to login. The problem is that anyone can open the server side links directly.
For example : http://mylink.com/foldername/json/json_example.php
If anyone browse the above link it opens directly.So I want to make secure to the database operations(some stores through JSON) and my server side PHP files by using sessions.I need to check user session before performing database operations and before opening of every page in server side.
The below code i used for User Sessions:
<?php
ob_start();
session_start();
if(isset($_SESSION['user'])){
header('Location: home.php');}
?>
<html>
<head>
<body>
<section class="container">
<div class="login">
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<p><input type="text" name="username" placeholder="Username" id="username"></p>
<p><input type="password" name="password" placeholder="Password" id="password"></p>
<p class="submit"><input type="submit" name="login" value="Login"></p>
</form>
</div>
<?php
if(isset($_POST['login'])) {
require_once('db/connection.php');
$username=$_POST['username'];
$password=md5(mysql_real_escape_string($_POST['password']));
$query=mysql_query("select * from tablename where username='$username' and password='$password'");
$row=mysql_num_rows($query);
if ($row == 1){
session_start();
$a=mysql_fetch_array($query);
$_SESSION['user']=$a['username'];
$_SESSION['pref']=$a['preference'];
header("location: home.php");
} else {
echo "wrong username/password";
}
}
?>
</section>
Please help in resolving the issue.
Thank you.
For blocking the access to the files that are included in others and should not be accessed directly: add this to the pages that are directly accessed, like index.php:
//This will prevent loading the included scripts as stand alone scritps.
define('SECURE', true);
and this to the scripts you don't want to be accessed by anyone directly
//Security check
!defined('SECURE') and exit("You should not be here.<br>Go back to the <a href='index.php'>home</a> page.");
For blocking access to any kind of file to the users that are not logged in, add this:
if (!isset($_SESSION['user']))
exit("You should not be here.<br>Go back to the <a href='index.php'>home</a> page.");
Is this something you are looking forward?
if(!isset($_SESSION['user'])){
header('Location: login.php');}
Note the ! at the beginning of isset. This means that if the user variable is not set inside the session, it will redirect to login.php.
Related
Suppose, I have two pages login.php and index.php. In index.php I have two buttons Login and register.After clicking the buttons ,the user is directed to login.php.
If I want to implement a login functionality using PHP, something related to facebook such that the if a user has logged in before, then it bypasses the index page once the username and password are set and directly lands into the login page. Is $_SESSION a proper way of doing it.
For example:
<?php
session_start();
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ayu</title>
</head>
<body>
<?php if (isset($_SESSION["user"])) { ?>
<h1>Hi <?php echo $_SESSION["user"]; ?></h1>
Logout
<?php } else { ?>
<h1>Login</h1>
<?php echo (isset($_GET["error"])) ? '<p>You idiot!</p>' : ""; ?>
<form action="new-user.php" method="post">
<div>
<label>
<strong>Username</strong>
<input type="text" name="username" />
</label>
</div>
<div>
<label>
<strong>Password</strong>
<input type="password" name="password" />
</label>
</div>
<input type="submit" value="Log In" />
</form>
<?php } ?>
</body>
</html>
In the login functionality, I am setting the $_SESSION values
<?php
session_start();
if (count($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
unset($_SESSION["user"]);
header("Location: ./?error");
}
?>
Yes using and creating ($_SESSION) session is the correct way to check logged in users.
$_SESSION is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a script.
There is no need to do global $variable; to access it within functions
or methods.
Check for session on very top of a page, if found redirect to index else to login page.
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
Refer this simple login example using my sql in php Here
EDIT
As requested by OP - if you want to hide a particular section in index.php page based on session value or say if a user is logged in or not that can be done like:
<?php
if(isset($_SESSION['login_user'])){
?>
<form>
<input type="submit" name="whatever" />
<!-- Other Fields -->
</form>
<?php
}
?>
Html Form in the above code will only be shown if a user is logged in else it will be hidden.
Yes, Session is best way to implement the same. You can use the below php code to solve your problem
<?php
session_start();
if (!empty($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
if($_SESSION["user"]!=''){
unset($_SESSION["user"]);
}
header("Location: ./?error");
}else{
/* Write code for form */
}
?>
We call it html1 for simplicity.
When a user goes to html1, there's a login2.php login page to enable access to client.php which is the hidden page.
It then goes to checklogin.php...if the password and user name matches...it then goes to the hidden client.php page...if not..it goes back to homepage.
The user has to login to be able to view the contents of hidden client.php page.
However the user can access client.php by typing in ..../client.php on the address bar...therefore bypassing the auth page and rendering it useless. I can just type servername/client.php...and it still shows me the contents of client.php...but I want client.php...to be private!
How do I prevent this from happening?
thanks.
first login page...
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<table>
<form method="post" action="checklogin2.php">
<div id="name">User Id: <input type="text" name="****"></div>
<div id="password">Password: <input type="password" name="*******"></div>
<div class="button"><input type="submit" value="Login"></div>
</form>
</table>
</body>
</html>
then it goes to....
checklogin2.php
<?php
$*** = $_POST['****'];
$***** = $_POST['***'];
if($uid == '****' and $***** == '*****')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
else
{
header("location:index.html");
}
?>
Then it goes to...
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
header("location:client.php");
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>
In the beginning of your every page you have to check if user is authorized.
On checklogin.php if user entered correct login and password, just set something like
$_SESSION['authorized'] = TRUE;
...and on other pages just check if user is authorized:
if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === TRUE) {
// Alright, let's show all the hidden functionality!
echo "Psst! Hey! Wanna buy some weed?";
} else {
// User is not authorized!
header('Location: login.php');
exit();
}
Note that you don't have to mess with cookies, session IDs etc. - just add session_start() before everything and freely use $_SESSION var.
This is the main pro of sessions (and $_SESSION variable in particular): you can remember some data among different pages on same website.
All pages has to check if the user is authed. I would recommend using objects, and always inherit a class that checks this for you. It's not fun to have the same code everywhere, doing the same thing.
if($_SERVER["PHP_SELF"] == '/yourpagefolder/yourpage.php' && !isset($_SESSION['login_user'])){
header('location: login.php');
}
I'm developing a simple member management system with php, and I've met a problem:
The user logs in and it is redirected to a main page and the user ID is saved in the session; there are some links to other pages in the main page, after the user clicks and is trying to go back to main by pressing browser "Back" button, sometimes the user ID in the session is lost.
I've checked the session save path, a new session file is created when I click "Back" button, so I assume the session_start() creates a new session for it; but I still don't know why, it's a random case...
Is there any way to solve it?
main.php:
<?php session_start(); ?>
<?php
$echo_string = '
<body>
a
b
</body>';
if (!empty($_SESSION['user']))
echo $echo_string;
else
header("Location: login.php");
?>
login.php:
<?php
session_start();
if (isset($_POST['userLogin'])) {
$_SESSION['user'] = $_POST['userLogin'];
// check userLogin in db
...
}
header("Location: main.php");
?>
<form novalidate="" method="post" action="login.php">
<label class="hidden-label" for="Username">Username</label>
<input id="Username" name="userLogin" type="text" placeholder="Username" value="" spellcheck="false" class="">
<label class="hidden-label" for="Passwd">Password</label>
<input id="Passwd" name="userPassword" type="password" placeholder="Password" class="">
<input id="signIn" name="signIn" class="rc-button rc-button-submit" type="submit" value="Log in">
</form>
a.php:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>...</head>
<?php
$echo_string = '...'; // a html format string
if (!empty($_SESSION['user']))
echo $echo_string;
else
header("Location: login.php");
?>
</html>
b.php is almost same as a.php
Thanks.
BR,
Sean
session_start()-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."
so you see, that when a session exists it doesnt create a new, that means when you set something like $_SESSION['logged_in'] = true; you should check before if $_SESSION is already filled with your infos
I'm currently in the process of developing a simple CMS for ONE user (this is unlikely to ever change). Therefore I'm storing login details in a .ini file (when live, will be stored outside root). Then using sessions to detect if the correct user has logged in, and if not, redirect them back to the login page using Header('Location: login.php') I'm curious as to how secure this actually is? Below is a draft of what I've got so far
Login Page:
<?php
session_start();
if ($_GET) {
header("Location: login.php");
die();
}
if (isset($_SESSION['user'])) {
header('Location: admin/index.php');
}
$config = parse_ini_file("login.ini", true);
$user = htmlentities($_POST['user']);
$password = htmlentities($_POST['pass']);
if ($user == $config['login']['user'] && $password == $config['login']['password']) {
$_SESSION['user'] = $_POST['user'];
header('Location: admin/index.php');
}
?>
<form action="login.php" method="POST">
<h2>Username:</h2>
<input type="text" name="user" />
<h2>Password:</h2>
<input type="password" name="pass" />
<input type="submit" Value="Login" />
</form>
Then there would be a check on every page in the admin area for the session, if not redirect to the login using the header location, like so:
Admin Welcome Page
<?php
session_start();
if (!isset($_SESSION['user'])) {
header('Location: ../login.php');
die();
}
And a logout page, would destroy the session.
I understand this is fairly simple and doesn't use a database. But are there any major secruity flaws to this design, using header location a lot, and storing sensitive date in the .ini file. Or for a simple application, is this well suited / not outdated?
I am doing a project in school, I need to know a simple way to stop poeple from entering the site without a session. I have alot of pages I don't believe I spent the time pasting code on every page. Also I have menu bar that is included in every page thanks to php, so i was wondering wat type of code would I have to put in the menu to block user without a session. The rest of the content code is on the pages that I want to hide. I believe that you can login by typing out the url and allow users to see hidden pages that are for logged in users.
Please do not use a plain cookie. Sessions are the way to go. Or if can't use sessions and must use a cookie, sign the cookies first to be able to verify that your application was really the one to set it.
<?php
session_start();
if (!isset($_SESSION['authenticated'])) {
header('Location: login.php');
exit;
}
... whatever logged in users should see ..
If you don't want to use session, then use cookie.
<?php
/*Just add this piece of PHP code to top of any page you
don't want not-logged in users to see */
if (!isset($_COOKIE['logged']))
header("Location: login.php"); //It redirects the user to your login page
?>
<html>
<body>
...
</body>
</html>
Login page could be like this:
<?php
if (isset($_COOKIE['logged']))
header("home.php");
if ($_POST['submit']) {
//get username and password
$uname = $_POST['uname'];
$pass = $_POST['password'];
if ($uname=="correct" && $pass=="correct"){ //EDIT
setcookie('logged','1');
header("Location: home.php"); //Redirect to home page
}
else echo "Wrong combinaton!";
}
?>
<html>
<body>
<form action="login.php" method="post">
<label>Username</label><input type="text" name="uname" /><br />
<label>Password</label><input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>