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.
Dear friends i am having strange error which i am unable to solve, need your help. The code is working fine when login is incorrect and when login is correct it still creates a session but do not redirect to index.php instead it throws an error of "Cannot modify header information - headers already sent by...". I already search for similar posts but was not able to solve the issue
here is the code
<?php include ("scripts/connection.php");
session_start();
$myusername = $_POST["myusername"];
$myusername = preg_replace('/[^a-zA-Z0-9\']/','',$_POST['myusername']);
$mypassword = $_POST["mypassword"];
$mypassword = preg_replace('/[^a-zA-Z0-9\']/','',$_POST['mypassword']);
$LoginQuery = "SELECT * FROM users WHERE username='$myusername' and password='$mypassword'";
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Admin Login</title>
</head>
<body>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr><form name="form1" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<?php if($_SERVER["REQUEST_METHOD"] == "POST")
{ $result = $mysql->query($LoginQuery);
if($result->num_rows ==1)
{
$_SESSION['login_user']=$myusername;
header("Location:index.php");
exit();
}
else
{
echo '<tr><td width="78"> </td><td width="6"></td><td width="294"><font style="color:#f00; font-weight:bold;">Invalid!</font></td></tr>';
}
}
?>
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</body>
</html>
Friends can u find what i did wrong and help me correct it please.
Thank you

You have to understand HTTP:
A redirct is realized by the HTTP-Header.
In HTTP the header is send, before any output (like the webpage itself)
So you are trying to send a Redirect-Header after you send payload.
This is not possible.
In short, never use header() after you print out something on the page.

you should use function header before writing any other text

Related

Why does my php login script work in Chrome, but not in FireFox or Edge?

I'm working on a php login based on mysql table. It's all working fine w/in Chrome, however in both Firefox and Edge, when I type a username and password I am just brought back to the login page. (with correct OR incorrect credentials)
Here is my php code..
<?php session_start();
if(isset($_POST['login'])) {
$uname = $_POST['uname'];
$pass = $_POST['pass'];
$sel_user = $con->prepare("SELECT id, username, pass, gid FROM employees WHERE gid!=4 AND username=?");
$sel_user->execute([$uname]);
$check_user = $sel_user->fetch();
if(count($check_user)>0 && password_verify($pass, $check_user['pass'])) {
$_SESSION['username']=$check_user['username'];
header("Location: xadmin.php" );
exit;
}
else {
echo "<script>alert('Email or password is not correct')</script>";
}};?>
Here is the html form..
<form action="login.php" method="post">
<table width="100%" border="0">
<tbody>
<tr>
<td bgcolor="#3B3B3B" height ="35" class="BodyTxtB" align="center">Administrator Login</td></tr>
<tr height="20"><td></td></tr>
<tr>
<td class="BodyTxtB" align="center">Username</td>
</tr>
<tr>
<td class="BodyTxtB" align="center"><input type="text" class="BodyTxtBC" name="uname" required="required"/></td>
</tr>
<tr height="20"><td></td></tr>
<tr>
<td class="BodyTxtB" align="center">Password</td>
</tr>
<tr>
<td class="BodyTxtB" align="center"><input type="password" class="BodyTxtBC" name="pass" required="required"/></td>
</tr>
<tr height="20"><td></td></tr>
<tr height="35"><td align="center"><input type="image" src="images/btn_login.jpg" name="login" value="Login"/></td></tr>
<tr height="20"><td></td></tr>
</tbody>
</table>
</form>
Here is the validation from xadmin.php
<?php session_start();
if (!isset($_SESSION['username']))
{
header("Location: login.php?e=access_denied");
exit();
}
?>
Does anyone know what could be causing the issue?
UPDATE: Although not relevant to the original issue or provided answers, I have updated this post to fix the issue's of mysql injection and password encryption
Firefox/Edge don't pass through the name of <input type="image" ... />
If you do a print_r($_POST) and submit the form with Firefox you'll get:
Array
(
[login_x] => 0
[login_y] => 0
)
Do the same thing with Chrome, however:
Array
(
[login_x] => 8
[login_y] => 8
[login] => Login
)
... and there you have it.
You could pass through login as a hidden form field:
<input type="image" src="images/btn_login.jpg" />
<input type="hidden" name="login" value="Login" />

php require path on Bluehost [duplicate]

