I currently have 2 pages, one a log in page, and when the log in details are correct, it redirects the user to the gold page. However you can just access the gold page through the URL and i only want it to open if the user logs in.
<?php
?>
<html>
<head>
<title>Log-in</title>
</head>
<body>
<p>Please enter your username and password</p>
<form method="post">
<input type="integer" name="userID"/>
<input type="text" name="password"/>
<input type="submit"/>
</form>
<?php
$i = $_POST["userID"];
$j = $_POST["password"];
$gold_cookie = "gold";
if (isset($i) && $i == "2" && isset($j) && $j=="hi") {
session_start();
$_SESSION['login_user']= $i;
setcookie($gold_cookie , time()+30) ;
header("Location:gold.php");
}
if (isset($i) && $i != "2" && isset($j) && $j !="hi") {
echo "Get lost bro!";
}
$_SESSION ["first_name"] = "Kevin";
$name = $_SESSION ["first_name"];
?>
</body>
</html>
html>
<head>
<title>Log-in</title>
</head>
<body>
<p>You have made it!</p>
<p> TAKE SOME GOLD </p>
<img src="http://ei.marketwatch.com//Multimedia/2013/04/19/Photos/MG/MW-BB708_GoldUs_20130419105117_MG.jpg?uuid=9fd4d8c0-a900-11e2-a57c-002128040cf6">
</body>
</html>
Could somebody direct me into the right direction please?
Thanks
Put this in gold.php at the beginning:
session_start();
if (empty($_SESSION['login_user'])) {
die('Not authorized');
}
But I would advise to use a php framework. A simple framework with routing like SlimPHP, will make such things much easier and more flexible.
//Add an if statement in your gold page :
if(User is logged in)
{
//Your gold page code
}
else /**redirect user to the login page*/
{
header("Location: login_page.php");
}
Related
I am working on a simple login form with sessions..Here is my index.php code
<?php
ob_start();
session_start();
?>
<?
// error_reporting(E_ALL);
// ini_set("display_errors", 1);
?>
<html lang = "en">
<head> </head>
<body>
<h2>Enter Username and Password</h2>
<div class = "container form-signin">
<?php
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username']) && !empty($_POST['password']))
{
if ($_POST['username'] == '1' && $_POST['password'] == '1' )
{
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
header('Location: /test/login.php');
}
else $msg = 'not working';
}
?>
</div> <!-- /container -->
</div>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" >
<?php echo $msg; ?>
<input type="text" name="username">
<input type="password" name="password" >
<input type="submit" name="login">
</form>
</body>
</html>
When someone write the right password, he will go to this page
localhost:8080/test/login.php
but, if someone try to open "localhost:8080/test/login.php" directly, he will go to this page "localhost:8080/test/index.php".
this is my login.php code
<?php
session_start();
if ($_POST['username'] == '1' && $_POST['password'] == '1' )
{
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
header('Location: /test/login.php');
}
else{
header('Location: /test/index.php/');
}
?>
test 1
Youve made several small mistakes (see comments), but the big mistake you make is that the session is never checked. Use this at login.php :
<?php
session_start();
if(!isset($_SESSION["valid"])){
header("location: index.php");
die();
}
?>
This checks if the session is set, and if not redirects back to index php
Good day!
I'm trying to make a website where you could only access it by first typing the password in the front page(www.mywebsite.com/index.php)
Once I enter the password, It will get the file home.html from outside my public_html.
Then in that page(home.html) there will be links using the variable z (www.mywebsite.com/index.php?z=one) which will return 1.html or other pages.
Here's what I tried so far, but even if i use www.mywebsite.com/index.php?z=one
it still opens home.html
Can I get some help? And/or is what I'm trying possible?
<?php
$pass = $_POST['pass'];
if ($pass == "1234") {
$page = $_GET['z'];
if ($page == "one") {
include("../1.html");
} else {
include("../home.html");
}
} else {
if (isset($_POST)) {
?>
<!DOCTYPE html>
<html lang="en">
<form role="form" method="POST" style="margin: 0px" action="index.php">
<input type="password" name ="pass" class="form-control" id="pwd"> </input>
<input type="submit" class="btn btn-danger" value="Enter"></input>
</form>
</html>
<?php
}
}
?>
Thats not the way to approach this.
First make use of a session, but only hold a isLoggedIn flag in the session not the password.
Second, all scripts can be in the public_html folder, but what you do is add a little script that checks the loggedIn state to all scripts and if not loggedIn throw the login page
Heres a simple example
login_check.php
<?php
session_start();
if ( ! isset($_SESSION['loggedIn']) || $_SESSION['loggedIn'] == 0) {
header('Location: login.php');
exit;
}
Now in your login script
login.php
<?php
session_start();
if ( isset($_SESSION['loggedIn'] && $_SESSION['loggedIn'] == 1) {
// already logged in
header('Location: index.php.php'); // or some other page
exit;
}
If ( "The password is correct" ) { // this is of course pseudo code
$_SESSION['loggedIn'] = 1;
header('Location: somepage.php');
exit;
} else {
unset($_SESSION['loggedIn']);
header('Location: login.php');
exit;
}
?>
Now in all your other scripts
<?php
// first thing is always to check if this user is logged in
// so any access from a user not yet logged in just get
// thrown to the login page, or maybe your index.php
require_once 'login_check.php';
You can also use this session to hold useful but not sensitive things like
$_SESSION['user_id']; // id of the users info in user table
$_SESSION['FirstName'];
$_SESSION['LastName'];
$_SESSION['nickname'];
and anything else that might be useful to know across your application that you dont want to go to the database each time to collect.
Additional info
Your HTML is not well formed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>
<form role="form" method="POST" style="margin: 0px" action="index.php">
<input type="password" name ="pass" class="form-control" id="pwd" />
<input type="submit" name="login" class="btn btn-danger" value="Login" />
</form>
</body>
</html>
You could store the get/post pass in a session like $_SESSION['pass']
But you better encrypt it with a sha1 a least like
$_SESSION['pass'] = sha1($pass);
and to get it back
if($_SESSION['pass'] == sha1("1234")){}
You should use session.
But it is not a good practice to store your password in a session.
<?php
session_start();
if(isset($_POST['pass'])){
$_SESSION['p'] = md5($_POST['pass']);
//$pass = $_POST['pass'];
if($_SESSION['p'] == md5("1234"))
{
$page = $_GET['z'];
if($page == "one")
{
include("../1.html");
}
else
{
include("../home.html");
}
}
}
?>
I'm sure this will help you.
<?php
session_start();
if (!empty($_POST['pass']) && $_POST['pass'] == "1234") {
$_SESSION['pass'] = $_POST['pass'];
}
if (empty($_SESSION['pass'])) {
?>
<!DOCTYPE html>
<html lang="en">
<form role="form" method="POST" style="margin: 0px" action="index.php">
<input type="password" name ="pass" class="form-control" id="pwd"> </input>
<input type="submit" class="btn btn-danger" value="Enter"></input>
</form>
</html>
<?php
die;
}
$page = $_GET['z'];
if ($page == "one") {
include("../1.html");
} else {
include("../home.html");
}
?>
I’m creating a site where users can complete a number of special offers to gain various rewards but I’m struggling how to store the user’s progress.
I envisage if a user completes offer 1 and 2, when they next log in they will be presented with offer 3. You could imagine each offer like a rungs in a ladder, and have to be competed consecutively.
Just to make things clearer; currently, when a user logs in they are redirected to the page for offer 1 which is great. But lets say they leave the site after completing a few offers then later return to the site they will be back to offer 1 again which is not so great. I’m trying to store their progress.
(I think a potential solution) to solve this, I’ve created a column in my database called “redirect” and by default this will be example.com/offer1. I need recall from the database and to redirect to this URL when the user logs in. And, every time an offer is completed this URL is then updated as required so on the next login progress is saved.
So, when the user first logs in they will be sent to the first offer (example.com/offer1) Then , after completing the first offer they will press “proceed to next offer” and this redirect then to offer 2 and will fire a script to update the redirect URL for that user to example.com/offer2 – in this way if they leave the site and return again they will be at offer 2. After offer 2 is completed and they press “proceed to next offer” , a similar script will fire updating that URL to example.com/offer3 – in this way user progress will be stored.
In a nutshell, I’m asking (1) how can I redirect to a user upon login to the URL in the redirect column and (2) how to update this URL when a button is pressed. Or would there be a more effective way to achieve this (using sessions perhaps).
Below is my current login script which works fine (base.php has the part to connect to the database), currently it directs to example.com/offer1 upon login or if a session is already present and the user hits the log in box. How could I change it to look up the users URL from the redirect column of the database instead? And then how could I code a script to update this URL in the database after each offer is completed?
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Management System </title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="main">
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
?>
"<meta http-equiv="refresh" content="0;URL='http://example.com/offer1'" />"
<ul>
<li>Logout.</li>
</ul>
<?php
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
?>
"<meta http-equiv="refresh" content="0;URL='http://example.com/offer1'" />"
<?php
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
else
{
?>
<h1>Member Login</h1>
<p>Thanks for visiting! Please either login below, or click here to register.</p>
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
</div>
</body>
</html>
NB: I'm assuming that the column where the number of the offer is stored is called "offer" and it is in the table named "users".
Warnings
You're using mysql extension for your login code, which is deprecated. Use mysqli instead.
To hash users' passwords, you're using md5, which can be broken with a brute force attack. Use crypt() instead.
You can fix these problems using this code for login (obviously, after you have hashed all passwords with crypt() - to do that, see the last point of my answer)
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Management System </title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="main">
<?php
$con = mysqli_connect("localhost","root","","your_db");
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
?>
"<meta http-equiv="refresh" content="0;URL='http://example.com/offer1'" />"
<ul>
<li>Logout.</li>
</ul>
<?php
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysqli_real_escape_string($_POST['username']);
$password = md5(mysqli_real_escape_string($_POST['password']));
$checklogin = mysqli_query($con,"SELECT * FROM users WHERE Username = '".$username."'");
$row = mysqli_fetch_array($checklogin);
if(mysqli_num_rows($checklogin) == 1 AND crypt($password, $row['Password']) == $row['Password'])
{
$email = $row['EmailAddress'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
?>
"<meta http-equiv="refresh" content="0;URL='http://example.com/offer1'" />"
<?php
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
else
{
?>
<h1>Member Login</h1>
<p>Thanks for visiting! Please either login below, or click here to register.</p>
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
</div>
</body>
</html>
Redirecting to the right offer on login
You need to edit this:
?>
"<meta http-equiv="refresh" content="0;URL='http://example.com/offer1'" />"
<?php
In this way:
echo '<meta http-equiv="refresh" content="0;URL=\'http://example.com/offer'.$row['offer'].'\'" />';
Updating the value on button click
1)Create a php file and put into it this code:
<?php
session_start();
$con = mysqli_connect("localhost","root","","your_db");
$select = mysqli_fetch_assoc(mysqli_query($con,"SELECT offer FROM users WHERE Username = '".$_SESSION['username']."'"));
$plus = $select['offer']++;
mysqli_query($con,"UPDATE users SET offer=".$plus);
header("location: http://example.com/offer".$plus);
?>
2)Point the button to the file you've just created
Hashing all passwords previously stored with crypt()
Launch this code once (A backup of your database before starting is strongly advised)
<?php
$con = mysqli_connect("localhost","root","","your_db");
function Casual($length=22){
$characters ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
$code = "";
for($i = 0; $i<$length; $i++){
$code = $code.substr($characters,rand(0,strlen($characters)-1),1);
}
return $code;
}
$query = mysqli_query($con,"SELECT Password,Username FROM users");
while($assoc = mysqli_fetch_assoc($query)){
$newcode= '$2a$07$'.Casual(22).'$';
$hashed_password = crypt($assoc['Password'],$newcode);
mysqli_query($con,"UPDATE users SET Password='".$hashed_password."' WHERE Username='".$assoc['Username']."'");
}
?>
First of all I won't build a login system that uses a database, I know it's more secure but in this case it's not relevant...
I have three files login.php, admin.php and config.php. The users email and password is stored in variables in config.php. If the user is logging in a session should be set. Then if a user that hasn't logged in trying to access admin.php ":-(" should be printed. But now the ":-(" is always printed and something needs to be wrong with how I coded it all...
config.php:
<?php
//site data
$title = "Abbesplace";
$siteurl = "index.php";
//user data
$password = "testtest";
$email = "example#example.com";
$name = "Albin Larsson";
?>
login.php:
<?php
require_once("config.php");
if (($_POST['email'] == $email && $_POST['password'] == $password)) {
//login
session_start();
$_SESSION['logged']= "welcometomoon";
header("Location: admin.php");
} else {
echo "login faild";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
</head>
<body>
<div>
<form method="post" action="login.php">
Email:<input type="email" name="email"/>
Password:<input type="password" name="password"/>
<input type="submit"/>
</form>
</div>
</body>
</html>
admin.php:
<?php
if(isset($_SESSION['logged'])){
echo "Hello";
} else {
echo ":-(";
}
?>
Any suggestions on what I should make different?
(I'm a newbie when i comes to PHP)...
You have to call session_start on every page. Right now you are only calling it when you post to the login form.
Well i just got my login page to work as it should and of course this has caused something else to go wrong, the issue i am having is that when you go to the home page it should allow you to browse the home page and navigate to other regular pages not logged in to any sort of account (don't have to be registered or logged in to view these pages) but for some reason when i click on my EOI_home.php (which is my home page) as a non-logged in user it automatically takes me to my login.php (my login page) and forces me to log in before i can view the home page, meaning that i am not able too view the home page as a non-registered or non-logged in user which i should be able to do. Here is my code for my home page (EOI_home.php) :
<head>
<title>Expression of Interest</title>
<link rel="stylesheet" href="Assign.css" type="text/css" />
</head>
<body>
<?php
require_once("nocache.php");
session_start();
if (!$_SESSION["who"]){
header("location: logoff.php");}
else {
$staff = $_SESSION["who"];
$access = $_SESSION["school_type"];
?>
<div class="title_background"><h2>Moving into Year 7 in a NSW government school in 2015</h2>
<h2>Information guide and Expression of Interest form for parents and carers</h2></div>
<p><img src="img1.jpg" width="750" height="550"></p>
<div class="right">
<?php
if ($access == S){
echo '<p>Process EOI</p>';
echo '<p>Print Offer Status Letters</p>';
}
if ($access == P){
echo '<p>School Leavers</p>';
echo '<p>Add School Comments</p>';
}
echo '<p>Logoff</p>';
}
?>
<p>Home</p>
<p>Guidelines</p>
<p>Your Secondary School Options</p>
<p>Expression of Interest Form</p>
<p>Privacy Statement and Contact Us</p>
<p>Login</p>
</div>
<h1>Moving to secondary school</h1>
and here is my code for the login page (login.php) :
<body>
<?php
require_once("nocache.php");
$id = $_POST["id"];
$pword = $_POST["pword"];
$msgp = "";
if(!empty($_POST)) {
if(!empty($id) && !empty($pword)) {
require_once("dbconn.php");
$sql = "select username, school_type from school_info where username = '$id' and password = '$pword'";
$rs = mysql_query($sql, $dbConn);
if(mysql_num_rows($rs) > 0) {
session_start();
$_SESSION["who"] = $id;
$_SESSION["school_type"] = mysql_result($rs, 0, "school_type");
header("location: EOI_home.php");
}
} else {
header("location: login.php");
$msgp = '<span class="error>Incorrect username and/or password</span>';
}
}
?>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="login">
ID: <input type="text" name="id" /><?php echo $msgp; ?></td><br/>
pword: <input type="password" name="pword" /><br/>
<p>Home</p>
<input type="submit" value="log in" />
<input type="reset" />
</form>
Here is the nochache.php code :
<?php
header("Cache-Control: no-cache");
header("Expires: -1");
?>
Here is also the code for logoff.php, just incase :
<?php
session_start();
require_once("nocache.php");
session_destroy();
header("location: login.php");
?>
By the way the accounts have different access levels and with the different access levels different links are available on the home page e.g. access levels S and P.
If anyone could help me with a solution that would be really great, i am new to this stuff.
<?php
require_once("nocache.php");
session_start();
if ($_SESSION["who"]){
$staff = $_SESSION["who"];
$access = $_SESSION["school_type"];
?>
Just comment header("location: logoff.php");
also check code for logoff is working or not