This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I have an php login function. When I try to logged in with correct user, it show the error like this :
Warning: Cannot modify header information - headers already sent by (output started at /home/hapshou1/public_html/index.php:15) in /home/hapshou1/public_html/index.php on line 150
-
include "config.php";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
function antiinjection($data)
{
$filter_sql = mysql_real_escape_string(stripslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES))));
return $filter_sql;
}
$username = antiinjection($_POST['username']);
$pass = antiinjection($_POST['password']);
$login=mysql_query("SELECT username, password FROM user WHERE (username='$username' OR email='$username') AND password='$pass'");
$found=mysql_num_rows($login);
$r=mysql_fetch_array($login);
if
((!empty($username)) &&
(!empty($pass)))
{
if ($found > 0)
{
session_register("username");
session_register("password");
$_SESSION[username] = $r[username];
$_SESSION[password] = $r[password];
date_default_timezone_set("Asia/Jakarta");
$date_log = date("j-F-Y, G:i ");
mysql_query("update user set status='online', date_logged_in='$date_log' WHERE username='$_SESSION[username]'");
header('location:home');
}
else
{
echo '<div class="error_log">
<p>Wrong username or password. Please try again.</p>
</div>';
}
}
else
{
echo '
<div class="error_log">
<p>Username and password are required.</p>
</div>
';
}
}
What's wrong with my code?
Well, then look at what's on line 15.
The most likely scenario is that this statement caused the output:
$found=mysql_num_rows($login);
Which in turn is caused by the fact that your mysql_query returns false.
You could consider this to report any errors:
if (false === ($login=mysql_query("SELECT username, password FROM user WHERE (username='$username' OR email='$username') AND password='$pass'"))) {
die(mysql_error());
}
It's not advisable to use die() statements like this in a production environment, so consider using a logger instead
Btw, learn how to use PDO / mysqli; PDO has a mode in which all errors can be turned into exceptions which helped me find bugs much faster.
Put ob_start(); at top of the code and put ob_flush(); at end
Always put exit(); after header redirect
Enclose your code within
ob_start();
...
ob_flush();
The reason this error occurs is that some part of the body of the web page has been sent to the user already when a request is made to set a header value.
Also always put exit(); after header() statement so that rest of code on current page after the header() call doesn't get executed.
Exemple: header('Location: http://www.example.com/');
Naga, try this code:
session_start();
date_default_timezone_set("Asia/Jakarta");
include "config.php";
if(isset($_POST['username']) && isset($_POST['password']))
{
function antiinjection($data)
{
$filter_sql = mysql_real_escape_string(stripslashes(strip_tags($data)));
return $filter_sql;
}
$username = antiinjection($_POST['username']);
$pass = antiinjection($_POST['password']);
$login = mysql_query("SELECT username, password FROM user WHERE (username='$username' OR email='$username') AND password='$pass'");
$r = mysql_fetch_array($login);
if((!empty($username)) && (!empty($pass)) && is_array($r))
{
if (count($r) > 0)
{
$_SESSION['username'] = $r['username'];
$_SESSION['password'] = $r['password'];
$date_log = date("j-F-Y, G:i");
mysql_query("UPDATE user SET status = 'online', date_logged_in = '$date_log' WHERE username = '$_SESSION[username]'");
header('Location: http://domen.com/');
}
else
{
echo '<div class="error_log">
<p>Wrong username or password. Please try again.</p>
</div>';
}
}
else
{
echo '
<div class="error_log">
<p>Username and password are required.</p>
</div>
';
}
} else {
// do some action
}
Related
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 6 years ago.
<?php
include 'conn/condb.php';
if (isset($_POST['submit'])) {
if (isset($_POST['username'])and isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT username,password FROM login WHERE`username='$username'AND password='$password'");
if (!$query)
die("Database access failed: " . mysql_error());
$rows = mysql_num_rows($query);
if (($username == 'admin') && ($password == 'keystech')) {
$_SESSION['username'] = $username;
$_SESSION['sid'] = session_id();
header("location:index1.php");
} else {
echo "<script type='text/javascript'>alert('Please Enter Your Correct user name And Password..')</script>";
echo '<script type="text/javascript">window.location="index.html";
</script>';
}
}
}
?>
At some point, before reaching your header() instruction, some output has been made. Your formatting is messed up, but there may be a space at the first character of the page before
<?php
but that could just be bad pasting.
after your <?php starting just type this ob_start(); it will buffer empty spaces or any output before redirect.
Do few things
add ob_start just after the <?php
Place exit(); or die() after your header.
This is probably a duplicate but i am having this issue on login when running the following code
<?php
include('includes/functions.php');
if(isset($_POST['login'])) {
if(isset($_POST['username'])) {
if(isset($_POST['password'])) {
$username = $_POST['username'];
$query = mysql_query("SELECT * FROM users WHERE Username = '$username'") or die(mysql_error());
$user = mysql_fetch_array($query);
if(md5($_POST['password']) == $user['password']); {
echo 'Login successful';
$_SESSION['user'] = $user['FullName'];
header("Location:index.php");
}
} else {
echo "Please check your password!";
include('login.php');
}
} else {
echo "Please check your Username!";
include('login.php');
}
} else {
echo "Please check you filled out the login form!";
include('login.php');
}
?>
So when username and password are entered i get this output in browser
Login successful
Warning: Cannot modify header information - headers already sent by (output started at /home/site/public_html/admin/dologin.php:12) in /home/site/public_html/admin/dologin.php on line 14
All help will be greatly appreciated
if(md5($_POST['password']) == $user['password']); {
^
echo 'Login successful';
$_SESSION['user'] = $user['FullName'];
header("Location:index.php");
}
There are 2 issues. That ; inside the if statement should not be there, and then that echo should also go as already mentioned by other answers. Removing the echo should fix that error but your if is messed up because of ; which then causes the header not to work.
Side note: How can I prevent SQL injection in PHP?
There should be no output before the header(<..>) so you should get rid of it (remove lines with echo).
USe :-
<script>location.href - "index.php"; </script>
instead of
header("Location:index.php");
add ob_start(); at the beginning of file..and remove spaces before and after php tags..
I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();
So what I'm trying to do here is have my users login in.
This is the script I am using to do that.
I have just used an converter found here: https://wikis.oracle.com/display/mysql/Converting+to+MySQLi to convert my Mysql to mysqli because I am a beginner and had no idea how to do that.
Now when the users puts in an correct password and username.
It goed exactly how I want it and the user gets redirected to 'dashboard.php'
However, when user enters incorrect data, the users ends up on a black 'login.php' (which is the code I am showing here) instead of 'loginerror.php' which is what I want.
I hope some people here can help me out because I am pretty lost.
PS: Yes I know the passwords are in plain text right now but don't worry about that because I will fix that later.
<?php
session_start();
if(!$_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Please leave.<br /><br />";
echo "<a href='index'>Click to go back</a>";
exit();
}
if(($GLOBALS["___mysqli_ston"] = mysqli_connect('localhost', 'root', ''))) {
if(((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE users"))) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$zoekresultaat = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if($zoekresultaat = mysqli_affected_rows($GLOBALS["___mysqli_ston"]) > 0) {
$record = mysqli_fetch_assoc($zoekresultaat);
$zoekresultaat = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if($zoekresultaat = mysqli_affected_rows($GLOBALS["___mysqli_ston"]) > 0) {
$record = mysqli_fetch_assoc($zoekresultaat);
$_SESSION['login'] = true;
$_SESSION['username'] = $record['username'];
header('location: dashboard.php');
} else {
header('location: loginerror.php');
}
exit();
} else {
echo "<br /><br />Could not find Database";
}
} else {
echo "<br /><br />Could not connect to Database";
}
}
?>
You cannot redirect using the header method after anything has been outputted. In this case, you use Echo before your header redirection, so it will not work.
See this thread for reference : How to fix "Headers already sent" error in PHP
What you should do define redirection before outputting anything in your application, if it seems difficult, your application might need to be restructured.
Here are some alternatives if you don't want to do that, but they are bad practice :
HTML
<meta http-equiv="Location" content="http://example.com/">
Javascript
<script> location.replace("target.html"); </script>
Also as usual, defend yourself against MySQL injections : How can I prevent SQL injection in PHP?.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP session seemingly not working
I'm currently coding my own CMS for fun but when I use $_SESSION, it doesn't work. The session isn't saved...
There's my code:
<?php
include('header.php');
if (isset($_SESSION['logged_in']))
{
$link = 'profile.php';
$link_name = 'Profile';
}
else
{
$link = 'login.php';
$link_name = 'Login';
}
if (isset($_POST['action']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password = md5($password);
$user = mysql_query("SELECT * FROM users WHERE `username`='".$username."'");
if (mysql_num_rows($user) == 1)
{
while ($userinfo = mysql_fetch_array($user))
{
if ($userinfo['banned'] != true)
{
$_SESSION['user_id'] = $userinfo['id'];
$_SESSION['username'] = $userinfo['username'];
$_SESSION['logged_in'] = "true";
header('Location: index.php');
}
else
{
header('Location: login.php?error=banned');
}
}
}
else if (mysql_num_rows($user) == 0)
{
header('Location: login.php?error=not-found');
}
}
?>
In the code, I get the user information in my database then I check if the user isn't banned. If not, I set my $_SESSION[] and I redirect to the home...
You need session_start() at first.
you should call session_start() in the beginning of the script. make sure you call it on every page you need the access to session variables as well
Make sure session_start() is being called. Use Tamper Data to check the Headers for Sent and Received requests. Your looking for the Set-Cookie Header from the server and the Cookies Header from the client. This should contain your PHPSESSID. If you don't see this then your session is not started. Good Luck!