Cannot modify header information - headers already sent [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I know that this is well known problem but I've tried all solutions with no avail :(
Here is my code:
<?php
ob_start();
if (!empty($_POST)) { // if submit
$username = $_POST['username'];
$userpass = $_POST['userpass'];
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('ita4') or die($connection_error);
function login($username, $userpass) {
$sqlQuery = "SELECT COUNT(userid) FROM users WHERE name='$username' AND password='$userpass' AND admin='t'";
$runQuery = mysql_query($sqlQuery);
return (mysql_result($runQuery, 0) == 1) ? TRUE : FALSE;
}
if(login($username, $userpass)) {
setcookie("username", $username, time()+60*60*24*30);
$_COOKIE['username'] = $username;
echo "Me:".$_COOKIE['username'];
//echo "<script> location.replace('done.html'); </script>";
} else {
echo "<script> alert('Your input data is not found!'); </script>";
}
}
?>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv=content-type content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="upper">
Home • Login • About
</div>
<div id="container">
<div id="loginDiv">
<form action="login.php" onsubmit="return checkEmpty()" method="post" name="loginForm">
<table>
<tr>
<td style="width:100px">Name: </td>
<td>
<input name="username" id="username" type="text" style="width:250px"></td>
</tr>
<tr>
<td style="width:100px">Password: </td>
<td>
<input name="userpass" id="userpass" type="password" style="width:250px"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center"><input id="loginImg" type="image" src="images/loginButton.png"></td>
</tr>
</table>
</form>
</div>
</div>
<div id="lower">
<br><br><br><br><br>
<p style="text-align:center">COPYRIGHTS © 2013 • WWW.HISHAM.WS</p>
</div>
<script type="text/javascript">
function checkEmpty() {
var username = document.getElementById("username").value;
var userpass = document.getElementById("userpass").value;
if(username=="" || username==null) { alert("You've to enter your name!"); }
else if(userpass=="" || userpass==null) { alert("You've to enter a password!"); }
else { return true; }
return false;
}
</script>
</body>
</html>
Thanks in advance

So against my initial reaction to not help you, I decided to go ahead and build the database and table like you have. I created a new database named ita4 and added a table called users with four fields (userid, name, password, and admin). I added a user named josh with a password of josh and an admin setting of 't'. I then put your file into my local development environment and named it login.php. I then loaded up the page in my browser and entered josh for the username and josh for the password and it resulted in it displaying "Me:josh" at the top of the page and the login page still displaying below it. I get no errors.
If you aren't getting that far, then the error message may be because the database connection details are bad or your table doesn't have one of those fields. You do have a "or die(mysql_error()" after the database connect code.

The header needs to be the first thing in the document. Your code should look something like
<?php header("header information"); ?>
<html>
... Your HTML HERE ...
</html>
More information can be found in the PHP documentation here.

As far as i understand, you want to redirect the user to another page if a login occurs.
You could use javascript and/or meta redirections in order to do that.
This question might also help : How to redirect if user already logged in

You did not tell the line number that causes the notice. But I assume it is because you are doing setCookie().
You are already using ob_start() so that is good.
What I suggest is that you pay attention to that NO CHARACTERS should be at the start of the document, before the ob_start(). Look especially for any characters or even white spaces or enters (new lines), before you start <?php. Let <?php be the very first thing in your file.

Related

Simple login without encryption in PHP

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.

How to insert data only when I click submit button? [duplicate]

This question already has answers here:
Prevent duplicate record insertion on refresh without redirecting
(2 answers)
Prevent duplicate records to a table using PHP [duplicate]
(4 answers)
Closed 5 years ago.
I am facing some problem which you can easily solve this.
Form which I make work fine in first look because it store data in database when click submit button. I it also store data after I refresh Profile page. I think it will be solve if code execute only on click submit button but not on refresh the page. But don't know how to do that.
Profile.php
<?php
include('session.php');
include('frnd.php');
if(!isset($_SESSION['login_user'])){
header("location: index.php"); // Redirecting To Home Page
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<span><?php echo $error; ?></span>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout">Log Out</b>
</div><br>
<form action="" method="post">
<input type="text" name="frndIn" required><input type="submit" name="add">
</form>
</body>
</html>
Frnd.php
<?php
$error = ''; // Variable To Store Error Message
if (isset($_POST['add'])) {
if (empty($_POST['frndIn'])) {
$error = "Please enter username of your friend";
}
else
{
$frndIn = $_POST['frndIn'];
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "msg");
$query = "INSERT INTO friend (username, friend) values (?,?)";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $login_session, $frndIn);
if ($stmt->execute())
{
echo "New record inserted successfully";
}
else
{
$error = 'Error occur';
}
mysqli_close($conn); // Closing Connection
}
}
?>
Edit: I solve this problem by using POST/Redirect/GET method. This video (https://www.youtube.com/watch?v=bIkqNHyj25w) is very helpful.
After validation and successful insertion into the database in Frnd.php you need to redirect the user/client back to your Profile.php.

Deactivate Account not working

The code in deactivate_myaccount.php ran once then thereafter it has an error at the top - "Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\includes\includes\header-inc.php on line 2" . Also, this code is supposed to change the 'closed' field in the DB to yes so the person cannot log in, however that doesn't happen. I believe the sessions are playing up. When i re-log in with the same details the system allows me to log in and then when i select the 'deactivate account' button, it just says "You must be logged in to view this page!" and doesnt display the form for me to deactivate.
Deactivate_myaccount.php
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: sign_up.php");
} else {
$username = $_SESSION["user_login"];
}
include ("includes/header-inc.php");
?>
<h2> Deactivate Account: </h2>
<?php
//Taking the user back
$email = "";
if ($email) {
if(isset($_POST['no'])){
header ("Location: includes/profile_student.php");
}
if (isset($_POST['yes'])){
$deactivate_acc = mysqli_query("UPDATE users SET closed = 'yes' WHERE email = '$email'");
echo "You account has now been deactivated! Sorry to see you leaving MYASTONSPACE";
session_destroy();
}
}
else {
die ("You must be logged in to view this page!");
}
?>
<br/>
<center>
<form action="deactivate_myaccount.php" method = "POST" >
Are you sure you want to deactivate your account? <br>
<input type="submit" name = "no" value="No">
<input type="submit" name = "yes" value="Yes">
</form>
</center>
<?php
include ("includes/footer-inc.php")
?>
profile_student.php
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: sign_up.php");
} else {
$username = $_SESSION["user_login"];
}
include ("includes/connect.php");
?>
<!doctype html>
<html>
<head>
<title>Student Profile</title>
<link rel="stylesheet" type="text/css" href="css/profile_student.css">
</head>
<body>
<div class="logo" style="margin-left: 750px;"><img class="logo" src="images/logo.png"/></div>
<li>Log Out</li>
</div>
<hr>
<div class = "main_menu_buttons" style="margin-left: 25px;">
<p> Home | Undergraduate Information | Post-Grad Information | International Students | Contact Us </p>
<div class = "User_options">
<table>
<tr>
<td>
Personal information
<br>
Favourite Properties
<br>
Upload Picture:
<br>
Messages
<br>
Deactivate Account
</td>
</tr>
</table>
</div>
According to the error message, you have a call to session_start() in your includes/header-inc.php file. When you execute Deactivate_myaccount.php, this opens a new session and then includes the header. Because a session is already open, header-inc.php can't open it again and so this function call is ignored.
This is merely a notice and the cause should be fixed to comply with common coding styles, but it shouldn't affect the function of your application. I see someone else already helped you with the functional problem though.
If your email is always $email = '', and it's not matching anything, it's just doing an update:
UPDATE users SET closed = 'yes' WHERE email = ''
which may or may not update the relevant user.
If you decide to populate that ... please escape it; or use PDO / parameterised queries.

