I am quite new at PHP, so I hope there are some that can help.
I have a login page which works fine.
My problem is if you know the url, you can still access the subpages.
This is what it says on my login page
<body>
<?php
if(#!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}
?>
<div id="loginWrapper">
<div id="login">
<form name="loginform" action="<?php $_SERVER['REQUEST_URI']; ?>" method="post" autocomplete="on">
<fieldset id="input">
<h1>Log Ind</h1>
<?php
if(isset($_POST['submit'])) {
echo '<div class="errorBox">';
$username = mysqli_escape_string($conn,$_POST['username']);
$password = mysqli_escape_string($conn,$_POST['password']);
if(!empty($username) && !empty($password)) {
$query = mysqli_query($conn,"SELECT * FROM member WHERE username='$username' LIMIT 1");
$result = mysqli_fetch_array($query);
if($result['username'] == $username && $result['password'] == $password) {
//Sesstion Information
$_SESSION['acesses'] = $result['id'];
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}else {
echo 'Brugernavnet eller Adganskoden stemmer ikke overens.';
}
}
echo '</div>';
}
?>
<label for="username"> Dit Brugernavn</label>
<input name="username" id="user" type="text" placeholder="Brugernavn">
<label for="password"> Dit password </label>
<input name="password" id="pass" type="password" placeholder="Password">
<input name="submit" type="submit" value="Log ind" />
</fieldset>
</form>
..........
This is what it says at the top of my subpage
<?php
session_start();
if(!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="login.php"; self.focus(); }</script>';
}
?>
<!doctype html>
<html lang="en">
<head>
You could do redirect the user, if they are not logged in, and vice-versa.
if (!empty($_SESSION['acesses'])){
header("Location: yourpage.php"); // or whatever page you like
exit();
}
else{
// your code for when user is logged in
}
Don't use JavaScript to redirect, especially when dealing with sessions. A user can simply turn off JavaScript in their browser and the redirect won't work anymore.
First of all, your subpage redirects away if the user isn't logged in. Second of all, instead of a javascript redirect, use an HTTP one:
<?php
session_start();
if(!isset($_SESSION['acesses']) || empty($_SESSION['acesses'])) {
Header("Location: index.php");
}
?>
You can use the following logic in the page(s) you wish to protect:
if(isset($_SESSION['acesses']) && !empty($_SESSION['acesses'])){
// give access
}
else{
// don't give access
}
and do the same for all your pages.
Sidenote: The code you posted for your login page doesn't contain session_start(); - If it's not in your working code, include it. It must be inside all pages using sessions.
<body>
<?php
session_start();
if(#!empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="subpage.php"; self.focus(); }</script>';
}
?>
You should also consider embedding <noscript>Please enable Javascript</noscript> into your code and redirect the user if it isn't enabled.
Important sidenote: I noticed you are storing passwords in plain text. This is highly discouraged.
If your PHP version is 5.5, you can use the password_hash() function, or crypt() or bcrypt()
Here are a few resources you can look into:
http://en.wikipedia.org/wiki/Bcrypt
http://codahale.com/how-to-safely-store-a-password/
http://www.php.net/manual/en/function.crypt.php
http://www.php.net/manual/en/function.password-hash.php
About using Javascript:
If you absolutely want to use JS in your code, you can use the following logic:
<?php
echo "<div id=\"hide\">This line is hidden in PHP and will appear once JS is enabled.</div>";
// you can include your JS anywhere in here and will execute once the user enables JS.
?>
<body>
<div class="hide_class">This is hidden using a CSS class and will appear once JS is enabled.</div>
<noscript>
Please enable Javascript to view the content of this page, thank you.
<style>
#hide {
display:none;
}
.hide_class {
display:none;
}
</style>
</noscript>
</body>
First of all, you should use PHP-PDO in order to prevent SQL Injection attacks.
Also your code is wrong at subpage. You should check out variable acesses like following example.
if(!isset($_SESSION['acesses']) or empty($_SESSION['acesses'])) {
echo '<script language="JavaScript">{ location.href="login.php"; self.focus(); }</script>';
}
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 */
}
?>
At the top of every page I have a header (header.inc.php) that has a login field that I add with
include 'login.php';
The code there is:
<?php
include 'checkPassword.php';
if (isset($_POST['login'])) {
if (checkLogin($_POST['username'], $_POST['password'])) {
session_start();
$_SESSION['isLoggedIn'] = true;
header("Refresh:0");
exit();
} else {
echo '<h1>nope</h1>';
}
}
?>
<div id="login"> <!-- Login field with link to registration -->
<fieldset>
<form method="POST" action="login.php">
<Legend>Login</Legend>
Username <input type="text" name="username" <?php if (isset($username)) {echo "value=$username";} ?>>
Password <input type="password" name="password"/>
<input type="submit" name="login">
<div id="register">
Not a member? Click here to register!
</div>
</form>
</fieldset>
</div>
I've seen a few different methods for using header() to load a certain page, but the login appears at the top of every page, therefore I'd like a way for the PHP to refer to itself. However, all the methods I've found so far refer to 'login.php', instead of the page the overall page that contains the header and login.
try this one
<?php
include 'checkPassword.php';
if (isset($_POST['login'])) {
if (checkLogin($_POST['username'], $_POST['password'])) {
session_start();
$_SESSION['isLoggedIn'] = true;
header("Refresh:0");
exit();
} else {
echo '<h1>nope</h1>';
}
}
?>
It refreshes your current page, and if you need to redirect it to another page, use following:
header("Refresh:0; url=page2.php");
echo meta tag like this: URL is the one where the page should be redirected to after refresh.
echo "<meta http-equiv=\"refresh\" content=\"0;URL=upload.php\">";
Is there any solution like unset $msg or something, that, when I reload the page, the $msg stops?
here is my code:
index.php:
<form class="ligar" action="log.php" method="post">
<p class="lig"><input name="username" type="text" placeholder="Username"></p>
<p class="lig"><input name="password" type="password" placeholder="Password"></p>
<p class="lig"><input name="Entrar" type="submit" value="log"></p>
<p class="error"><?php if(isset($_GET['msg']))
echo $_GET['msg'];
?>
</p>
</form>
log.php:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if ($username =='john' AND $password=='abc') {
header("Location:/detalhes.php");
} elseif ($username!='john' OR $password!='abc'){
$msg = "Wrong, try again.";
header("Location:http://localhost/index.php?msg=$msg");
}
?>
Something like this should do the job: (untested)
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username =='john' AND $password=='abc') {
header("Location:/detalhes.php");
} elseif ($username!='john' OR $password!='abc'){
$_SESSION['msg'] = "Wrong, try again.";
header("Location:http://localhost/index.php");
}
?>
log.php
<?
session_start();
<?php if(isset($_SESSION['msg']))
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
If I understand correctly, if first time you enter the wrong credentials, the log.php code redirects the page to
http://localhost/index.php?msg=Wrong,%20try%20again.
So if you reload the page via browser, obviosly the uri remains the same, so you still get the error message in the $_GET['msg'] variable.
EDIT I don't think there's a solution to that using only HTML+PHP.
You can convert the form post to an AJAX request and show/hide the error code via javascript, so you don'
t need to change the uri.
The web is full of easy examples on how to implement an AJAX login form.
EDIT Well, as #Stefano L said, you can use session cookies so you don't need to use any javascript at all.
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 months ago.
I'm building a website which includes a login page. I need to redirect the user to their profile page once they've logged in successfully, but I don't know how to do that in PHP (It's my first site).
I've searched the internet and have been told that the header() function should do the trick, but it will only work if I haven't outputted any information before using it.
That's the problem. I've outputted a bunch of information (Including the HTML to build the login page itself).
So how do I redirect the user from one page to the next?
What options do I have? Also, what is the best practice in these instances?
EDIT: Here's my entire login.php page:
<?php
session_start();
echo "<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Sprout</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'>
</head>
<body>
<div class='box'>
<form action='login.php' method='post'>
Name<br /> <input type='text' name='username' class='form'/><br />
Password<br /> <input type='password' name='password' class='form'/>
<input type='submit' value='Login' class='button' />
</form>
</div>
</body>
</html>";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST["username"];
$password = $_POST["password"];
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");
$dbname = "database";
mysql_select_db($dbname);
$query = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($query) or die ("Failed Query of " . $query);
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
}
?>
You could use a function similar to:
function redirect($url) {
header('Location: '.$url);
die();
}
Worth noting, you should them with a die() or exit() function to prevent further code execution.
Note that it just makes no sense to output large chunks of HTML if you are going to redirect. Therefore you have to move the form handling code above all HTML. As a side effect it will mitigate the notorious "Headers already sent" error.
Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/
This guide includes reasons for using die() / exit() functions in your redirects, as well as when to use ob_flush() vs ob_start(), and some potential errors that the others answers have left out at this point.
You can conditionally redirect to some page within a php file....
if (ConditionToRedirect){
//You need to redirect
header("Location: http://www.yourwebsite.com/user.php");
exit();
}
else{
// do something
}
That's the problem. I've outputted a bunch of information (including the HTML to build the login page itself). So how do I redirect the user from one page to the next?
This means your application design is pretty broken. You shouldn't be doing output while your business logic is running. Go an use a template engine (like Smarty) or quickfix it by using output buffering).
Another option (not a good one though!) would be outputting JavaScript to redirect:
<script type="text/javascript">location.href = 'newurl';</script>
header won't work for all
Use below simple code
<?php
echo "<script> location.href='new_url'; </script>";
exit;
?>
Assuming you're using cookies for login, just call it after your setcookie call -- after all, you must be calling that one before any output too.
Anyway in general you could check for the presence of your form's submit button name at the beginning of the script, do your logic, and then output stuff:
if(isset($_POST['mySubmit'])) {
// the form was submitted
// ...
// perform your logic
// redirect if login was successful
header('Location: /somewhere');
}
// output your stuff here
You could use ob_start(); before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.
Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML.
The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.
If the login is valid you'll redirect using the "header" function.
Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.
<?php
ob_start();
if (FORMPOST) {
if (POSTED_DATA_VALID) {
header("Location: https://www.yoursite.com/profile/");
ob_end_flush();
exit;
}
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>
firstly create index.php page and just copy paste below code :-
<form name="frmUser" class="well login-form" id="form" method="post" action="login_check.php" onSubmit="return FormValidation()">
<legend>
<icon class="icon-circles"></icon>Restricted Area<icon class="icon-circles-reverse"></icon>
</legend>
<div class="control-group">
<label class="control-label" for="inputPassword">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-user icon-cream"></icon> </span>
<input class="input" type="text" name="username" id="username" placeholder="Username" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-password icon-cream"></icon>
</span> <input class="input" type="password" name="password" id="password" value="" placeholder="Password" />
</div>
</div>
</div>
<div class="control-group signin">
<div class="controls ">
<input type="submit" class="btn btn-block" value="Submit" />
<div class="clearfix">
<span class="icon-forgot"></span>forgot password
</div>
</div>
</div>
</form>
/*------------------after that ----------------------*/
create a login_check.php and just copy paste this below code :-
<?php
session_start();
include('conn.php');
<?php
/* Redirect browser */
header("location:index.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
<?php
if(count($_POST)>0)
{
$result = mysql_query("SELECT * FROM admin WHERE username='".$_POST["username"]."' and password = '".$_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["user_id"] = $row[user_id];
$_SESSION["username"] = $row[username];
$session_register["user_id"] = $row[user_id];
$session_register["username"] = $row[username];
}
else
{
$_SESSION['msg']="Invalid Username or Password";
header("location:index.php");
}
}
if(isset($_SESSION["user_id"]))
{
header("Location:dashboard.php");
}
?>
/*-----------------------after that ----------------------*/
create a dashboard.php and copy paste this code in starting of dashboard.php
<?php
session_start();
include('conn.php');
include('check_session.php');
?>
/*-----------------------after that-----------------*/
create a check_session.php which check your session and copy paste this code :-
<?php
if($_SESSION["user_name"])
{
?>
Welcome <?php echo $_SESSION["user_name"]; ?>. Click here to Logout.
<?php
}
else
{
header("location:index.php");
}
?>
if you have any query so let me know on my mail id farjicompany#gmail.com
Although not secure, (no offense or anything), just stick the header function after you set the session variable
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
header('Location: /profile.php');
On click BUTTON action
if(isset($_POST['save_btn']))
{
//write some of your code here, if necessary
echo'<script> window.location="B.php"; </script> ';
}
----------
<?php
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>';
$gourl='http://stackoverflow.com';
echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">';
exit;
?>
----------
Just like you used echo to print a webpage. You could use also do the same with redirecting.
print("<script type=\"text/javascript\">location.href=\"urlHere\"</script>")
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>
Im very new in php and try to use cookie but it is not woking in my site, can anyone guide me please , what is going wrong in my code:
<?php
session_start();
?>
<script>
function Redirect(url)
{
location.href = url;
}
</script>
<?php
define('_VALID_ACCESS', true);
include_once "includes/connect.php";
include_once "includes/login.php";
if(empty($_POST['loginname']) || empty($_POST['password']))
{
$msg = "User or password is empty";
}
else
{
if(login($_POST['loginname'], $_POST['password']) == true)
{
$usern = $_POST['loginname'];
session_register('loginname');
$loginname = $usern;
sleep(1);
if(activestatus($_POST['loginname'], $_POST['password']) == true)
{
$usern = $_POST['loginname'];
session_register('loginname');
$loginname = $usern;
sleep(1);
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['loginname'], $hour);
setcookie("Key_my_site", $_POST['password'], $hour);
$test = $_COOKIE["ID_my_site"];
$msg = "<script> Redirect ('home.html?testname=".$test."')</script>";
//header("Location: home.html");
}
else
{
$msg = "<script> Redirect ('valid.php?testname=".$usern."')</script>";
}
}
else
{
$msg = "<font color=red>User or Password is wrong</font>";
}
}
echo '<div id="divTarget">' . $msg . '</div>';
?>
<link rel="stylesheet" href="css/blueprint/screen.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="css/blueprint/print.css" type="text/css" media="print">
<link rel="stylesheet" href="css/blueprint/ie.css" type="text/css" media="screen, projection">
<body>
<div class="container" id="login_container">
<form id="login" action="action.php" method="post" name="loginform" >
<fieldset id="login_screen" style="width:350px">
<label id="login_label" for="login">User Login </label>
<br><br>
<label for="login">Email Address</label>
<input type="text" name="loginname" id="loginname" value="email#coolmates.com">
<p id="space"><label for="password">Password</label>
<input type="password" id="password" name="password" value="********" ></p>
<input type="checkbox">Keep me signed in until i signout
<p id="test"><input type="submit" value="Submit"></p>
<a href="forgetpassword.html">Forgot
your password</a> |<span id="free">Not a member?</span>Sign up<blink><span id="free">Free</span></blink>
</p>
</fieldset>
</form> </div>
</body>
Turn on display_errors and set your error_reporting to E_ALL and you should see an error message about 'headers already sent' - you have to call setcookie() BEFORE ANY HTML IS SENT. From php.net/setcookie:
setcookie() defines a cookie to be
sent along with the rest of the HTTP
headers. Like other headers, cookies
must be sent before any output from
your script (this is a protocol
restriction). This requires that you
place calls to this function prior to
any output, including and
tags as well as any whitespace.
In the code block that you posted this bit:
<script>
function Redirect(url)
{
location.href = url;
}
</script>
Is being output directly to the browser well before you ever attempt to set the cookies.
Your two possibilities would be to use output buffering so that you output everything at the very end or to switch to a method where all of your processing code is executed first in one script and there you set $_SESSION and cookie values and then include a second script at the tail end of the first that contains the code to be output to the browser.
Try this (specifying the root of your site) :
setcookie("ID_my_site", $_POST['loginname'], $hour,'/');
or try this (adding quotes to your loginname) :
setcookie("ID_my_site", "$_POST['loginname']", $hour,'/');
1st you don't need session_register, you can just do.
Since session_register is the preferred method since 4.1.0 and deprecated as of PHP 5.3
$_SESSION["loginname"] = $_POST["loginname"]
2nd if you are going to use sessions, your flow could be better, since this does not work.
$_SESSION["foo"] = 1;
header("Location: stuff.php");
Then you can't view the session data in stuff.php. You could either send the user to the main page, and do the authentication there, and if it passes then you just continue on with the loading of the main page, and if it doesn't, then you send the user back to the login page like this.
if($_SESSION["authenticated"] == 0)
{
header("Location: login.php");
die();
}
Also you should not be storing a password is cookie data -- this is a big security No-No!!!
If you want to do something like that set a unique - random - identifier that changes when they login and use that instead (you should still MD5 it)