Hello Stackoverflowers
Im new to PHP and im trying to make a members area for my testpage. I have made a successful register and login page, but now when I changed the code so if I log in correctly it redirects my to a page, and if I log in with wrong information it send me to a different page. However the members area is accessible if you type the location in the address-bar. Now, here's what I need help with, When someone tries to access that location without being logged in it should say "Access denied" but when you log in, it should redirect you to the members area and all it content is shown.
Here is my code:
login.php
<?php
session_start();
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'Data';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if(isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM Project WHERE username='$username' AND password='$password' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows($res) == 1){
header("Location: loggedin.php");
exit();
} else {
echo 'Användarnamn eller lösenord stämmer ej med informationen i databasen, var snäll försök igen <br>';
echo 'Gå tillbaka Eller Registrera dig';
exit();
}
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Logga in</title>
<script src="js/prefixfree.min.js"></script>
</head>
<body>
<div class="body"></div>
<div class="grad"></div>
<div class="wrapper">
<div class="header">
<div>bababa<span>bababa</span></div>
</div>
<br>
<div class="login">
<form method="post" action="login.php">
<input type="text" placeholder="Användarnamn" name="username" required><br>
<input type="password" placeholder="Lösenord" name="password" required><br>
<input type="submit" value="Logga in">
</form>
</div>
</div>
<script src='http://codepen.io/assets/libs/fullpage/jquery.js'></script>
</body>
</html>
signup.php
<!DOCTYPE HTML>
<html lang="sv">
<head>
<link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" >
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
});
$(".email").focus(function(){
$(".email-help").slideDown(500);
}).blur(function(){
$(".email-help").slideUp(500);
});
</script>
</head>
<div class="wrapper">
<h1>Registrera er här</h1>
<p>Detta är ett test-formulär för Webbutvecklingsprojektet. Skriv ditt namn här
under och om allt funkar rätt skall systemet lagra ditt namn i en MySQL databas.</p>
<form class="form" name="form" method="post" action="add.php">
<input type="text" id="username" name="username" placeholder="Användarnamn" required>
<input type="password" id="password" name="password" placeholder="Lösenord" required>
<input type="email" id="email" name="email" placeholder="E-mail" required>
<input type="submit" class="submit" value="Registrera dig">
</form>
<h3>
Allmänt & regler:
</h3>
<ul>
<li>Maximalt 2GB Lagring</li>
<li>Du måste skriva för- och efternamn</li>
<li>Databasen lagrar bara upp till 60 användare</li>
</ul>
</div>
<p class="optimize">
</p>
</html>
And last: loggedin.php
<?php
session_start();
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'Data';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if(!isset($_SESSION['username'])) {
die("Please login");
} else {
echo 'Du är inloggad';
}
?>
FTR: I tried the if isset but even when I logged in correctly the same message shows up: Please log in, how should I fix this?
Im a newbie at this so help me a bit extra
Thank you!
You can use Cookies or SESSION to do this.
When a user is authenticated, before redirecting to homeS page you should set a session variable like this: $_SESSION['id']=$user_id;. And if you want to set COOKIES so that user can access his account directly even after closing browser, you can set it like this setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // for 1 day.
So, now at the start of every page you need to start session session_start() to get the session value you set during login.
If a user_id of any user info exists in the session it will automatically use that info to access the page.
Now considering you want that the user is automatically redirected to login page/ACCESS DENIED if he tries to access home page.. You can do this by checking if the session user_info or cookie exist or not...if it doesn't redirect him to the login page or any error page as per you need...
In your code, before header("Location: loggedin.php"); create a session $_SESSION['username'] = $username;. And keep in mind to session_start() on every page, where $_SESSION value is going to be used..
What you would do is to redirect to a login page if user is not logged in.
if(!isset($_SESSION['username'])){
header('location: login.php');
}
I tried the if isset but even when I logged in correctly the same message shows up: Please log in, how should I fix this?
OK, when you log in succesfully, just before you redirect the user to the other page:
header("Location: loggedin.php");
you've to assign a session variable to the user, like this (for example. It depends how you want to identify them).
$_SESSION['ID'] = $row['ID'];
I think this is enought
By the way, please, don't use mysql_query
Use instead: mysqli extension.
(for more information)
Hope it helps
You have started the session session_start, but you haven't actually set the $_SESSION['username']. You need to set the session variable in between these two line.
if (mysql_num_rows($res) == 1){
// set session variable here
header("Location: loggedin.php");
exit();
}
Make sure you use the session_start() on the top of every page so that your able to check if the person who is viewing the page is logged in.
Also just another tip mysql_connect has been deprecated see here, you can use mysqli or PDO which escapes things automatically for you.
Related
I am currently in the process of developing a browser based game in php to test myself, and unfortunately I am having trouble with sessions. The pages seem to all just go blank if i set session include in the header, but then it doesn't redirect to membersarea.php when a user logs in using the form (form works i think). I may be doing all this wrong
header.php
<?php
include 'inc/conf.php';
?>
<!DOCTYPE html>
<head>
<title>Mineshaft Online | Free to play Browser MMORPG</title>
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<?php
if(isset($_SESSION['username'])) {
?>
<div class="navigation">
<ul>
<li>Dashboard</li>
<li>Mineshaft</li>
<li>Smeltery</li>
<li>Blacksmith</li>
<li>Settings</li>
<li>Logout</li>
</ul>
</div>
<?php
} else {
?>
<div class="navigation">
<ul>
<li>Home</li>
<li>Login</li>
<li>Register</li>
</ul>
</div>
<?php
}
?>
<div class="main-content">
and here is the login.php
<?php
include 'inc/conf.php';
include 'header.php';
if(isset($_POST['submit'])){
// Escape special characters in a string
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// If username and password are not empty
if ($username != "" && $password != ""){
// Query database to find user with matching username and password
$query = "select count(*) as cntUser from users where username='".$username."' and password='".$password."'";
$result = mysqli_query($conn, $query); // Store query result
$row = mysqli_fetch_array($result); // Fetch row as associative array
$count = $row['cntUser']; // Get number of rows
if($count > 0){
$_SESSION['username'] = $username;
header('location: membersarea.php');
} else {
echo "Error! Invalid username and password.";
}
}
}
?>
<form method="post" action="">
<div id="div_login">
<h1>Login</h1>
<div>
<input type="text" class="textbox" id="username" name="username" placeholder="Username" />
</div>
<div>
<input type="password" class="textbox" id="password" name="password" placeholder="Password"/>
</div>
<div>
<input type="submit" value="Submit" name="submit" id="submit" />
</div>
</div>
</form>
Here is the 'inc/session.php' file
<?php
session_start();
if(!isset($_SESSION["username"])) {
header("Location: login.php");
exit();
}
?>
It sounds like the inc/session.php file isn't included at any point in your project. If you want to use sessions, all the scripts using them must start with the session_start() function, and that, before you start to write any html in your page.
That being said, I'm tempted to assume that you've made a little mistake, writing 'inc/session.php' instead of 'inc/config.php' file, which is indeed loaded in your scripts.
I see two things that you should check:
In your 'login.php' file, you include the 'inc/config.php' as well as the 'header.php' file (which already includes 'inc/config.php'). That might be a problem, because you will then start your sessions two times.
In your 'inc/config.php' file (again, assuming that this is the 'inc/session.php' that you wrote), you start the sessions, and immediately say "if the session 'username' doesn't exist, then we redirect to login.php", which would be a problem if you don't have your 'username' session created before... this would do a redirection loop and your web browser should stop and display a message explaining so.
Other than that, make sure that your server has the sessions activated, you could write a simple script (with nothing else in the file, to keep it simple) like this:
<?php session_start(); $_SESSION['test'] = 'it works!'; ?>
Run the script once, then change the same file to:
<?php session_start(); if(isset($_SESSION['test'])) { echo $_SESSION['test']; } else { echo 'The SESSION test has not been set'; } ?>
And see what your script say.
I'm making a very simple login script (beginner at PHP) and here is my code. I can't figure out how to redirect after true login credentials. I know this probably is a duplicate but I can't figure this out without help on my exact script (as mentioned above I'm not that good).
update: So I have fixed name in password, form method, and the redirect . But now I'm getting to a empty page, something is wrong with my function as one comment earlier. I'm also a dummie at MySQL can someone help me further? My code is updated
Another update
Okay so i have finished all of my script, but the problem is my sql functions. So does anyone know mysqli and can translate it?
<?php $tilkobling = mysqli_connect("localhost","root","root","login_form");
if(isset($_POST["name"], $_POST["password"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$result1 = mysql_query("SELECT username, password
FROM user
WHERE username = '".$name."'
AND password = '".$password."'");
if(mysql_num_rows($result1) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>login</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>bypass to information site</h2>
<div class="login-page">
<div class="form">
<h1>Login</h1>
<form method="post" class="login-form">
<input name="name" type="text" placeholder="username"/>
<input name="password" type="password" placeholder="password"/>
<button name="submit">login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script type="text/javascript">
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
</html>
You're using mysqli connector and mysql functions so let's assume you'll use mysql for all
$tilkobling = mysql_connect("localhost","root","root");
mysql_select_db( "login_form", $tilkobling );
and you'll need to add session_start() before using/setting any session variables
session_start();
$_SESSION["logged_in"] = true;
Your header needs to be in the true portion of the if/else, which is where you set your $_SESSION variables, here you are:
if(mysql_num_rows($result1) > 0 )
{
session_start();
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
Have you Tried the HTML meta tag, this subtitutes the header() function.
Of course initially convert it into PHP code. Like this:
Echo "<meta http-equiv='refresh' content='0; URL=put your url in here to the page you like to redirect to'>" ;
This should probably operate correctly.
I want to create login page for admin and worker, and each of them will have different content table in their page once they logged in.
I've installed insert php plugin to write code in page directly.
I am using session for login and I want to use record set to create custom table in each page.
I created a code in dreamweaver then post it in page text.
I have created this code but it didn't work as php and didn't logged in and shows code in the page.
[insert_php]
error_reporting(E_ALL);
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "lujcarwa", "lcarwash2015");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = mysqli_real_escape_string($password);
// Selecting Database
$db = mysqli_select_db("login", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login']=$username; // Initializing Session
header("location: profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
error_reporting(E_ALL ^ E_DEPRECATED);
include('login.php'); // Includes Login Script
if(isset($_SESSION['login'])){
header("location: profile.php");
}
error_reporting(E_ALL ^ E_DEPRECATED);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "lujcarwa_washer", "dj0P7]w4S]");
// Selecting Database
$db = mysqli_select_db("lujcarwa_washer", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysqli_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
[insert_php/]
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1> Login </h1>
<div id="login">
<form action="" method="post">
<p>
<label>UserName :</label>
</p>
<p>
<br />
<input id="name" name="username" placeholder="username" type="text">
<br />
<label>
<br>Password</label>
<br />
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
</p>
</form>
</div>
</div>
</body>
I'm not known with the [insert_php] plugin but it looks like it's a issue with not closing you [insert_php] tag like this [/insert_php] at the end of your php.
Edit:
You are closing it like:
[insert_php/] //While it should be: [/insert_php]
Hope this helps you out.
Edit:
I just took a look at the plugin description and saw this in the FAQ:
Why can't I set cookies or do a browser redirect?
With PHP, cookies are set in the web page header lines, before any page content is processed. Redirects, too, are done in the header lines. When PHP code is within a post or a page, all the header lines have already been sent, along with part of the content. At that point, it is too late to set cookies or redirect with PHP
So it looks like you can't use this plugin to redirect the user at login.
I would suggest just to write the php in your template folder in a custom page template or header file.
Hope this helped!
I have created a webpage (lets call the root as main.php) and decided to put a login on top of it (file index.php). The login works fine, but the problem is this. If I type the address of the page (main.php) directly in the browser, it is opened.
Is there any way to prevent opening the page unless I go through the login?
In case it is relevant, this is the login code:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="login_container">
<div id="login-form">
<h3>Login</h3>
<fieldset>
<form action="checklogin.php" method="post">
<input name="username" type="text" required placeholder="Username">
<input name="password" type="password" required placeholder="*******">
<input type="submit" value="Login">
</form>
</fieldset>
</div>
</div>
</body>
</html>
and it directs to :
<?php
ob_start();
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = pg_escape_string($username);
$password = pg_escape_string($password);
if($username == "username" && $password == "password"){
$_SESSION['username']="username";
$_SESSION['password']="password";
header("location:main.php");
}
else header("location:index.php");
ob_end_flush();
?>
You need to check, on every request that requires a login, that the user is logged in and is authorized.
A good way of looking at this is seeing the request URL as part of the input to your program. Just like the cookies and GET/POST parameters are input.
main.php will either return a page with data or a request for login.
Sure.
Check if the user is currently logged on when they access the page using php sessions if they aren't logged on send an error, or redirect them elsewhere.
I have created a HTML page which takes user-id and password from user and then check there validity through database. Till now i was directing them to another page after successful login. But now i want to update same page after login. Just like www.facebook.com ; when we are NOT logged in its asks for user-id and password, but if we are login our profile contents are displayed on the same page i.e. facebook.com. What i was doing; directing it to page "login.php" which of course you can access without login.
For example there is a page "movies.com" which allows user to watch some movies after login; before i was just directing them to another page say "successful_login.com" after they login. It was a funny approach, but was working for my college assignments.
PS. Am just a noob, sorry if i asked something funny.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("data");
if($_POST)
{
$id=$_POST["email"];
$pwd=$_POST["password"];
$pwd=hash( 'sha256', $pwd);
$sql=mysql_query("SELECT* FROM admin_data WHERE id='$id' AND pass='$pwd'");
if($sql)
{
header("Location: login.php");
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
To use the session variable you need to start session at the top.
session_start();
Now store the email value in the session in here.
if(mysql_num_rows()>0)//It was originally if($sql)but I am using mysql_num_rows
//The reason for saving the value in the session here is this.
First you want to make sure that user have valid credential to log in.
{
$_SESSION['email']=$id
header("Location: login.php");
}
In your form you can do something like this
session_start();//Start the session at the top so you can use the session variable.
then simply use if else statement.
if($_SESSION['email']==TRUE)
{
$email=$_SESSION['email'];
//Now you can run the query by using $email to fetch the record of the user.
}
else
{
//Show them a form or redirect them to another page.
}
Note:mysql is deprecated and is going to be dropped soon. Use mysqli or P.D.O