Login issue with PHP Session

Hi I have meet a problem here.
I need to log in an account here
but after i key in all the details and click Sign-In the page will redirect me back to the log in page. But actually the account is already logged in just that it cant redirect back to the Home Page after log in.
What problem is this? Im using Session.
and i put my session_start in connect.php(which is use to connect to database)
Below is The Code
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
//Code Refer to http://www.w3schools.com/php/func_http_setcookie.asp
if(isset($_SESSION['user'])!="")
{
header("Location: Home.php");
}
if(isset($_POST['btn-login']))
{
$username = mysql_real_escape_string($_POST['username']);
$upass = mysql_real_escape_string($_POST['password']);
$res=mysql_query("SELECT * FROM user WHERE u_username='$username'");
$row=mysql_fetch_array($res);
if($row['u_password']==md5($upass))
{
$_SESSION['user'] = $row['u_ID'];
header("Location: Home.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
?>
<?php
$year = time() + 31536000;
setcookie('rememberme', $_POST['username'], $year);
if ($_POST['rememberme'])
{
setcookie ('rememberme',$_POST['username'], $year);
}
else
{
setcookie(rememberme, $past);
}
}
?>
<!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>Login</title>
<link rel="stylesheet" href="Style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>AngelService</label><br/>
<p>Royal Borough of Greenwich</p>
</div>
</div>
<center> Home Page | View Post | Post A Service</center>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="username" placeholder="Your Username" required value="<?php
echo $_COOKIE['rememberme']; ?>"/>
</td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Your Password" required />
</td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td>
<input type="checkbox" name="rememberme" value="rememberme" style="font- size:6px;"> Remember Me<br>
</td>
</tr>
<tr>
<td>
Sign Up Here</td>
</tr>
</table>
</form>
</div>
</center>
<div id="footer">
<div id="center" align="center">
<br/>
<p>Angel Services | Royal Borough of Greenwich | Created By UOG Student: Kuai Boon Ting</p>
</div>
</div>
</body>
</html>
You are missing action="Your redirection page" in form tag i.e.,
<form method="post" action="forexample-Home.php">
.....
</form>
There are several things you can do to improve your code. For starters, you do not need to close and open PHP tags directly after each other, like you have
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
could just be
<?php error_reporting(0);
include_once 'connect.php';
The statement if(isset($_SESSION['user'])!="") doesn't do exactly what you think it does. isset($_SESSION['user']) returns a boolean (true/false), so checking whether or not a boolean is empty won't work. You can do if (!empty($_SESSION['user'])) {... to check if it's set and if it's empty or not. Check out the documentation for isset() and documentation for empty().
For your actual problem though: Note also that your header(); functions cannot be called after any output is made to the browser (any whitespace, HTML or PHP echo). This would appear as a PHP Warning, which will be reported should you put error_reporting(-1); instead of ignoring all errors (as you currently are doing with having error_reporting set to 0).
The other answer suggested using the HTML action-attribute for the form, but in case the login is invalid, it's best to have it sent to the same page, and only redirect should the login be valid. This is called "validate and redirect".
These pointers below are just to improve your code, and not necessarily the cause of your problem.
If you want to set a cookie, it has to be done before any and all output is sent to the browser (see this post), so in case the if($row['u_password']==md5($upass)) statement fails, and it enters the else-brackets, your cookie will not be set.
You should stop using mysql_* functions if you can. They are deprecated, and will be removed in the future. Switch over to mysqli_* or PDO instead. (Check out this post).
Usage of md5 hashing is not that secure. If you have PHP 5.5.0 or higher, you should perhaps look into usage of password_hash and password_verify
After every header("Location: ...."); you should always put a exit;, so that the code stops executing after it's redirecting. (Check out this post).

PHP Log-In indirection new page with the ID [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Just want to make sure that my PHP login page submitted with a new page that comes with my Login ID, for example "Welcome, XX", XX for your login username. So what should I do for my codes below (I use reCapture here):
<!DOCTYPE html>
<head>
<title>reCaptcha Log-in</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
<!-- your HTML content -->
<body>
<fieldset style="border:2px groove; border-color:blue; padding:15px 30px 15px;margin-right:5px;width:350px;height:400px">
<form method="post" action="recaptcha.php">
<p><b>User Name </b> <input type="text" name="username1" size="20px" maxlength="15"></p>
<p><b>Password </b> <input type="password" name="password1" size="20px" maxlength="15"></p>
<?php
require_once('recaptchalib.php');
$publickey = "6LfxlgcTAAAAALNywpDCYeKbH8ACc9dw6xaCZT-0"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<br/>
<div align="left"> <input type="submit" name="submit1" value=login></div>
</form>
<!-- more of your HTML content -->
</body>
</html>
<?php
session_start();
require_once("require_pro.php");
if($_SERVER["REQUEST_METHOD"]=="POST")
{
if(isset($_POST['submit1'])){
require_once('recaptchalib.php');
$privatekey = "6LfxlgcTAAAAACugkAYxfmc__38DtbI5MzDUHKx-";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ((!$resp->is_valid)&&(isset($_POST['username1']))) {
// What happens when the CAPTCHA was entered incorrectly
echo "<p>Sorry, Please enter the right reCaptcha code</p>";
$error = $resp->error;
} else {
$myusername=addslashes($_POST['username1']);
$mypassword=addslashes($_POST['password1']);
$sql=" SELECT * FROM user
WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count == 1)
{ $user1=$_POST['username1'];
echo "Login Successfully";
header("location:welcome.php?=$user1");
} else if(!empty($_POST['username1'])){
echo "<p><font color='black'>Login Information wrong, please try again</font></p>";
}
}
}
}
?>
<welcome.php> :
<!DOCTYPE html>
<html>
<head>
</head>
<body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
<!-- your HTML content -->
<body>
<fieldset style="border:2px groove; border-color:blue; padding:15px 30px 15px;margin-right:5px;width:350px;height:400px">
<?php
echo" Welcome !".??????
</body>
</html>
First, addslashes isn't the right function for preventing SQL injection. See Examples of SQL Injections through addslashes()?.
Second, mysql_* functions are deprecated and should not be used in new code. See the big red box at http://php.net/mysql_query. Use something like PDO with parameterized queries (which will also help you with SQL injection).
Third, you need to store something in the session so you know that they're logged in and which user they're logged in as. When the user successfully logs in, something like:
$_SESSION['username'] = $_POST['username1'];
Which will allow you to use it in subsequent pages.
since you are passing the username via the url,you use the $_GET[''] array but you code needs a little clean up ..you do this instead
if($count == 1)
{ $user1=$_POST['username1'];
echo "Login Successfully";
header("location:welcome.php?username=$user1");
}
to get the username,you do this
echo "Welcome $_GET['username']"; //make sure you clean up the variable

Categories