I have this little code, which in fact is a login script which check if the register is on, and show it after the login button:
<?php
include("../inc/db.php");
if(isset($_POST['user']) && isset($_POST['pass']))
{
$password = $_POST['pass'];
$username = $_POST['user'];
$sql = "SELECT * FROM `users` WHERE `user` = '".$username."' AND `password` = '".$password."'";
$rez = $pdo->query($sql);
if($rez->fetchColumn() > 0)
{
...
}
else {echo '<p align="center">...</p>';}
}
else { echo '<p align="center">...</p>'; }
}
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="login">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="user" type="text" id="user"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="pass" type="password" id="pass"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
<?php $sql = "SELECT setare FROM setari WHERE nume_setare = 'OPEN_REG'";
$openreg = $pdo->query($sql)->fetch();
if($openreg['setare'] == 1)
{
?>
<tr>
<td> </td>
<td> </td>
<td>Inregistrare</td>
</tr><?php } ?>
</table>
</td>
</form>
</tr>
</table>
My problem is this line:
include("../inc/db.php");
Warning: include(E:/wamp/www//inc/db.php): failed to open stream: No such file or directory in E:\wamp\www\proiect1-test\scripts\login.php on line 3
Warning: include(): Failed opening '../inc/db.php' for inclusion (include_path='.;C:\php\pear') in E:\wamp\www\proiect1-test\scripts\login.php on line 3
and i can't figure it out where i'm wrong. The path is correct, and if i hit the login button, it works.If i hit login button with an inccorect combination of username and password, the warning disappear. However, it doesn't include that when i open it for the first time. This login file is included in the index of the site.
Your path to that file is obviously incorrect. This commonly happens when you use a relative path to a file and then start placing files in different directories. You should use the full system path to the file to avoid this issue:
include("/path/from/root/to/inc/db.php");
A common thing to do is define a variable or constant that defines the root path to your web files. That way if it ever changes (i.e. you change hosts) you only need to change it in one place.
In your config file:
define('ROOT_PATH', '/path/from/root/to/');
In your PHP files;
include(ROOT_PATH . "inc/db.php");

php include error not findind the path

I have this little code, which in fact is a login script which check if the register is on, and show it after the login button:
<?php
include("../inc/db.php");
if(isset($_POST['user']) && isset($_POST['pass']))
{
$password = $_POST['pass'];
$username = $_POST['user'];
$sql = "SELECT * FROM `users` WHERE `user` = '".$username."' AND `password` = '".$password."'";
$rez = $pdo->query($sql);
if($rez->fetchColumn() > 0)
{
...
}
else {echo '<p align="center">...</p>';}
}
else { echo '<p align="center">...</p>'; }
}
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="login">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="user" type="text" id="user"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="pass" type="password" id="pass"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
<?php $sql = "SELECT setare FROM setari WHERE nume_setare = 'OPEN_REG'";
$openreg = $pdo->query($sql)->fetch();
if($openreg['setare'] == 1)
{
?>
<tr>
<td> </td>
<td> </td>
<td>Inregistrare</td>
</tr><?php } ?>
</table>
</td>
</form>
</tr>
</table>
My problem is this line:
include("../inc/db.php");
Warning: include(E:/wamp/www//inc/db.php): failed to open stream: No such file or directory in E:\wamp\www\proiect1-test\scripts\login.php on line 3
Warning: include(): Failed opening '../inc/db.php' for inclusion (include_path='.;C:\php\pear') in E:\wamp\www\proiect1-test\scripts\login.php on line 3
and i can't figure it out where i'm wrong. The path is correct, and if i hit the login button, it works.If i hit login button with an inccorect combination of username and password, the warning disappear. However, it doesn't include that when i open it for the first time. This login file is included in the index of the site.
Your path to that file is obviously incorrect. This commonly happens when you use a relative path to a file and then start placing files in different directories. You should use the full system path to the file to avoid this issue:
include("/path/from/root/to/inc/db.php");
A common thing to do is define a variable or constant that defines the root path to your web files. That way if it ever changes (i.e. you change hosts) you only need to change it in one place.
In your config file:
define('ROOT_PATH', '/path/from/root/to/');
In your PHP files;
include(ROOT_PATH . "inc/db.php");

Php login form problems

I am having problems with this, when i login with valid data, the page just refreshes (i am assuming that the if statement in protectedstuff.php failed). When i used the deprecated method to register the session and check if it exists, it worked if(!session_is_registered(myusername)).
Oh and also I am able to see a cookie was created "PHPSESSID".
what am I doing wrong?
login.php ->
<?php
if($_POST){
$errorLogin="Wrong Username or Password";
$link = mysqli_connect('localhost', 'root', '', 'mydb')
or die('Could not connect: ' . mysqli_error($link));
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$sql_query="SELECT * FROM users WHERE username='$myusername' and password='$mypassword';";
$result = mysqli_query($link, $sql_query) or die('query failed'. mysqli_error($link));
$row = mysqli_fetch_assoc($result);
$dbUserName= $row['username'];
$dbPassword= $row['password'];
// Mysql_num_row is counting table row
// If result matched $myusername and $mypassword,
if($myusername==$dbUserName && $mypassword==$dbPassword){
// Register $myusername, and redirect to file "login_success.php"
//session_register("myusername"); <- deprecated
$_SESSION['myusername']=$myusername;
header("location:protectedstuff.php");
}else {
echo $errorLogin;
}
}
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
the usernames and passwords are already in the database.
This is my protectedstuff.php
<?php
session_start();
if(!isset($_SESSION['myusername']))
{
header("location:login.php");
}
else{
?>
<html>
<body>
Login Successful
</body>
</html>
<?php
}
?>
Thank you!
I don't see a session_start() above your $_POST block. You must call that on every page BEFORE any output is sent

move_uploaded_file is giving a error

this is my form
<form action="test.php" method="post" name="myform">
<table width="500" border="0">
<tr>
<td width="369" colspan="3">Admin's Area </td>
<td width="121"><?php echo $_SESSION['name'];?></td>
</tr>
<tr>
<td colspan="3">sponseres list </td>
<td>+Add new Sponser</td>
</tr>
<tr>
<td colspan="3"><?php echo $sponsere_list; ?></td>
<td> </td>
</tr>
<tr>
<td align="center" colspan="4"> <a name="sponserForm" id="sponserForm"></a> Add New Sponser Form</td>
</tr>
<tr>
<td align="left">Sponser name</td>
<td align="left"><input type="text" name="spname" id="spname" tabindex="1" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="left">Image</td>
<td align="left"><input type="file" name="fileToUpload" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="left">Add this</td>
<td align="left"><input type="submit" name="sumit" id="sumit" value="Submit" tabindex="3" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="center" colspan="4"> </td>
</tr>
</table>
</form>
and this is the php code to retrive it
<?php
if(isset($_POST['spname'])){
$spname=mysql_real_escape_string($_POST['spname']);
$user_query = "INSERT INTO `sponsers` (`spname`)
VALUES ('{$spname}')
";
$sql=mysql_query($user_query)or die (mysql_error());
$spic= mysql_insert_id();
$newname="$spic.jpg";
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],"../sponsers/$newname")or die (mysql_error());
}
?>
when i try to upload a image it gives me this warning message
Notice: Undefined index: fileToUpload in J:\xampp\htdocs\srimag\admin\test.php on line 3
so i tried to echo the fileToUpload value by using $_POST['fileToUpload'] it show the values without errors so can't figure out the error.
so please help me on this :-(
Thanks.
Your main problem is you are missing the appropriate enctype attribute on your form
<form ... enctype="multipart/form-data">
Make sure you read this section of the manual carefully - http://php.net/manual/en/features.file-upload.php
Your issue is mentioned on the first page
Note:
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
You need enctype="multipart/form-data" in your form to upload images, also it would be a good idea to check if user even uploads an image and specificity naming a file .jpg will not work, images will be treated as corrupt when outputting if ther not jpegs, not to mention people uploading php files.
You also need to make some other checks on validity, upload security is not something that should be overlooked, else you have one of thos awful phone home / botnet malware scripts injecting code into all your scripts:
<?php
if(isset($_POST['spname'])){
$spname=mysql_real_escape_string($_POST['spname']);
$user_query = "INSERT INTO `sponsers` (`spname`)
VALUES ('{$spname}')";
$sql=mysql_query($user_query)or die (mysql_error());
$spic= mysql_insert_id();
if(isset($_FILES["fileToUpload"]["tmp_name"]) && $_FILES["fileToUpload"]["error"] ==0){
$name = basename($_FILES["fileToUpload"]['name']);
$ext = end(explode('.', $name));
$newname = $spic.".".$ext;
$info = getimagesize($_FILES["fileToUpload"]['tmp_name']);
$allowed = array('image/png','image/jpg','image/gif');
if($info[0]>0 && $info[1] > 0 && in_array($info['mime'],$allowed)){
move_uploaded_file($_FILES["fileToUpload"]['tmp_name'], "../sponsers/$newname");
//done upload
}else{
//Not allowed, perhap notify user
}
}
}
?>
include this in form tag
enctype="multipart/form-data"
You should add this in your form
<form action="test.php" method="post" name="myform" enctype="multipart/form-data">

Categories