Fix "Error 500: Page not working" error PHP - php

This is an assignment for a PHP course I'm taking. We created a database in mySQL, and we are working on making a website to view/insert/update/delete information in the database. Right now, I'm getting a "Page not working" error while running an if statement to see if an ID # already exists in the database.
I have tried commenting out parts of my code to determine where the problem is, and I'm pretty sure it's an issue with the code underneath my "database connections" comment. This is a beginner's class, and I'm following my professor's walkthrough video for the assignment, but I can't figure out what I'm doing wrong.
<?php
session_start(); //starts the session
//Set all variables
$uniqueid = $_POST["uniqueid"];
$breed = $_POST["breed"];
$color = $_POST["color"];
$furlength = $_POST["furlength"];
$dogweight = $_POST["dogweight"];
//test if variables come in correctly
//echo "variables: " . $uniqueid . $breed . $color . $furlength . $dogweight;
//test if all fields filled
if (($uniqueid == "") || ($breed == "") || ($color == "") || ($furlength == "") || ($dogweight == "")) {
$_SESSION["errormessage"] = "You must complete all fields!"; //error message if any field is empty
header("Location:insert.php");
exit;
}
else { //if all fields filled
$_SESSION["errormessage"] = ""; //no error message
}
//database connections -- THIS IS PROBABLY WHERE THE ISSUE IS
include("includs/openDBConn.php"); //include the database
//check that # adding isn't already part of database
$sql="SELECT UniqueID FROM Dogs WHERE UniqueID=".$uniqueid;
$result=$conn->query($sql);
if($result->$num_rows > 0) { //make sure database loads the rows
echo("num rows= ".$result->$num_rows); //echo the number of rows
}
else { //if there are no rows
echo("No data found"); //give error message
}
?>
On a different page, there are fields for me to type in UniqueID, breed, color, etc. This page is supposed to check that all fields are filled in (that part works), and then check if there is already a row with the UniqueID that I typed in. If there is, it's supposed to echo the number of rows it found with that UniqueID (which is supposed to be 1).
I'm very new to PHP, so if I'm missing any essential information please let me know. I appreciate any advice!

Your code is full of vulnerabilities. It is prone to sql injection, xss attack, csrf, html injection.
I have re-written it to avoid most of this issues.
1.) Sql Injection is now mitigated using prepare queries
2.) Html injection is mitigated using intval for integer variables and strip_tags for strings. you can read more about data validations and sanitization in php to see more options available
3.) xss attack has been mitigated via htmlentities(). you can also use htmlspecialchars(). Read more about all this things
see better secured codes below
Please put your database credentials where possible
I do not know whether this your unique id is a string or integer(number)
// if UniqueID is integer or number use i parameter
$stmt->bind_param("i", $UniqueID);
// if UniqueID is a string use s parameter
$stmt->bind_param("s", $UniqueID);
here is the code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ur dbname";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection to db failed");
}
session_start(); //starts the session
// ensure that the Id is integer using intval
//$uniqueid = intval($_POST["uniqueid"]);
// sanitize your data against xss and html injection
$uniqueid = strip_tags($_POST["uniqueid"]);
$breed = strip_tags($_POST["breed"]);
$color = strip_tags($_POST["color"]);
$furlength = strip_tags($_POST["furlength"]);
$dogweight = strip_tags($_POST["dogweight"]);
//test if all fields filled
if (($uniqueid == "") || ($breed == "") || ($color == "") || ($furlength == "") || ($dogweight == "")) {
$_SESSION["errormessage"] = "You must complete all fields!"; //error message if any field is empty
header("Location:insert.php");
exit();
}
//Avoid sql injection using prepared statement
$stmt = $connect->prepare("SELECT UniqueID FROM Dogs WHERE UniqueID = ?");
// UniqueID is integer or number use i parameter
$stmt->bind_param("i", $UniqueID);
// if UniqueID is a string use s parameter
//$stmt->bind_param("s", $UniqueID);
$stmt->execute();
$stmt -> store_result();
$stmt -> bind_result($UniqueID);
if ($stmt->num_rows >= "1") {
while ($stmt -> fetch()) {
// ensure that xss attack is not possible using htmlentities
// fetch UniqueID
echo "your UniqueID: .htmlentities($UniqueID). <br>";
}
}else{
echo "No data found";
}
$stmt->close();
$connect->close();
?>

