PHP Echo causes file to add html end comment dashes - php

When I'm trying to connect to a database in order to search for a username and password, it seems that running 'echo' command for any option kills the entire page and doesn't execute the rest of the code.
Here is my PHP file:
<html>
<body>
<?php
//setting variables for connecting to database
error_reporting(0);
$host = 'localhost';
$username = 'root';
$password = '';
$db = 'aquamandb';
date_default_timezone_set('America/Chicago');
//connecting to the database
$connect = new mysqli($host,$username, $password, $db) or die("Unable to connect");
//getting the username, user type, and password for sanitizing
$_US_username = $_GET['username'];
$_US_password = $_GET['password'];
//sanitize the variable to remove SQL statements that could drop the database potentially.
$username = mysql_real_escape_string($_US_username);
$password = mysql_real_escape_string($_US_password);
$sql = "SELECT * FROM user WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql);
//Send alert to page if there is not a match found between username password and user type
if(!$result)
{
die('Could not get data: ' . mysql_error());
}
else
{
$row = mysql_fetch_array($result);
if($row['type'] == 1)
{
echo '<form name = "auto" action = "../admin-dash.html" method = "POST">';
}
else if($row['type'] == 2)
{
echo '<form name = "auto" action = "../sigadmin-dash.html" method = "POST">';
} else
{
echo '<form name = "auto" action = "../sigusr-dash.html" method = "POST">';
}
}
?>
Note: I'm only posting a link to the PHP code because the file would never format correctly and would actually cause the same issue when I tried to use it on my website.
The issue is at Line 37. The echo statement stops, it doesn't create the form, and it just prints the rest of the elseif statements in regular text on the live web page.
If there are any clues as to what I am doing wrong (if I'm formatting something wrong) would be fantastic.

Not sure why you don't just put the form inside the html and call $_POST or $GET Inside php it would be way more simple that way. The error I see is right before line 37 where you forgot your(";") but even fixed it doesn't print the form i dont even think its processing your if but not sure. Also you should use prepared statements instead of mysql_real_escape_string , also your using mysqli to initially connect then you use mysql while escaping. .Try something like this:::::
<!doctype html>
<html>
<body>
<form action = "whatever.php method = "post">
<input type = "email" name = "email" />
<input type = "password" name = "password" />
<input type = "submit" name = "submit" value = "insert" />
</form>
<?php
// connect to the server
$conn = new mysqli('localhost', 'usename', 'password', 'database');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
} else {
echo "your connection was successful";
}
if($_POST && isset($_POST['submit'], $_POST['name'] )) {
$email = ( $_POST["email"]);
$pass = ($_POST["password"]);
$query = mysqli_prepare($conn, "SELECT pass FROM database
WHERE email = ? ");
mysqli_stmt_bind_param($query,'s', $email );
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $email);
if(mysqli_stmt_fetch($query)) {
echo "<br />";
echo "SUCCESS at query";
if (password_verify($input, $id)) {
echo "matching pass" . header("Location: inserh.php");
} else{
echo "not a match";
}
}
mysqli_stmt_close($query);
}
mysqli_close($conn);
Hope this helps Also this script verifies the hashed password using bcrypt!

There is a missing semi colon # the end of line 34:
$row = mysql_fetch_array($result);

$row = mysql_fetch_array($result) is missing a ; and is crashing your script

Related

PHP Login script only works with usernames known to mysql

