Having problems with PHP [closed] - php

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'].

Related

Username and Password Don't Match Output

I am in the process of creating a signup system using mysql and PHP. I have been able to connect the system to a database and it works for when the username and password entered are correct. However, when the username and password is not correct (i.e anytime when the username/password pair is not stored in the database), it just leads to a blank white page. Currently, my code has it so that when the username and password are not correct, it prints our "Invalid username of password". Please see the code below, any help is appreciated. Thank you in advance!
<?php
require_once 'source/session.php';
require_once 'source/db_connect.php';
if(isset($_POST['login-btn'])) {
$user = $_POST['user-name'];
$password = $_POST['user-pass'];
try {
$SQLQuery = "SELECT * FROM users WHERE username = :username";
$statement = $conn->prepare($SQLQuery);
$statement->execute(array(':username' => $user));
while($row = $statement->fetch()) {
$id = $row['id'];
$hashed_password = $row['password'];
$username = $row['username'];
if(password_verify($password, $hashed_password)) {
$_SESSION['id'] = $id;
$_SESSION['username'] = $username;
header('location: dashboard.php');
}
else {
echo "Error: Invalid username or password";
}
}
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
Well, currently your SQL query would return a set with 0 rows for a non-existent user, but that would not cause an error. It would just be an empty result set. Therefore it would not go through the while loop, it would just terminate without an error.
Your logic is leaving out the check to see whether $statement->rowCount() is zero.
To clarify in case this answer is confusing: You have 0 results if you enter a username that doesn't exist... then you do while(0) so you never get into that part of the code. No password check is done. And no error is thrown, so you never escape the try{} and get into the catch{} portion of the code. There is nothing returned here if the username turns up zero results from the database. You need to add another error in that case.

Header redirect not initializing PHP [duplicate]

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 ?>

Implementing a login on index page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to implement a login in my index page. The code runs through with no errors. My issue is after a user submits they are not being logged in. I appreciate everyone's comments, I am new to stackoverflow, not to coding, so I am still trying to grasp the community and how it works..
<?php
session_start()
if($_POST['submit']=='Login')
{
//Login form submitted??
$err = array();
//Hold errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
//Data escaping
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
//If kosher, Login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
//Session storing data
setcookie('tzRemember');
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
//Save errors in session
header("Location: login.php/");
exit;
}
you have many errors (for me) in your code. First, if you do not open the session_start (), sessions will never work. Second, the condition of "if" I do not think is correct because not have comparison method. I hope it can give you a hand
<?php
if($_POST['submit']=='Login')
{
//Login form submitted??
$err = array();
// Hold errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
//Data escaping
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if(!empty($row['usr']))
{
// If kosher, Login
session_start();
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
//Session storing data
setcookie('tzRemember');
}
else $err[]='Wrong username and/or password!';
}
if(!empty($err)){
session_start();
$_SESSION['msg']['login-err'] = implode('<br />',$err);
}
//Save errors in session
header("Location: login.php/");
exit;
}?>
Despite you not asking a distinct question and rather just asking for a code review (much better to do this on codereview) here is my opinion.
You has a couple of obvious issues,
Firstly like napster3world said you really need to start your session or nothing of much use will come of your error reporting.
Secondly you are wide open for all sort of malicious attacks this kinda undermining having a secure login.
While by no means exhaustive the following contains a couple of suggestions to help make it a little securer.
Detach your variables from the POST global - making it more obvious in the input is tainted.
Using a PDO database connection as this is much more secure method of connecting to your database than mysql_connect especially when using bound parameters to protect against sql injection (See the discussion here)
Code
The following is a quick ready that hopefully will point you in the right direction and improve some of you security.
// Start the session for storing your errors
session_start();
// Check that the button was clicked on the form
if (isset($post)) {
// Array for storing any errors
$err = array();
// Extract details from POST global
$_username = $_POST['username'];
$_password = $_POST['password'];
/*
You may want to consider some filtering here
*/
// Did the user fill in the username field?
if (empty($_username)) {
$err['username'] = "User name not provided";
}
// Did the user fill in the password field?
if (empty($_password)) {
$err['password'] = "Password not provided";
} else {
// Yes so hash it for the database check
$hashedPassword = md5($_password);
}
if (empty($err)) {
// Establish database connection
try {
$dsn = "mysql:host{$host};port={$port};dbname={$database}";
$connection = new PDO($dsn, $dbUsername, $dbPassword, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
} catch (PDOException $e) {
throw new \Exception("Unable to connect to the Database");
}
// Build SQL query and run on PDO connection
$sql = "SELECT id, usr FROM tz_members WHERE usr = :username AND pass = :hashedPassword";
try {
$stmt = $connection->prepare($sql);
// Bid your parameters to prevent sql injection
$stmt->bindParam(':username', $_username);
$stmt->bindParam(':hashedPassword', $hashedPassword);
$stmt->execute();
} catch (PDOException $e) {
throw new Exception("Error with executing query: {$e->getMessage()}");
}
// Fetch your results
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($row)) {
// Fill the session up with users details
$_SESSION['id'] = $row['id'];
$_SESSION['usr'] = $row['usr'];
// Head back to the login page - surely you wan to head to your protected page?
header("Location: login.php/");
return;
}
// Login failed
$err['login'] = "Wrong username and/or password!";
}
// Head back to the login page
$_SESSION['errors'] = $err;
header("Location: login.php/");
return;
}
Further reading
The following are a couple of links to tuts that might help a little.
This is a tut by the excellent Jeffrey Way on using the PDO Api
And this tut looks at more detailed ways to secure your forms.
I hope this is of help, and if anything makes you ask more questions.

php login script can't be loaded [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to php and i need help with this code, because i get "HTTP-fout 500 (Internal Server Error):" when i try to load it. Could someone post the whole good code. thanks.
<?php
session_start();
if(empty($_POST['username']) || empty($_POST['password'])) {
$notifications[] = 'Login failed! Please provide a username and password.';
}
if(count($notifications) == 0) {
try {
$dbh = new PDO('mysql:dbname=####;host=####',
'####', '####');
$sql = "SELECT username, verified FROM users WHERE username = :username AND
password = :password";
$sth = $dbh->prepare($sql);
$sth->execute(array(
':username' => $_POST['username'],
':password' => md5($_POST['password'])
));
$result = $sth->fetch(PDO::FETCH_ASSOC);
if($result) {
// Set session details and redirect user to members page
session_regenerate_id();
$_SESSION['username']=':username';
$_SESSION['password']=':password';
header('Location: index.php');
} else {
$notifications[] = "Username or Password incorrect.";
}
?>
You are missing a few curly braces. Not sure if this is the cause of your issue but try this out. The third and forth lines added set the error reporting to display on the current page instead of logging it to file / syslog / etc.
<?php
session_start();
ini_set('display_errors', true);
error_reporting(E_ALL);
if(empty($_POST['username']) || empty($_POST['password'])) {
$notifications[] = 'Login failed! Please provide a username and password.';
}
if(count($notifications) == 0) {
try {
$dbh = new PDO('mysql:dbname=####;host=####','####', '####');
$sql = "SELECT username, verified FROM users WHERE username = :username AND password = :password";
$sth = $dbh->prepare($sql);
$sth->execute(array(
':username' => $_POST['username'],
':password' => md5($_POST['password'])
));
$result = $sth->fetch(PDO::FETCH_ASSOC);
if($result) {
session_regenerate_id();
$_SESSION['username']=':username';
$_SESSION['password']=':password';
header('Location: index.php');
} else {
$notifications[] = "Username or Password incorrect.";
}
}
}
?>
Use the following in the top of your script, your page will now display all the information about what went wrong =)
With that information others can help you more easily, and it will help you to learn/find your mistakes
ini_set('display_errors', true);
error_reporting(-1);

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