you have a syntax error on $result->$num_rows, that should be $result->num_rows without the second dollar sign,
and of course, your example here has security vulnerabilities that you also need to address, but that is not your question

Related

password_verify Always Returns False, even with proper variables used

My webpage starts with a login page, like many, and if the user has no account they can sign up. My sign up works and the users password they input is successfully hashed with password_hash and sent to the database. However, when trying to login, password_verify always returns false. Thinking I made a silly error when I originally made the hashed password, I echoed the variable I was using as the second parameter in password_verify. However, it was an exact match to the hash in the database. What could be the issue?? Shortened code is available below for both creating the password during sign up and checking the password while logging in.
CREATING HASHED PASSWORD
<?php
session_start();
require('db_credentials.php');
$inputUsername = $_POST['createUsername'] ? $_POST['createUsername'] : null;
$inputPassword = $_POST['createPassword'] ? $_POST['createPassword'] : null;
$vPassword = $_POST['verifyPassword'] ? $_POST['verifyPassword'] : null;
//protect database from corrupt user input
$inputUsername = $mysqli->real_escape_string($inputUsername);
$inputPassword = $mysqli->real_escape_string($inputPassword);
$vPassword = $mysqli->real_escape_string($vPassword);
//create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
$protectedPassword = password_hash($inputPassword, PASSWORD_DEFAULT);
//Check if the passwords match
if($inputPassword != $vPassword){
echo '<p style = "text-align: center;">Oops!The passwords you input did not match. Please try again.</p>';
session_write_close();
exit;
}
//Check for duplicate username
$query = "SELECT * FROM user_info WHERE username = ' ".$inputUsername." ' ";
$result = mysqli_query($mysqli, $query);
if(mysqli_num_rows($result) == 1) {
echo '<p style = "text-align: center;">Oops! That Username is already taken. <br>Please try a different one.</p>';
session_write_close();
exit;
}
//Username is not takin and the passwords match
else {
$sql = "INSERT INTO user_info (username, password) VALUES (' ".$inputUsername." ', ' ".$protectedPassword." ')";
echo '<p style = "text-align: center;">Success! You Have Made an Account!</p>';
if($mysqli->query($sql) === TRUE) {
session_write_close();
exit;
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
LOGGING IN
<?php
require('db_credentials.php');
$inputUsername = $_POST['username'] ? $_POST['username'] : null;
$inputPassword = $_POST['password'] ? $_POST['password'] : null;
//protect database from corrupt user input
$inputUsername = $mysqli->real_escape_string($inputUsername);
$inputPassword = $mysqli->real_escape_string($inputPassword);
$mysqli = new mysqli($servername, $username, $password, $dbname);
$query = "SELECT * FROM user_info WHERE username = ' ".$inputUsername." ' ";
$result = $mysqli->query($query);
//check if username is in database. If it is, do the passwords match?
if($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
echo $row['password'] . "<br>"; //matches hash in database exactly
echo $inputPassword; //matches the password I type in. Which is same I used to sign up.
if(password_verify($inputPassword, $row['password'])){
header("Location: puzzlerMember.php"); //this never happens
exit;
}
}
echo '<p style = "text-align: center;">Oops! Your Username/Password is incorrect. Sign up if you do not have an account.</p>'; //this always happens
exit;
?>
Note: In the database, I have the password column set to VARCHAR(255).
I've looked at many of these questions which are similar, but they all seemed to have mistaken the length of their password in the database to be too short. If they did not, I tried the top answer of the solutions. I have absolutely no idea what is wrong.
If you can help, I thank you in advance.
You are escaping your password, as a result this changes the password from what it was. Instead of relying on escaping as a security measure (which in itself is a misconception), use prepared statements.
As per the comment below, a clarification is required it seems: You are escaping the password then hashing it, as a result what is stored in the db is not what the user passes therefore it will never find what the user passes, hence, false is always returned.
Related: Should I mysql_real_escape_string the password entered in the registration form?
Update #1
As spotted by #mario, you seem to have spaces in your query when you are passing the values to it as such, it is searching your table for incorrect values.
Reading Material
Prepared Statements

PHP username session variable not saving if the username includes a number

I searched for this question but couldn't find it.
I have made a create user page that will allow the user to create an account on my page using a username. Usernames can be any combination of letters and numbers. When they create the user, it is supposed to call the same page, then redirect the user to the main page when it sees that the session variable is now set.
When I create a user with only letters in the username, it works fine and redirects them to the index page. However, when I create a user such as "student1" it will not set the session variable and therefore not redirect them.
You can try it yourself at http://collinmath.com/accounts/create.php to see what I mean. (Just don't use real info since I haven't set up the SSL yet)
<?php
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
// Set variables equal to POST data
$login_name = $_POST['username'];
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$role = $_POST['role'];
$pwd1 = $_POST['password_1'];
$pwd2 = $_POST['password_2'];
register();
}
// Register function will check the input and add the user if
// the input is accepted
function register() {
global $login_name;
global $first_name;
global $last_name;
global $email;
global $role;
global $errors;
global $connection;
global $pwd1;
global $pwd2;
global $hostname;
global $username;
global $password;
global $dbname;
// Connect to database
$connection = mysqli_connect($hostname, $username, $password);
mysqli_select_db($connection, $dbname);
// Check that username contains only letters and number
if (preg_match('/[^A-Za-z0-9]/', $login_name)) {
array_push($errors, "Username must contain only letters and/or numbers");
} else {
$login_name = strtolower($login_name);
}
// Sanitize SQL data
$first_name = mysqli_real_escape_string($connection, $first_name);
$last_name = mysqli_real_escape_string($connection, $last_name);
// Validate registration input and generate error log if there are issues
// Check if username is taken or empty
if (strlen($login_name) > 4) {
$query = "SELECT `User_Login` AS `Login` FROM `CMP_Users` WHERE `User_Login`=?";
$mysqli = new mysqli($hostname, $username, $password, $dbname);
$mysqli->set_charset("utf8");
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $login_name);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row[Login]) {
array_push($errors, "That username is taken");
}
} else {
array_push($errors, "Username must be at least 5 characters long");
};
if (strlen($login_name) > 16) {
array_push($errors, "Username must be 16 characters or less");
}
// Check First name
if ($first_name) {
if (preg_match('/[^A-Za-z\'\-\s]/', $first_name) || !preg_match('/[A-Za-z]/i', $first_name)) {
array_push($errors, "First Name is not valid");
}
if (strlen($first_name) > 15) {
array_push($errors, "First name must be 15 characters or less");
}
} else {
array_push($errors, "Must enter a first name");
}
//Check Last name
if ($last_name) {
if (preg_match('/[^A-Za-z\'\-\s]/', $last_name) || !preg_match('/[A-Za-z]/i', $last_name)) {
array_push($errors, "Last Name is not valid");
}
if (strlen($last_name) > 25) {
array_push($errors, "Last name must be 25 characters or less");
}
} else {
array_push($errors, "Must enter a last name");
}
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "Please enter a valid e-mail address");
}
if (strlen($email) > 50) {
array_push($errors, "E-mail address must be 50 characters or less");
}
// Check if role is legal
$role_value = 0;
if ($role == 'student') {
$role_value = 1;
} else if ($role == 'teacher') {
$role_value = 2;
} else {
array_push ($errors, "No role selected");
}
// Check if passwords match
if ($pwd1 != $pwd2) {
array_push($errors, "Passwords do not match");
} else {
// Check if passwords meet criteria
if (!preg_match('/\W/', $pwd1) || !preg_match('/[0-9]/', $pwd1) ||
strlen($pwd1) < 10) {
array_push($errors, "Password is not valid");
}
}
// If there are no errors, commit results to DB and create session
if (empty($errors)) {
// Hash passwords for DB storage
$pwd1 = password_hash($login_name . $_POST['password_1'], PASSWORD_DEFAULT);
/*
THIS WILL NEED TO BE UPDATED WHEN E-MAIL VALIDATION IS IMPLEMENTED
*/
// Create query for inserting new data
$add_user_query = "INSERT INTO `CMP_Users` (User_First_Name, User_Last_Name, "
. "User_Login, User_Email, User_Password, User_Role, User_Created) VALUES "
. "(?, ?, ?, ?, ?, ?, NOW())";
$mysqli_add_user = new mysqli($hostname, $username, $password, $dbname);
$mysqli_add_user->set_charset("utf8");
$stmt_add_user = $mysqli_add_user->prepare($add_user_query);
$stmt_add_user->bind_param("sssssi", $first_name, $last_name, $login_name, $email, $pwd1, $role_value);
$stmt_add_user->execute();
// Set session variables
$_SESSION['username'] = $login_name;
$_SESSION['role'] = $role_value;
$_SESSION['email'] = $email;
$_SESSION['fname'] = $first_name;
$_SESSION['lname'] = $last_name;
$connection->close();
header('Location: http://www.collinmath.com/mathpages/index.php');
exit();
}
// Close db connection
$connection->close();
}
// Check whether the user is already logged in
// and redirect them to the main user page if they are
if (isset($_SESSION['username'])) {
header('Location: http://www.collinmath.com/mathpages/index.php');
exit();
}
?>
UPDATE:
So, I changed a bunch of the code and tinkered with the php.ini file but I'm still having problems. When I look at my cookies, I see the cookie is there. I see the file is created in the sessions folder and that the variables are set in that file, but there is still no session info when I do a var_dump.
My session_save_path and var_dump shows this:
/home/[myname]/sessions/
array(0) { }
and the file that is created in my sessions folder looks like this:
username|s:7:"testerz";role|i:1;email|s:19:"email#email.com";fname|s:4:"First";lname|s:6:"Name";
Problem Fix:
This is work in progress from the long comment discussion and will be updated as we go
From what you've told me the logic process of your situation is impossible.
RE: Your update:
Then if the session is definitely being written then there are three possible options:
1) there is an ini_set() or a directory-local .ini file which is changing the session name so data from one directory is not being recognised in another, as they're looking in different sessions.
2) You have a spelling or casing issue of your $_SESSION keys.
3) session_start() has not been initiated.
Furter debugging and Solution:
Whenever you var_dump your session data, and it's turning up blank; add these lines:
error_log(print_r(session_status()."<BR>",true));
error_log(print_r(session_name()."<BR>",true));
error_log(print_r($_SESSION,true)); //your original output.
Add this code block to both your data-in page (create.php) and the destination page that is failing to show certain sessions.
If the above are always exactly the same (and they may be if , as you say, some data does "work".
Then the answer is that you definitely absolutely have some lines in your code that change the session values. The symptoms look like you've got a screwed up REGEX preg_ function somewhere. Again; use your PHP Error Log to check these things out.
General Fixes:
Quote your array keys; $row[Login] should be `$row['Login']
Use a single MySQLi connection, of a single type
That type should be the Object Orientated approach (->)
Do not use real_escape_string for Object Orientated MySQL connections.
Use Multibyte PHP String functions
Use UTF8mb4 MySQLi connection character sets, and the same in your tables and columns.
Tidy up your code and your logic process, you've made a funtion but the function always runs so it has no benefit being a function - it may as well just be straight code.
Don't use globals
MySQL does not care about new lines so you don't need to concatenate the SQL strings.
Wow, this was the most random reason...
It turns out the problem was my php.ini file, but not for the reason I thought. I had set the session.cookie_domain value to "collinmath.com" but needed to add a period to the beginning of collinmath. I changed the session.cookie_domain value to ".collinmath.com" and it fixed the problem. I have no idea why this worked, but it did.

User not being deleted on link click [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?
There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.
Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

How to get two fields while creating session?

In my login page I am using a phone number and password fields only to login, thereafter, I am creating and storing a session using the phone number.
Insted, I want to echo the username currently logged in to display the current user becasue in my case I am currently only able to display the phone number of the logged in user. How do I do that?
Here is my login script
<?php
// Starting Session
session_start();
include "../script.php";
$error=''; // Variable To Store Error Message
if (isset($_POST['signin'])) {
if (empty($_POST['signinphone']) || empty($_POST['signpassword'])) {
$error = "Phone or Password is invalid";
}
else
{
// Define $username and $password
$phone=$_POST['signinphone'];
$password=$_POST['signpassword'];
// To protect MySQL injection for Security purpose
$phone = stripslashes($phone);
$password = stripslashes($password);
$phone = pg_escape_string($db, $phone); // Set email variable
$password = pg_escape_string($db, $password); // Set hash variable
$pass_crypted = password_hash($password);
// SQL query to fetch information of registerd users and finds user match.
$sql="SELECT usr_id, usr_email, usr_first_name, usr_last_name,
usr_encrypted_password,
usr_salt, usr_stos_id, usr_pers_id, usr_username, usr_updated_at,
usr_created_at, usr_enabled, usr_role_id, usr_jbrn_id,
usr_mobile_number,
stp_acc_id, usr_location, usr_mobile_imei, usr_type
FROM js_core.stp_users
where usr_mobile_number='$phone'
AND usr_encrypted_password='$password'";
$result=pg_query($db, $sql);
$rows = pg_num_rows($result);
if ($rows == 1) {
$_SESSION['phone']=$phone; // Initializing Session
$_SESSION['username'] = pg_fetch_object($result)->usr_last_name;
header("location: ../index.php");
} else {
//echo "0 results";
echo "Try Again the credentials you entered don't much ours";
}
; // Closing Connection
}
}
?>
and Here is my sample code where I want to display the username inplace of the phone
<li>
<?php
if(isset($_SESSION['username'])) {
echo '<li>'. $_SESSION["username"] . '</li>';
echo '<li>
Log Out</li>';
} else {
echo '<a class="signing" href="#login" data-toggle="modal" data-target="#signIn">Login </a>';
}
?>
</li>
There is not one answer to your question.
I'm posting this because it contains an example of all the things that have been mentioned in the comments to your question.
Firstly, you'll notice that there is a new $db connection that uses the PDO. This is the generally accepted way to handle DB connections and is relatively easy to install (if your php version doesn't have it) - there are plenty of examples on SO. I'd assume you'd want this in your script.php since it's common.
I've also swapped out the password hashing function for the native BCRYPT password_hash() function. When you sign the user up, you would then use it like so:
$encryped_password = password_hash($_POST['signpassword'], PASSWORD_BCRYPT);
This contains a uniquely salted password with the default cost.
Following that, you can fetch the user as you were, with the small adjustment to make it a prepared statement. This provides SQL Injection protection and generally makes things cleaner.
You'll then see that after the row is fetched, you can compare the password with the password_verify() function.
Finally to your original issue - I've set the PDO mode to object, so you can access and assign as many properties as you need to in the same way. Only the properties in the SELECT clause will be available in that object.
// Starting Session
session_start(); //I'd suggest this should also go in your script.php
$db = new PDO('pgsql:dbname=mydb;host=localhost;user=myuser;password=mypass');
include "../script.php";
$error=''; // Variable To Store Error Message
if (isset($_POST['signin'])) {
if (empty($_POST['signinphone']) || empty($_POST['signpassword'])) {
$error = "Phone or Password is invalid";
}
else
{
// SQL query to fetch information of registerd users and finds user match.
$sql = 'SELECT usr_id, usr_email, usr_first_name, usr_last_name, usr_encrypted_password
usr_stos_id, usr_pers_id, usr_username, usr_updated_at,
usr_created_at, usr_enabled, usr_role_id, usr_jbrn_id,
usr_mobile_number, stp_acc_id, usr_location, usr_mobile_imei,
usr_type
FROM js_core.stp_users
WHERE usr_mobile_number = :phone_number';
$stmt = $db->prepare($sql);
$stmt->execute(['phone_number' => $_POST['signinphone']]);
if ($row = $stmt->fetch(PDO::FETCH_OBJ)){
if(password_verify($_POST['signinpassword'], $row->usr_encrypted_password)) {
$_SESSION['phone'] = $row->usr_mobile_number; // Initializing Session
$_SESSION['username'] = $row->usr_username;
header("location: ../index.php");
} else {
//valid user, invalid password
}
} else {
//Invalid user
echo "Try Again the credentials you entered don't much ours";
}
}
}
I've made the assumption that you're running at lease PHP 5.5 for the password_hash, but there is a polyfill if not.

My if / else statement doesnt work for my custom php login script

Somehow my conditional simply doesnt work. Once I click the button on my login form which is set to "post" and has the action defined as the below login script I only get directed to the script but not redirected as defined in my conditional statement. What is wrong with my code?
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$database = "project";
$connection = mysqli_connect($servername, $username, $password, $database) or exit(header("location:maintenance.php"));
function login_check() {
global $connection;
$name = $_POST['name'];
$password = $_POST['password'];
$prepared = mysqli_stmt_init($connection);
$request = mysqli_stmt_prepare($prepared, "SELECT id FROM members WHERE name = ? AND password = ?");
mysqli_stmt_bind_param($prepared, "ss", $name, $password);
$result= mysqli_stmt_bind_result($request);
$rows_counter = mysqli_num_rows($result);
mysqli_stmt_close($prepared);
if ($rows_counter > 0) {
$_SESSION['member'] = $name;
header("location:../../success.php");
}
else {
header("location:../../relogin.php");
}
}
Here is my input and approach to your code.
First of all before writing a solution and tell to much, it is always a good practice to make step by step code troubleshooting.
Before going and building a complete login system and put if statement or make prepare statement with inputs etc.
Make your solution in small working chops and put the puzzle together.
You question was focused on if statement and most of the help and answer was also focused on if statement which is nice, but the problem was not there.
I removed the if statement and a lot and just focused to see if I get some thing returned, I did not.
You $result= mysqli_stmt_bind_result($request); missed arguments, when that fixed, the next line missed also something else. I already there quit debugging.
I have rewrite your code and it works, what I did I have redefined the naming of variable so they are crystal clear to understand what is name, call it username, database username call it dbUser or dbUsername etc.
And if you want to check your code returning some thing or not, use var_dump($someVariable).
Last thing, before making a post form, you could create a dummy username and password in your database and inject that directly in your code like, just to see if every thing is working, and then move to your form:
$username = "user1";
$password = "1234";
The solution I did is just to demonstrate how to do it and not necessarily representation of the best logic, but it is up to you to find the correct logic and all depends on your strategy.
Here is my suggestion:
<?php
session_start();
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "product";
$connection = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
// Check connection
if ($connection->connect_error)
{
header("location:maintenance.php");
exit();
// or for debugging, activate following line
//die("Connection failed: " . $connection->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
//if username and password empty stop login
if (!$username || !$password)
{
//do something, die is only example
die ("Not all the fields were filled in");
} else
{
login_check($username, $password);
}
function login_check($username, $password)
{
global $connection;
//sql statements is corrected, change field name to username
$sql = "SELECT * FROM `members` WHERE `username` = ? AND `password` = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$output = $stmt->get_result();
$row = $output->fetch_array(MYSQLI_NUM);
$stmt->close();
//print what comes out in $row
//print_r($row);
//check if $row has data
if ($row)
{
echo "success do something";
$_SESSION['member'] = $username;
} else
{
echo "fail do something";
}
}
After defining the function login_check(), you should also call it (if the conditions are right):
function login_check() {
// your implementation as above
}
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
As a side note, it is good practice to also explicetely close the connection before redirecting.
Edit
as KhomeHoly comments, only call the function when necessary...
You need to call your functions if you define them. Not doing so is like building a room within a new house but forgetting the door. It's there, but nobody can use or access it.
So what you need to do is the following:
// your script as it is right now
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
With isset() you check if the certain $_POST parameters are set, but not validated. You should at least do a basic validation of the data to see if they are correct!
Something like this would work, depends on your requirements
if (isset($_POST['name']) && strlen($_POST['name') >= 4 && isset($_POST['password']) && strlen($_POST['password']) >= 4) {
login_check(); // actually call the function
}
The code above would check if those paramters are set and check if name and password are at least 4 characters long. (I wouldn't accept usernames lower than 4 chars personally, passwords should be at least 8 for me)
Now of course this misses an correct error reporting and all that stuff, but I think that should give you the basic idea based on your quesiton.
Always, always, always put exit() after header redirect call. Even in that case, it might solve your issue.
header("location:../../success.php");
exit();
Why?

Categories