This script should get some Variables of a submit form. Then it should check them from the DB and see if password and username match, if not it should send them back to the login page.
I already tried letting it check if the username exist via:
$this = "Select name from user where name = '".$_POST['name']"'";
$query = mysqli_query($conn,$this);
while( $row = mysqli_fetch_assoc($query)){
if (empty($row['name']){
do this;
}
}
But still got a blank page.
<?php
include "private/dbconnection.inc.php";
$conn = mysqli_connect($servername, $username, $password, $db);
if(!$conn){
die ("Verbindung fehlgeschlagen: ". mysqli_connect_error());
}
$selectpw = "SELECT * from user where name = '".$_POST['name']." ' ";
$pwcheck = mysqli_query($conn,$selectpw);
$selectname = "SELECT name from user where name = '".$_POST['name']."'";
$namecheck = mysqli_query($conn,$selectname);
while ( $row = mysqli_fetch_assoc($pwcheck)){
if ( $_POST['password'] === $row['password'] && $_POST['name'] === $row['name'] ){
header("Location:https://myhost.de/xxx/this/user.php");
}
else{
header("Location:https://myhost.de/xxxx/prototyp1/");
}
}
mysqli_close($conn);
?>
The script should check if the user is valid for login if hes not he should be send back to login. If hes valid he gets to another page.
But it only works with usernames the mysql knows with other usernames im stuck on the php page and it just shows a blank screen.
As Obsidian said, your code is potentially vulnerable to SQL injection, therefore it would be more suitable to use PDO. This can be achieve like so in the basic code example below.
<?php
include "private/dbconnection.inc.php";
try {
$db = new PDO('host=' . $server_name . ';dbname=' . $database . 'charset=utf-8;', $username, $password);
}
catch(PDOException $e)
{
throw $e; // Throw the PDOException if something failed
}
if(isset($_POST['username']) && isset($_POST['password']))
{
if(!empty($_POST['username'] && !empty($_POST['username'])
{
$query = $db->prepare('SELECT password FROM users WHERE username = ?');
$query->bindParam(1, trim($_POST['username']));
if($query->execute())
{
$password = $query->fetchColumn();
if($_POST['password'] == $password)
{
header('Location: https://myhost.de/xxx/this/user.php');
} else {
header('Location: https://myhost.de/xxxx/prototyp1/');
}
}
}
}
?>

echoing wrong else in php

Whenever I input wrong username, the resulting page gives the second else output. I want the first else to be displayed on the screen if a user types in wrong username and the second else to be displayed when someone tries to go in the login page directly from the url without inputting any name. And yes session_start(); has been declared on top of both the pages.
<?php
if (isset($_POST["submit"]))
{
$username = $_POST["username"];
$conn = new mysqli("localhost", "root", "", "test");
$result = $conn->query("select name from students where name = '$username'");
if ($result->num_rows > 0)
{
$_SESSION["username"] = $username;
echo "You are logged in. This is the welcome page. Welcome user: " . $username;
}
else
{
echo "Invalid username. Try again.";
}
$conn->close();
}
else
{
echo "Come through proper ways.";
}
?>
Possible issues
In general, you omitted some error management that could lead to unexpected behavior, which breaks the logic of your conditions.
You must check $_POST['username'], consider possible to receive $_POST['submit'] without an username (the web is full of surprises). The best way to differentiate missing username and bad username is to check it directly with isset() and empty() for instance.
You must check that the database connection succeeded to avoid exceptions with conn->connect_errno.
You must check if $result evaluates to false which would mean that there is a query error.
You may escape $username before inserting it into the request, I don't know how mysqli manages SQL injections.
Possible solution
<?php
if ( isset($_POST['submit']) && isset($_POST['username']) && !empty($_POST['username']) ) {
$conn = new mysqli("localhost", "root", "", "test");
$username = mysqli_real_escape_string($conn, $_POST["username"]);
// check connection
if ( $conn->connect_errno ){
die("Data access denied ([".$conn->connect_errno."] ".$conn->connect_error.")");
}
$result = $conn->query("select name from students where name = '$username'");
// check for query errors
if (!$result) {
die("Data access denied (invalid query)");
}
// ...
} else {
echo "Come through proper ways.";
}
try with following codes
<?php
if(isset($_POST["submit"] && array_filter($_POST) && $_POST['username']){
$conn = new mysqli("localhost", "root", "", "test") or die('Database Connection Failure ' . (($conn->connect_errno) ? $conn->connect_error : ''));
$username = mysqli_real_escape_string($conn, $_POST['username']);
$result = $conn->query("select name from students where name = '{$username}'");
if($result->num_rows > 0){
// success
$_SESSION["username"] = $username;
echo "You are logged in. This is the welcome page. Welcome user: " . $username;
}else{
echo "Invalid username. Try again.";
}
$conn->close();
}else{
echo "Come through proper ways.";
}

Issue with logging in with mySQL and PHP

Im trying to allow users that are on the database to log in if their credentials are present, problem is, whenever I enter details into the login screen, it will always return Invalid Login Credentials, regardless of whether or not the name/password is on the database.
Here is what I'm working with:
loginSubmit.php
<?php
//begin our session
session_start();
//Check the username and password have been submitted
if(!isset( $_POST['Username'], $_POST['Password']))
{
$message = 'Please enter a valid username and password';
}
else
{
//Enter the valid data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = sha1($password);
//Connect to the database
$SQLusername = "root";
$SQLpassword = "";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$query = "SELECT * FROM
customers WHERE name =
('$_POST[Username]' AND password = '$_POST[Password]')";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['username'] = $username;
}
else
{
echo "Invalid Login Credentials";
}
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
echo "Hello " . $username;
}
}
catch(Exception $e)
{
$message = 'We are unable to process your request. Please try again later"';
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
</body>
</html>
Login.php
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Here</h2>
<form action="loginSubmit.php" method="post">
<fieldset>
<p> <label for="Username">Username</label>
<input type="text" id="Username" name="Username" value="" maxlength="20" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" id="Password" name="Password" value="" maxlength="20" />
</p>
<p>
<input type="submit" value="Login" />
</p>
</fieldset>
</form>
</body>
</html>
AddUser
//Enter the valid data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = sha1($password);
//Connect to the database
$SQLusername = "root";
$SQLpassword = "";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$sql = "INSERT INTO
customers (name, password)
VALUES
('$_POST[Username]','$_POST[Password]')";
if(!mysql_query($sql, $dbhandle))
{
die('Error: ' . mysql_error());
}
//Unset the form token session variable
unset( $_SESSION['formToken'] );
echo "1 record added";
//close the connection
mysql_close($dbhandle);
}
catch (Exception $ex)
{
if($ex->getCode() == 23000)
{
$message = 'Username already exists';
}
else
{
$message = 'We are unable to process your request. Please try again later"';
}
It might be because of this, the way you have the brackets.
-Please see my notes about using prepared statements and password_hash() below.
SELECT * FROM customers
WHERE name = ('$_POST[Username]'
AND password = '$_POST[Password]')
Change it to:
SELECT * FROM customers
WHERE name = '$username'
AND password = '$password'
and for testing purposes, try removing
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
that could be affecting / rejecting characters. Make sure there is no white space also.
Also changing if($count == 1) to if($count > 0)
or replacing $count = mysql_num_rows($result); if($count == 1) { with if(mysql_num_rows($result) > 0){
Your password is not being hashed
After testing your Adduser code, I noticed is that your hashed password isn't being stored as a hash.
Change ('$_POST[Username]','$_POST[Password]') in your Adduser page to ('$username','$password').
I suggest you move to mysqli with prepared statements, or PDO with prepared statements, they're much safer.
As it stands, your present code is open to SQL injection.
Here is a good site using PDO with prepared statements and password_hash().
http://daveismyname.com/login-and-registration-system-with-php-bp
See also:
CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Try this mate
$query = "select * from customer where name = '" .$username ."' and password = '" .$password ."'";
//use the SANITIZED data
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row) {
$_SESSION['name'] = $row['name'];
$_SESSION['password'] = $row['password'];
}
else { //not found
header('Location: go back.php?error=2');
}
echo "Hello " . $username;

PHP Login Database Issues

I am new to PHP so please be patient with me! I am trying to set up a user login page but every time I click log in it won't recognize the data that is already in the database. I currently have 7 sections in a the table but only taking data from 2 sections. I am unsure where abouts I am going wrong could be the php or the MySQL queries Would someone help me please!
<?PHP
$email = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = $_POST['Email'];
$pword = $_POST['Password'];
$email = htmlspecialchars($email);
$pword = htmlspecialchars($pword);
$e_mail = "root";
$pass_word = "";
$database = "the_travel_cult";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $e_mail, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM user_login WHERE Email='$email' AND Password='$pword'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//if(!$result) die ('Unable to run query:'.mysql_error());
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['user_login'] = "1";
header ("Location: SignedIn.php");
}
else {
session_start();
$_SESSION['user_login'] = "";
//$errorMessage = "Not Registered";
header ("Location: Register.php");
}
}
else {
$errorMessage = "Error logging on";
}
mysql_close($db_handle);
}
else {
$errorMessage = "Error logging on";
}
}
?>
<FORM NAME ="form1" METHOD ="POST" ACTION ="HomePage.php">
<form method=post action=”login.php”>
<p><center><strong>Email Addres:</strong></center><br>
<center><input type=”text” name= 'email' value="<?PHP print $email;?>" size=40 maxlength=100></center>
<p><center><strong>Password</strong></center><br>
<center><input type=”text” name= 'password' value="<?PHP print $pword;?>" size=40 maxlength=20></center>
<P align = center>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
<form action="Register.php"> <input type="submit" value="Sign Up"> </form>
First off, congratulations on starting to code. I hope you're having fun!
It looks like you might have a case of "case sensitivity" going on. I noticed that you have the following code at the top:
$email = $_POST['Email'];
$pword = $_POST['Password'];
However, in your HTML, you're actually passing those variables named in all lowercase. Try changing either the code at the top to:
$email = $_POST['email'];
$pword = $_POST['password'];
Or the name of your inputs to "Email" and "Password" (again, notice the uppercase first letter). An easy way to check if the problem is here (vs something in the query) is to
var_dump($_POST);
to see what exactly your script is getting from the form submission.
For more information, see PHP's http://php.net/manual/en/language.variables.basics.php or check out a related post to see how you can make your own case insensitivity check though be warned: it's more work. PHP: Case-insensitive parameters

