I'm creating a website with a login.
Here is my login.php:
<?php
include 'connect.php';
include 'header.php';
echo '<h3>Sign up</h3>';
$username="";
$finished = false;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field cannot be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo '<p class="error">login failed';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul></p>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo '<p class="error">Something went wrong while registering. Please try again later.</p>';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
if(mysql_num_rows($result) == 0)
{
echo '<p class="error">You have supplied a wrong user/password combination. Please try again.</p>';
}
else
{
$_SESSION['signed_in'] = true;
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Successfully logged in as ' . $_SESSION['user_name'];
$finished=true;
}
}
}
}
if(!$finished) {
echo '<form method="post" action="">
<table>
<tr>
<td>Username:</td><td> <input type="text" name="user_name" value="' . $username . '"/></td>
</tr>
<tr>
<td>Password:</td><td> <input type="password" name="user_pass"/></td>
</tr>
</table>
<input type="submit" value="login" />
</form>';
}
include 'footer.php';
?>
my header.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="A short description." />
<meta name="keywords" content="put, keywords, here" />
<title>PHP-MySQL forum</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<h1>My forum</h1>
<div id="wrapper">
<div id="menu">
<a class="item" href="index.php">Home</a> -
<a class="item" href="/forum/create_topic.php">Create a topic</a> -
<a class="item" href="/forum/create_cat.php">Create a category</a>
<div id="userbar">
<?php
if($_SESSION['signed_in'])
{
echo 'Hello' . $_SESSION['user_name'] . '. Not you? Sign out';
}
else
{
echo 'Log in or create an account.';
}
?>
</div>
</div>
<div id="content">
and the footer:
</div><!-- content -->
</div><!-- wrapper -->
</body>
</html>
Now when i login succesfully, and i try to access the $_SESSION['signed_in'] in the header it is not set(i tried an output with echo and it didnt show anything). 'user_name' etc. is also not set, but in the login.php it has the correct content. What am i doing wrong?
For sessions to work in PHP, you must start them first using session_start(). You can do that in your script by either adding that at top of login.php or connect.php, Like below:
<?php
session_start();
include 'connect.php';
Better add it in connect.php to make it available on all other pages as well.
WARNING
mysql_* is DEPRECATED as of php-5.5 and was REMOVED in php-7.0. So instead use mysqli_* or PDO.
Why shouldn't I use mysql_* functions in PHP?
on the first line, the first thing to do is to create the session.
<?php
session_start();
?>
remember to write this line as the first thing on every file which uses the session variables
Related
So I'm making a Login - Successful Login page with PHP, and using MySQL Database. My code successfully checked the Username and Password and only allowed me to head to the next page once they are correct.
However, I cannot print out the Username on Successful Login page. So I'm not sure if my session is running properly or not.
login.php
<!DOCTYPE HTML>
<html>
<?php
session_start();
?>
<head>
<title>Login</title>
</head>
<body>
<!--<form action ="SuccessfulLogin.php" method = "get"> --> // If I put this in my code, the whole program stops checking Username and Password, and just put me to the next page
<?php
//define variables and set to empty values
$nameErr = $loginErr = "";
$Username = $website = $Password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Username"])) {
$nameErr = "Name is required";
} else {
$Username = test_input($_POST["Username"]);
}
if (empty($_POST["Password"])) {
$passErr = "Password is required";
} else {
$Password = test_input($_POST["Password"]);
}
//continues to target page if all validation is passed
if ( $unameErr ==""&& $passErr ==""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$hashpass=hash('sha256',$Password);
$sql="SELECT * from Members WHERE Username ='$Username' AND Password='$hashpass';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database");
$a=mysqli_num_rows($result);
if ($a===0){
$loginErr="Invalid username or password";
}else{
$_SESSION["Username"]=$Username;
header('Location: /SuccessfulLogin.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Login </h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
User Name: <input type="text" name="Username" value="<?php echo $Username;?>"/>
<span class="error">* <?php echo $unameErr;?></span>
<br/><br/>
Password:
<input type="text" name="Password" value=""/>
<span class="error">* <?php echo $passErr;?></span>
<br/><br/>
<span class="error">* <?php echo $loginErr;?></span>
<input type="submit" name="submit" value="Login"/>
</form>
<!--</form>--> // closing tag of form action SuccessfulLogin.php
</html>
SuccessfulLogin.php
<!doctype html>
<html>
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<body>
<!--<form action ="MemberMenu.php" method = "get">-->
<h2><?php echo "User $Username LOGGED IN"; ?></h2> // Doesn't print out the $Username
<p align="center"> Click here to be redirected to the menu page </p>
<!--</form>-->
</footer>
</body>
</html>
you need to check session isset or not.
Change
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
With
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
echo $Username;
}
?>
You're using $_GET["Username"] which will be empty in this example, and then setting $_SESSION["Username"] to the empty variable.
Also this is a very odd way to do user auth.
Change this line of code
<?php
session_start();
$Username=$_SESSION['Username'];
$_SESSION['Username']=$Username;
?>
Into:
<?php
session_start();
$Username=$_SESSION['Username'];
?>
Read more about PHP session here
I am having difficulty with header redirecting me to index.html from my login page. I'm not sure header is even the way to go but it is all that I could find on page redirection.
This code is just a simple login page which checks the username and password against a MySQL database.
The problem I am having is inside the if statement:
if(mysqli_num_rows($res) == 1){
header("Location: index.php");
exit();
}
full code for login.php:
<?php
//Connects to MySQL database using sql_connect.php
require "sql_connect.php";
?>
<?php
if(isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM login_test WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysqli_query($connection, $sql);
if(mysqli_num_rows($res) == 1){
header("Location: index.php");
exit();
} else {
echo "Invalid login information!";
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link rel="stylesheet" href="../style.css">
</head>
<body>
<form name="login" method="post" action="login.php">
<h3>Login</h3>
<p>Username: </p><input type="text"name="username">
<p>Password: </p><input type="password" name="password">
<br/>
<input type="submit"name="submit"value="log in">
</form>
<script src="../script.js" type="text/javascript"></script>
</body>
</html>
While I'm sure the rest of my code is far from perfect I am just really looking at how to redirect to a new page if the user is authenticated in the database? Is there a better option than header in my case or am I just implementing it wrong?
I used php header before, but have bad experience.
Normally I use javascript
echo '<script type="text/javascript">' . "\n";
if(isset($from))
{
echo 'window.location="..";';
}
else
{
echo 'window.location="..";';
}
echo '</script>';
header() function didn't work well may cause by your "mysqli_num_rows($res) == 1" result is false.
And There is no space between "Location" and your "index.php" like:
header("Location:index.php");
Or you can create a php function and use JavaScript, its a good way to avoid that.
function redirect($url, $prompt) {
$js_string = "<script>";
$js_string .= $prompt ? "alert('". $prompt ."');" : "";
$js_string .= "window.location = '{$url}';";
$js_string .= "</script>";
exit($js_string);
}
I have a log-in script for user login. The user information is stored in the MYSQL database. When i login for first time, it stores the information in the session and display the welcome message. But when i log-out and try to log-in again, the session array display empty although it is logged in.
Here are my codes:
reservation.php
<?php
session_start();
require_once("./includes/config_db.php");
$error1=array();
if(isset($_POST['submit'])){
if (preg_match ('%^[A-Za-z0-9]{4,8}$%', stripslashes(trim($_POST['user_id'])))) {
$e = escape_data($_POST['user_id']);
} else {
$e = FALSE;
$error1['user_id']="UserID Required!";
}
if (preg_match ('%^[A-Za-z0-9]{8,}$%', stripslashes(trim($_POST['password'])))) {
$p = escape_data($_POST['password']);
} else {
$p = FALSE;
$error1['password']="Password Required!";
}
if($e && $p){
$query="SELECT * FROM users WHERE(user_id='$e' AND password=SHA('$p')) AND active='NULL'";
$results=mysql_query($query);
if(mysql_affected_rows() == 1){
$row=mysql_fetch_array($results, MYSQL_NUM);
mysql_free_result($results);
$_SESSION['name']=$row[0];
$_SESSION['department']=$row[1];
$_SESSION['email']=$row[2];
$_SESSION['user_id']=$row[4];
$_SESSION['phone']=$row[5];
$_SESSION['pre']=$row[8];
//create second token
$tokenid=rand(10000,9999999);
$query2="UPDATE r_users SET token='$tokenid' WHERE user_id='$_SESSION[user_id]'";
$result2=mysql_query($query2);
$_SESSION['tokenid']=$tokenid;
session_regenerate_id();
mysql_close();
header("Location:local.php");
exit();
}else
{
$error1['active']="Either your Account is inactive or Email/Password is incorrect";
mysql_close();
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reservation System</title>
<!--Link to external files-->
<link rel="stylesheet" type="text/css" href="css/reservation.css"></link>
</head>
<body class="body">
<div id="mainHeader">
<?php include('includes/ers_header.php'); ?>
</div>
<div id="content">
</div>
<div id="navigation">
<?php include('includes/ers_nav.php');?>
<h3>Member Login</h3>
<form id="login" action="reservation.php" method="post">
<?php if(!empty($error1['active'])) echo '<p><font color="red">'.$error1['active'].'</font></p>'; ?>
<label for="userid">User ID:</label>
<input type="text" name="user_id" <?php if (!empty($error1['user_id'])){ echo 'value="'.htmlentities($_POST['user_id']).'"';} ?> autofocus />
<?php if (!empty($error1['user_id'])){ echo '<p><font color="red">'.$error1['user_id'].'</font></p>';} ?>
<label for="password">Password:</label>
<input type="password" name="password" />
<?php if (!empty($error1['password'])){ echo '<p><font color="red">'.$error1['password'].'</font></p>';} ?>
<button class="submit" name="submit" type="submit">Login</button>
</form
</div>
</body>
</html>
ers_header.php:
<h1>XXXXXXXXXX</h1>
<h2>YYYYYYYYYYY</h2>
<h2>ZZZZZZZZZZZZ</h2>
<?php
require_once("./includes/config_db.php");
if(isset($_SESSION['name'])){
$sql="SELECT token FROM users WHERE(user_id='$_SESSION[user_id]')";
$result=mysql_query($sql);
if (mysql_affected_rows() == 1) { // A match was made.
$row = mysql_fetch_array ($result, MYSQL_NUM);
mysql_free_result($result);
mysql_close(); // Close the database connection.
if($_SESSION['tokenid'] == $row[0]){
echo '<p>Welcome';
echo " {$_SESSION['name']}";
$loggedin=1;
}else{
$loggedin=0;
}
}
}
if(isset($_SESSION['user_id']) AND (substr($_SERVER['PHP_SELF'] AND $loggedin,-10)!='logout.php')){
echo' Logout';
echo'</p>';
}
?>
logout.php
<?php
session_start();
require_once("./includes/config_db.php");
if ( !isset( $_SESSION['name'] ) ) {
header("Location: reservation.php");
exit();
} else {
$_SESSION = array(); // Destroy the variables.
session_destroy(); // Destroy the session itself.
setcookie( session_name(), ", time()-300, '/', ", 0 ); // Destroy the cookie.
header("Location:reservation.php");
}
I don't know what is the problem. I have tried a lot but couldn't find it out. Please can anyone figure out my mistake.
You really should only need to unset the $_SESSION array, not destroy the session and cookie data, try removing those lines, but also:
mysql_affected_rows should be mysql_num_rows
also this line of code is incorrect:
$query2="UPDATE r_users SET token='$tokenid' WHERE user_id='$_SESSION[user_id]'";
$_SESSION[user_id] should be $_SESSION["user_id"] and you should wrap it in {}. PHP probably gives warnings about this.
and this line of code is strange:
if(isset($_SESSION['user_id']) AND (substr($_SERVER['PHP_SELF'] AND $loggedin,-10)!='logout.php')
is the $loggedin,-10 really supposed to be in substr?
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I have been struggling with this error for some time now.
I have created a profile site, If I run it localy there is no problem to login and get redirect to the profile page.
But at soon I upload it, nothing happends when i press the login . I just get an empty page ... But if i open the page source I can se that its reading my init.inc.php file. but nothing more than the comment code is readed..
And since i wont get any error message I really dont know whats the problem.
aaa hope you get what Im trying to say :)
This is my login page
<?php
include 'core/inc/init.inc.php';
if ($_SERVER['HTTP_HOST'] != 'localhost') // running in remote server
$server = 'pixeltouch2.mysql.domeneshop.no';
else // running locally
$server = 'pixeltouch2.mysql.domeneshop.no';
mysql_connect($server, "LOGIN", "pass") or die(mysql_error());
mysql_select_db("pixeltouch2") or die(mysql_error()) ;
$errors = array();
if (isset($_POST['username'], $_POST['password'])){
if(empty($_POST['username'])){
$errors[] = 'The username cannot be empty.';
}
if(empty($_POST['password'])){
$errors[] = 'The password cannot be empty.';
}
//Log in
if (valid_credentials($_POST['username'], $_POST['password']) == false ){
$errors[] = 'Username / Password incorrect.';
}
if (empty($errors)){
$_SESSION['username'] = htmlentities($_POST['username']);
$_SESSION['uid'] = fetch_user_id($_SESSION['username']);
header("Location: profile.php?uid=" . $_SESSION['uid']);
die();
echo $_SESSION['uid'];
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Pixeltouch</title>
<link rel="stylesheet" type="text/css" href="ext/style.css" />
</head>
<body>
<div id="page-wrap">
<div id="main-content">
<br/>
<?php include_once('template/head.inc.php');
?>
<div id="menu">
<?php include_once('template/nav.inc.php');
?>
</div>
<!-- SKRIVBOX-->
<div>
<?php
if(empty($errors) == false){
?>
<ul>
<?php
foreach ($errors as $error) {
echo "<li>$error</li>";
}
?>
</ul>
<?php
}else{
echo 'Need an account ? Register here';
}
?>
</div>
<br/>
<form method="post" action="" >
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="<?php if (isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</p>
<p>
<label for="password">Password: </label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" value="Login" />
</p>
</form>
<!-- SKRIVBOX END-->
</div>
<?php include_once('template/foot.inc.php');
?>
</div>
</body>
</html>
And my init.inc.php file
<?php
session_start();
/*
mysql_connect("pixeltouch2.mysql.domeneshop.no", "LOGIN", "PASS") or die(mysql_error()) ;
mysql_select_db("pixeltouch2") or die(mysql_error()) ;
*/
if($_SERVER['HTTP_HOST'] != 'pixeltouch2.mysql.domeneshop.no')// running in remote server
$server = 'pixeltouch2.mysql.domeneshop.no';
else // running locally
$server = 'pixeltouch2.mysql.domeneshop.no';
mysql_connect($server, "login", "pass") or die(mysql_error());
mysql_select_db("pixeltouch2") or die(mysql_error()) ;
$path = dirname(__FILE__);
include("{$path}/user.inc.php");
?>
<!--Registration/Login (START)-->
<?php
$exceptions = array('register', 'login', 'user_list', 'profile', 'edit_profile', 'upload');
$page = substr(end(explode('/', $_SERVER['SCRIPT_NAME'])), 0, -4);
if(in_array($page, $exceptions) == false){
if (isset($_SESSION['username']) == false){
header('Location: login.php');
die();
}
}
?>
<!--Registration/Login (END)-->
<!--User Profile (START)-->
<?php
$_SESSION['uid'] = 1;
?>
<!--User Profile (END)-->
Error LOG
Warning: Cannot modify header information - headers already sent by (output started at /home/3/p/pixeltouch/www/book/core/inc/init.inc.php:2) in /home/3/p/pixeltouch/www/book/login.php on line 32
When I look # line 32 I its my header("Location: profile.php?uid=" . $_SESSION['uid']);
die();
echo $_SESSION['uid'];
So its something about the session, is there another way to write the code so it work ?
Well the error says it right there. You are already sending output to the browser, and by saying "output" it means anything sent to the browser that are not http headers.
So look in your file for:
echo/print statements before your header location statement.
whitespaces or newline charachters before your <?php tags (even in included files).
Using the byte-order mark (BOM) at the beginning of a page.
So.. looking at your code samples I see (The + sign indicates spaces)
++++<?php
session_start();
You need to correct that use
<?php
session_start();
// No spaces at the beginning
Or even in this part
// You close the php tag
?>++++++++++
++++<!--Registration/Login (START)-->+++++++
<?php
$exceptions = array('register', 'login', 'user_list', 'profile', 'edit_profile', 'upload');
You dont need to do that, and you are sending a html comment.
To avoid such problems you could always use output buffering to ensure no output gets sent before the headers.
I currently have this code in my project:
require_once('mysql.inc.php');
session_start();
if (!isset($_SESSION['username']) && !isset($_SESSION['uid']))
{
login_sequence();
}
else
{
login_check($_SESSION['username'], $_SESSION['uid']);
}
function login_sequence()
{
echo '<p>' . $pretext . '</p><form method="post" action="" /><label for="password">Password: </label><input type="password" name="password" id="password" /><input type="submit" value="Log In" /><input type="hidden" name="submitted" /></form>';
if (isset($_POST['submitted']))
{
$pword = hash('sha256', $_POST['password']);
$query = "SELECT pword FROM users WHERE user = 'guest'";
$result = mysql_query($query);
$return = mysql_fetch_assoc($result);
if ($return['pword'] == $pword)
{
pageout();
}
else
{
echo 'You entered the wrong password, if you are not a member, please leave.';
}
}
}
function login_check($username, $uid)
{
}
function pageout()
{
echo('
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="" />
</head>
<body>
<div id="header">
<p>WOOT</P>
</div>
<div id="">
</div>
<div id="navigation">
</div>
<div id="footer">
</div>
</body>
</html>
');
}
?>
There is a single "Guest" password stored in a database, it accesses the database and checks the password entered by the user against the one stored in the database. I want to have it so after the form is submitted and the information is correct, on the same page the form disappears and the page appears. How do I do it? How do I get rid of the form to make room for the new page?
header(location ...) on success, or a page display conditional on log in settings
simply do
at the end of your form and at the php code do this
if(!isset($_POST['s'])){
?>
your form here
<?php
}
else //form handle
I would make structure look slightly different:
//First
if (!isset($_POST['submitted'])) {
//include your form only
} else {
//Check if user submitted correct password
//If password is correct
if ($return['pword'] == $pword) {
pageout();
//OR write pageout code on different page and call header("Location: Yourpage.php");
} else {
//Include form or inform user about password mismatch
}
}
edit. Also if you use header("Location:") function make sure you're not echoing or including anything that outputs data. This will cause Headers already sent error.