PHP - refresh entire page from an included file? - php

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\">";

Related

Login implementation in PHP

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 */
}
?>

Check page permission by session?

I included header.php to every page for header logo and check page permission by SESSION!
So if you request main.php without login (session null state), It will display login page and do exit in header.php for not showing current page content.
Its header.php is work for every page except login.php.Because login page is not show login form
So I want to show login form ,how can I check in header.php for its ? Sorry for my poor english :(
login.php
<?php
session_start();
include("header.php");
if($_POST){
//set session logged in
}
?>
<div class="login-box ">
<h3> Log In </h3>
<form method="POST">
<input type="text" name="user" placeholder="Type User Name"><br>
<input type="password" name="pass" placeholder="Type Password"><br>
<input type="submit" name="submit" value="Login" class="button">
</form>
<span id="signup_text">You are not still a member.Click Sign Up</span>
</div>
header.php
<?php
session_start();
?>
<div id="header" class="container">
<div id="logo">
<h1>Online Quiz Management</h1>
</div>
</div>
<?php
if (isset($_SESSION['login'])) {
echo "<div id='menu'><ul><li>HOme</li><li>Signout</li></ul></div>";
}
else {
echo "<div class=head1> Your are not logged in<br> Please <a href=login.php>Login</a><div>";
exit;
}
?>
</div>
</div>
?>
main.php
<?php
session_start();
include("header.php");
?>
//show main code if logged in
Just add a check if the current page is login.php and don't run your block if it is
else if(!basename($_SERVER['PHP_SELF']) == "login.php") {
echo "<div class=head1> Your are not logged in<br> Please <a href=login.php>Login</a><div>";
exit;
}
i think u dont need to include the header.php to login.php, since it is check for the session, while the login.php is the session starter...
after all, try to add this to the header.php :
session_start();
if(!isset($_SESSION['login'])){
echo '<script language="javascript">';
echo 'alert("Please Login")';
echo '</script>';
echo("<script>location.href = 'login.php';</script>");//direct the user to login.php if they aren't logged in
}

Adding Function on Sign Out button by php

I am creating a website where I want to sign in and sing out. So when I sign in I redirect to home.html, so in home.html I added a button by naming it "logout", I want to add function on it so whenever I will click on that button it will sign me out. As I know already, the code I have to use but don't know how put that code to logout button?
I want to know how I can refer my this button name="logout" button to that specific code
session_destroy(); so when I m in home.html click on Sign out button it will destroy my current season and locate me back to index.php.
index.php
<form class="form-horizontal" role="form" action="process.php" method="post">
<div class="form-group">
<label id="email" for="inputtext" class="col-sm-4 control-label">User name:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="inputEmail" placeholder="User name" name="username">
</div>
</div>
<div class="form-group">
<label id="pass" for="inputPassword" class="col-sm-4 control-label">Enter Password</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" name="pass">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Sign me in!</button>
</div>
</div>
</form>
process.php
<?php
$action = $_GET['action'];
if ($action == 'logout') {
unset($_SESSION['username']);
}
$username = $_POST ['username'];
$password = $_POST ['pass'];
//fixed values
if($username=='syedhasan' AND $password=='Syed712207') {
echo "You have successfully logged in";
header('Location: home.html');
}
else {
echo "Credential is wrong";
}
?>
in home.html i have added this button
<input href="logout.php" type="submit" class="signout btn btn-warning"" value="Sign Out" name="logout">
THen i created logout.php
<?php
session_start();
unset($_SESSION);
session_destroy();
header("Location: index.php");
?>
Create another file named "logout.php".Place the below code.
<?php
session_start();
unset($_SESSION);
session_destroy();
header("Location: index.php");
?>
On click of "logout" button ,it should redirect to "logout.php".
Just create another page called logout.php. Unset the session there unset($_SESSION['someusername']) and write code to redirect to your home page.
header('Location: http://www.example.com/');
All you have to do is give user a link to sign out, and redirect the page to index.php.
home.html:
Logout
logout.php
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
ok
you have logout buttom with and you have to make logout.php and link it to logout buttom
for example
logout.PHP
<?PHP
session_start();
session_destory();
unset($_SESSION['user_id']);
header("location: login.html");
?>
And index.html like this
<a name="logout" href="logout.php"> Logout </a>
I assume your login page is login.php, there I guess you have a html form for username and password, and also have the user validation with the redirect to home.html. It makes sense to put the logout logic also in there.
Put the following code to the top of login.php:
$action = $_GET['action'];
if($action == 'logout') {
/* I'm sure you don't want to destroy the entire session, as there
could be other valuable data stored, so use unset to destroy only
the specific login-variable. */
unset($_SESSION['loginVar']);
}
$_SESSION['loginVar'] is the session var where you users login data is stored.
Now you can use the following href for the logout link / button:
login.php?action=logout
HTML
<a href='index.php?logout=1'>Logout</a>
PHP
if(isset($_GET['logout'))
{
session_destroy();
header('Location:home.php');
}

PHP - Checking if the user is logged on

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>';
}

How to redirect to another page using PHP [duplicate]

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
}
?>

Categories