Password Change in Php, Php is returning blank

I am trying to create a password change page for a website I am attempting to make. However when the user enters in the information to the form it sends me to a blank page. In other words my php code is not even executing and I am not sure why. I have tried it a few different ways but I am not entirely sure whats going on. This is my first time making a settings page or website in general so maybe its a simple mistake or I'm going about it all wrong. Here is my php code.
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$db_server = "server";
$db_username = "name";
$db_password = "pass";
$con = mysql_connect($db_server, $db_username, $db_password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$database = "Account_Holder";
$er = mysql_select_db($db_username);
if (!$er) {
print ("Error - Could not select the database");
exit;
}
$username = $_P0ST['username'];
$cur_password = $_POST['cur_password'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
// Check for an existing password.
if (isset($_POST['cur_password']))
{
$pass = FALSE;
print('<p>You forgot to enter your existing password!</p>');
}
else {
$pass = escape_data($_POST['cur_password']);
}
// Check for a password and match against the confirmed password.
if (empty($_POST['password']))
{
$newpass = FALSE;
print('<p>You forgot to enter your new password!</p>');
}
else
{
if ($_POST['password'] == $_POST['password2']) {
$newpass = escape_data($_POST['password']);
}
else
{
$newpass = FALSE;
$message .= '<p>Your new password did not match the confirmed new password!</p>';
}
if ($pass && $newpass) { // If checking passes
$query = "SELECT * FROM Account_Holder WHERE password='$pass')";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if ($num == 1) {
$row = mysql_fetch_array($result);
// Make the query.
$query = ("UPDATE Account_Holder SET password='$newpass' WHERE username=$username");
$result = mysql_query($query); // Run the query.
if (mysql_affected_rows() == 1) { // If it ran OK.
echo '<p><b>Your password has been changed.</b></p>';
}
else
{ // If query failed.
print('<p>Your password was not changed.</p><p>' . mysql_error() . '</p>');
}
} else
{
print('<p>Your username and password did not match any in the database.</p>');
}
}
else
{
print('<p>Please try again.</p>');
}
}
?>
</body>
</html>
<!--
I also did it this way and all the validations work and it says the password was updated but it does not change in the database. Is something wrong with my sql?
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Change Password Confrim</title>
</head>
<body>
<?php
$db_server = "server";
$db_username = "name";
$db_password = "pass";
$con = mysql_connect($db_server, $db_username, $db_password);if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$database = "Account_Holder";
$er = mysql_select_db($db_username);
if (!$er)
{
print ("Error - Could not select the database");
exit;
}
//include "include/session.php";
// check the login details of the user and stop execution if not logged in
//require "check.php";
//////////Collect the form data ////////////////////
$username =$_P0ST['username'];
$todo=$_POST['todo'];
$password=$_POST['password'];
$password2=$_POST['password2'];
/////////////////////////
if(isset($todo) and $todo=="change-password"){
$password = mysql_real_escape_string($password);
$password2 = mysql_real_escape_string($password2);
//Setting flags for checking
$status = "OK";
$msg="";
//Checking to see if password is at least 3 char max 8
if ( strlen($password) < 3 or strlen($password) > 8 )
{
$msg=$msg."Password must be more than 3 char legth and maximum 8 char lenght<br/>";
$status= "NOTOK";
}
//Checking to see if both passwords match
if ( $password <> $password2 )
{
$msg=$msg."Both passwords are not matching<br/>";
$status= "NOTOK";
}
if($status<>"OK")
{
echo "<font face='Verdana' size='2' color=red>$msg</font><br><center><input type='button' value='Retry' onClick='history.go(-1)'></center>";
}
else
{ // if all validations are passed.
if(mysql_query("UPDATE Account_Holder SET password='$password' WHERE username='$username'"))
{
echo "<font face='Verdana' size='2' ><center>Thanks <br> Your password changed successfully.</font></center>";
}
else
{
echo "<font face='Verdana' size='2' color=red><center>Sorry <br> Failed to change password.</font></center>";
}
}
}
//require "bottom.php";
?>
<center>
<br><br><a href='Settings.html'>Settings Page</a></center>
</body>
</html>
I wish I could just leave a comment. But no.
You have a lot of errors in your code such as this
$username = $_P0ST['username'];
Im guessing error reporting is turned off on the page, so you don't see the syntax errors, and you just get a blank page.
Turn on errors. This may work.
error_reporting(E_ALL);
A few comments:
$er = mysql_select_db($db_username);
This is the wrong variable.
$username = $_P0ST['username'];
A zero instead of a letter O.
$query = "SELECT * FROM Account_Holder WHERE password='$pass')";
and
$query = ("UPDATE Account_Holder SET password='$newpass' WHERE username=$username");
Can you say "SQL injection"? Also, missing quotes around the username value.
As mentioned by Adam Meyer above, you appear to have error reporting off. Either that, or you have output buffering somewhere and yet another syntax error in there.

Categories