Header redirect not initializing PHP [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
I'm having a small issue with a header redirect on a login form. I have debugged the If & While statement and they both work fine, which surely can only be the header. I have tried redirecting it too numerous sites and pages but still nothing. Would really appreciate any help. Thanks!!!
<center>
<?php
include './index.php';// This is a login form
include './connection.php';// SQl connection page
include './session.php'; // Sessions page
error_reporting(E_ALL);
$mysqli = new mysqli ("c3433870.co.uk.mysql", "c3433870_co_uk", "BFUWGpn3", "c3433870_co_uk");
if($mysqli->connect_errno > 0) {
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
session_start();
if(isset($_POST['submit'])){
$stmt = $mysqli->prepare("SELECT username, password FROM users WHERE username=? AND password=? LIMIT 1");
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
while($stmt->fetch()) //fetching the contents of the row
{
$_SESSION['Login_sessions'] = true;
$_SESSION['login_user'] = $username;
header('Location: ./profile.php');
}
}
else {
echo "Wrong Username or Password!";
}
$stmt->close();
$stmt->free_result();
}
else
{
echo "Not Found";
}
$mysqli->close();
?>
</center>

Server headers are sent after the first echo. when you echo your center tag you thwart yourself.
Since the headers are already sent, you cannot change the location inside.
For this same reason, it is considered best practice not to close your php tags, as the php parser doesn't care either way.
I would remove the ?>

Related

session variables don't stop unauthorised access [duplicate]

This question already has answers here:
How to use store and use session variables across pages?
(8 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 2 years ago.
I am creating a login system and I have completed the authentication and a user can log in successfully. However, I have tried checking for the correct session variables on other pages but even if a user hasn't logged in they can still access these pages.
authenticate.php
<?php
//Start session.
session_start();
//Connect to MySQL
$servername = "localhost";
$username = "root";
$password = "Turtle#98!";
$dbname = "login";
$conn = mysqli_connect($servername, $username, $password, $dbname);
//Check the connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check if the data from the login form was submitted.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
exit('Please fill both the username and password fields!');
}
// Preparing the SQL statement will prevent SQL injection.
$stmt = mysqli_prepare($conn, ("SELECT password FROM users WHERE username=?"));
if ( !$stmt) {
die('mysqli error: ' .mysqli_error($conn));
}
//Bind input variables to prepared statement.
mysqli_stmt_bind_param($stmt, 's', $_POST['username']);
//Execute prepared statement.
mysqli_stmt_execute($stmt);
//Store the result to check if account exists.
mysqli_stmt_store_result($stmt);
//Make sure 'users' table is not empty.
if (mysqli_stmt_num_rows($stmt) > 0) {
//Bind password in table to stmt.
mysqli_stmt_bind_result($stmt, $password);
mysqli_stmt_fetch($stmt);
// Account exists so now to verify the password, as password stored is hashed.
if (password_verify($_POST['password'], $password)) {
// User logged in.
// Create sessions so we know the user is logged in.
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
//Redirect user to StudentEntry page after successful login.
header('Location: StudentEntry.php');
//echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
session variable check on other page
session_start();
// If the user is not logged in redirect to the login page.
if (!isset($_SESSION['loggedin'])) {
header('Location: UserLogin.html');
exit;
}
Thanks

When I try to redirect to new location in php I get "cannot modify header information-headers already bing sent error" [duplicate]

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.

Having problems with PHP [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
My PHP code won't verify the data to the database, it keeps returning saying Invalid login data, even though the data is correct.
This problem occurred after I switched over from using MySQL (which worked fine) to mysqli to be more secure.
The connection file data is sound, so I have no idea why the code keeps saying invalid login data.
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username=?
AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->fetch();
$res = $mysqli->query($stmt);
if (mysqli_num_rows($res) == 1) {
$row = $res->fetch_assoc();
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: forum.php");
exit();
} else{
echo "Invalid login information. Please return to previous page.";
exit();
}
}
Thank you.
The query and execute functions both execute your query. The query doesn't work with prepared statements.
Try:
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username=?
AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$row = $stmt->fetch_assoc();
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: forum.php");
exit();
} else{
echo "Invalid login information. Please return to previous page.";
exit();
}
It also is unclear if you are hashing already or not but user passwords should be hashed.
Also rather than telling the user to return to the previous page you could pass a parameter in a header function that displays the message for the user.
Something like:
header('location: http://domain.com/page.php?message=Your+username+or+password+were+incorrect+please+try+again');
in place of
echo "Invalid login information. Please return to previous page.";
and then on previous page check $_GET['message'].

PDO login script failing

Thanks to my last question im updating my site to PDO, i figured id start on my front pages and work my way deeper, and ive hit my first hurdle and fallen over, my login script.
login-exec.php EDITED
session_start();
include_once ('connect.php');
$Email = isset($_POST['Email']) ? $_POST['Email'] : "Email Never Sent";
$Password = isset($_POST['Password']) ? $_POST['Password'] : "Password Never Sent";
$stmt = $db->prepare("SELECT * FROM members WHERE Email = :Email AND Password = :Password");
$stmt->bindParam(":Email" , $Email );
$stmt->bindParam(":Password", $Password);
$stmt->execute();
$member = $stmt->fetch(PDO::FETCH_ASSOC);
if ($member)
{
$_SESSION['SESS_MEMBER_ID'] = $member['Member_ID'];
$_SESSION['SESS_POST_AS'] = $member['Post_As'];
$_SESSION['SESS_AUTH'] = $member['auth'];
session_write_close();
header('location: index.php');
exit();
} else {
header("location: ?p=login-failed");
exit();
}
connect.php
$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
EDIT: Now i get sent to the login-failed page, so does my problem now lie in what this page received from the form?
I know my $password is plain text, i was using md5 before and once i get this working ill implement some better protection
Put your connection attempt into a try/catch and then you will see the error
try {
$dbh = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Maybe the problem is if ($count > 1) and should be
if ($count > 0)
or
if ($count == 1)
if sql returns 1 row which I assume is what you want.
in addition to setting up a proper error reporting, also change
$count = $stmt->rowCount();
if ($count > 1)
to
$member = $stmt->fetch();
if ($member)
to make the code consistent
This will work, for you to check if a result was found or not:
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
//...
}
else
{
//...
}
Also note that you always have to put
session_start();
at the top of the page, otherwise it won't work.
$member doesn't really make sense here, where do you init it? $member should act as a row but in this case, $result would do the job for you.
I recommend taking a look at phpass for password protection.
You should also make logic around the POST, you can never be sure that anything is really posted unless you check. The Ternary Operator can be handy here:
$Password = isset($_POST['Password']) ? $_POST['Password'] : "Password Never Sent";
You should not use try catch around the whole page if it's only to catch a failed pdo connection, that should be a part of your connect file.
I'd avoid using "?p=login-failed", since it's easy to manipulate if you don't have any valid validations ongoing.
I personally don't like the bindParam approach, it makes more sense to me to execute an array of parameters onto the statement:
$stmt->execute(array(":Email"=>$Email, ":Password"=>$Password));
But your approach shouldn't be causing an error in this case.
Note that you don't need exit(); after header();
I hope that my comments help.
Try this:
if ($count > 0)
or
if ($count >= 1)
{
session_start();
$_SESSION['SESS_MEMBER_ID'] = $member['Member_ID'];
$_SESSION['SESS_POST_AS'] = $member['Post_As'];
$_SESSION['SESS_AUTH'] = $member['auth'];
session_write_close();
header('location: index.php');
exit();
}

PHP Login Form Doesn't Redirect [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have a login form for registered users, but it doesn't seem to want to redirect when proper email and password is entered. Not sure why I am getting back a 0 from my query? Am I missing something obvious?
<?php
session_start();
require_once('includes/db_connect.php');
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Define $email and $mypassword
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$qry="SELECT * FROM dontblame WHERE email='$email' and password='$password'";
$result = mysql_query($qry);
$count = mysql_num_rows($result);
if($count==1){
$_SESSION['user']=$email;
header('location: ../dashboard.php');
}
else {
$login_err = "<p>Your email or password is incorrect.</p>";
}
mysql_close();
}
?>
Edit: This is the error I am getting...
FROM dontblame WHERE email='XXXXXXX#gmail.com' and password='e6a52beca192a3fd67c8a0ea52cdea29162dd265'" resource(3) of type (mysql result)
try this:
$password = mysql_real_escape_string(hash("sha1",$_POST['password']));
then use this query:
$qry = "SELECT * FROM dontblame WHERE email='".$email."' and password='".$password."'";
But please dont use mysql_*. Use PDO or mysqli_* instead.
Use exit; or die(); after this line
if($count==1){
$_SESSION['user']=$email;
header('location: ../dashboard.php');
exit; or die();
}
if it not works tr this javascript code in place of header.
<?php
$url = "http://localhost/admin/dashboard.php";
echo '<script> window.location = "'.$url.'";</script>';
?>
Hope It helps..
Try to debug this program like this :
$password = mysql_real_escape_string($_POST['password']);
$qry="SELECT * FROM dontblame WHERE email='$email' and password='$password'";
var_dump($qry);
$result = mysql_query($qry);
var_dump($result);
make sure if the sql query is the same as you think .
or "header('location: ../dashboard.php'); " has some problem!
After redirect use die; or exit . and before header location close session writing. and try to use complete path in header(location:http://localhost/admin/dashboard.php') like this. as suggest by some of my frirnds as well.
why use exit or die?
header() won't automatically stop the script from excecuting.
Please try this:-
session_write_close();
header('Location: *where you want your form to go*');
die;
I would suggest you move to using mysqli instead because it is much more secure.
So here is a code snippet of your code implemented in mysqli.
<?php
$host = "localhost";
$username = "anon";
$password = "secret";
$schema = "your database name";
$mysqli = new mysqli($host, $username, $password, $schema);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT email FROM dontblame WHERE email=? and password=?";
if ($stmt = $mysqli->prepare($query)) {
/* bind parameters */
$stmt->bind_param("ss",$email,$pass);
$email = $_POST['email'];
$pass = $_POST['password'];
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($result_email);
/* fetch values */
if($stmt->fetch()) {
$_SESSION['email'] = $resutl_email;
$success = true;
} else {
$success = false;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if($success){
header('location: ../dashboard.php');
exit();
} else {
$login_err = "<p>Your email or password is incorrect.</p>";
exit();
}
?>
I also closed the connection before redirecting for the sake of safe programming. mysqli has a lot more benefit than using the regular mysql methods, preparing parameters for queries is one of those benefits.
also, please hash and salt your passwords. thats the least you can do to protect your users' personal information in case you get hacked.
try using this ..
$password=mysql_real_escape_string(sha1($_POST['password']));
next check $count value if it's till 0 then u have to use other method to convert password
or check for any spaces... Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

Categories