PHP not working, database not updating - php

im writing this php script to update user passwords, requiring old pasword, new and new confirmation. It all works it seems up to the actual UPDATE mysql statement. Not sure what I've done wrong, al help appreciated!
Also, I am aware its not secure and such, I am just trying ot make it work first im a php newbie!
I'm tearing my hair out, when I run this, everything seems to work except it breaks just before if (empty($error)){ , i have tested the echo for session email and it displays that, however it does not update the database with the new password. Please help! below is my code:
<?php
session_start();
include('database_connection.php');
$error = array();
if (empty($_POST['oldpassword'])){
$error[] ='You did not enter your current password!';
} else {
$oldpassword = $_POST['oldpassword'];
}
if (empty($_POST['newpassword'])){
$error[] = 'You did not enter a new password!';
} else {
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["newpassword"])){
$newpassword = $_POST['newpassword'];
} else{
$error[] = 'Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit!';
}
}
if (empty($_POST['newpasswordcon'])){
$error[] = 'You did not enter your new password confirmation!';
} else {
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["newpasswordcon"])){
$newpasswordcon = $_POST['newpasswordcon'];
} else{
$error[] = 'Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit!';
}
}
if($_POST['newpassword'] != $_POST['newpasswordcon']){
$error[] ='New password and confirmation do not match!' ;
}
$sql = "SELECT password FROM users WHERE email='" . $_SESSION['email'] . "'";
$result = mysql_query($sql);
if( $r = mysql_fetch_array($result) ) {
extract($r);
if($_POST['oldpassword'] != $password);{
$error[] ='Incorrect current password!';
}
//breaks here
echo $_SESSION['email'];
if (empty($error)){
echo $_SESSION['email'];
mysql_query("UPDATE users SET password='$newpassword' WHERE email='" . $_SESSION['email'] . "'");
echo '<p class ="alert alert-success fade in">Success! Your password has been updated!</p>';
}
} else{
foreach ($error as $key => $values) {
echo '<p class ="alert alert-error fade in">'.$values.'</p>';
}
}
?>

There is a semicolon which should not be there.
if ($_POST['oldpassword'] != $password);{ // <- remove this semicolon after )
$error[] ='Incorrect current password!';
}

I don't see any addslashes() in your code and am wondering if you get any matches? http://www.php.net/manual/en/function.addslashes.php

Related

PHP/MySQL - Email validation not working

I know this has been asked a lot, and I've search and literally tried it all. I'm really close, but can't get it to work.
I'm trying to check if the username or usermail is already in use and display the error accordingly.
<?php
if (isset($_POST['register'])) {
try
{
$checkValidity = $connect->prepare('SELECT username, usermail FROM users WHERE username = :username OR usermail = :usermail');
$checkValidity->bindValue(':username', $username);
$checkValidity->bindValue(':usermail', $usermail);
$checkValidity->execute();
$row = $checkValidity->fetchColumn();
if ($row == $username) {
$errName = 'This username is already taken.';
}
if ($row == $usermail) {
$errMail = 'Email already in use.';
}
}
catch(PDOException $e)
{
// print $e->getMessage();
}
}
?>
It works fine for the username, but for the life of me I can't get the email error to work...
I attempted separate SELECT queries (username/usermail), and the email error would show ONLY if the username error showed.
The email error will never show just by itself.
I've spent one too many hours just trying to get this to work, and I'm slowly losing my mind.
Any indication would be greatly appreciated...!
Thank you...
FetchColumn return first column value. You need to use fetch instead. Like
$row = $checkValidity->fetch();
if ($row['username'] == $username) {
$errName = 'This username is already taken.';
}
if ($row['usermail'] == $usermail) {
$errMail = 'Email already in use.';
}
There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.
your fetching username only you need to use fetch() to get the whole row and compare like this
$row = $checkValidity->fetch();
if ($row['username'] == $username) {
$errName = 'This username is already taken.';
}
if ($row['useremail'] == $useremail) {
$errMail = 'Email already in use.';
}

Password_hash Incorrect after updating table

My login system md5 hashes the username and I password_hash the password. Therefore I cannot fetch the row based on the username? My client then enters an email address which I base64encode. I then offer a lost password change option. However, when I UPDATE the field using the same type of hash but, using the email field as an identifier, the new password is incorrect?
Below is a sample of my UPDATE, but hard coded for illustration(PS this does not work either?).
$em = 'example#example.com';
$em1 = base64_encode($em);
$ps = 'some password';
$password_hash = password_hash($ps, PASSWORD_BCRYPT);
$qu = "UPADTE table SET field = '$password_hash' WHERE email = '$em1'";
$res = mysqli_query($link, $qu);
Edited question to include my code after verifying that the user exists and sending out an email for them to positively identify themselves as the owner of the account. Here is the final processor page.
if(EMPTY($_POST[psw1]) ) {
echo "New password must be supplied"; }
elseif(EMPTY($_POST[psw2]) ) {
echo "Repeat password must be entered"; }
elseif($_POST[psw1] != $_POST[psw2]) {
echo "Passwords entered do not match";
} elseif(EMPTY($_POST[eu])) {
echo "Essential data is missing in order to complete this process.";
}
elseif (strlen($_POST['psw1']) < 6) {
echo "Password must be at least six characters in length";
}
elseif (preg_replace("/[^a-zA-Z0-9]/", "", $_POST['psw1']) != $_POST['psw1']) {
echo "Password may only contain letters and numbers";
}
elseif(!EMPTY($_POST[psw1]) && !EMPTY($_POST[psw2]) && !EMPTY($_POST[eu]) && $_POST[pw1] == $_POST[pw2] ) {
include "conn.php";
echo "$_POST[eu]<br />";
$eu = $_POST[eu];
$pdw = password_hash($_POST[pw1], PASSWORD_BCRYPT);
$sq = mysqli_query($link, "UPDATE str1 SET pf = '$pdw', cu_pw_status = '2' WHERE cu_type = '$eu'");
echo "Your password has been changed, you may now login <a href='login2.php'>Login</a>";
} else {
echo "An error occured. Contact Site Admin"; }
Check if you have column 'field' in your users table. Seems suspicios.
Check your update string, now it misses table name.
Check if you have user before updating:
$exists = mysqli_query("SELECT id FROM users WHERE email='$em1');
if (!is_empty($exists)) {
mysqli_query("UPDATE TABLE users SET password = '$ps' WHERE id='$exists');
echo 'updated' . "\n";
} else {
echo 'no user with such email hash' . "\n";
}

Recurring Error Display error function php

I have an output_errors function on my website which outputs all the "set" errors in a variable.
It pretty much works exactly how it should except for one thing; for one error in particular, it will output that error more than once (which it shouldn't).
How it is supposed to work is: if the user that is registering does not input any information into a certain part of the form, it needs to output (once) the error Fields marked with an asterisk(*) must be filled in., along with any other errors that the user has come across. All of this is displayed in an unordered list.
This is the function that I have created:
function output_errors($errors){
return '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
}
This is the code in which I specify when an error should be output:
$required = array('fname', 'username', 'password', 'password_again', 'email');
$reqCCNo = array('ccno');
// validation
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required) === true){
$errors[] = 'Fields marked with an asterisk(*) must be filled in.';
}
if(empty($value) && in_array($key, $reqCCNo) === true){
$errors[] = 'Please select a country.';
}
}
if(empty($errors)){
// credentials
if(preg_match('/[^a-z_\-0-9]/i', $fnp) || preg_match('/[^a-z_\-0-9]/i', $lnp)){
$errors[] = 'Credentials must only contain letters and numbers.';
}
// username
$result = mysqli_query($conn, "SELECT username FROM users WHERE username = '$user'");
$count = mysqli_num_rows($result);
if($count !== 0) {
$errors[] = 'That username is already taken.';
}
if(strlen($user) < 4){
$errors[] = 'Your username must be more than 4 characters long.';
}
if(strlen($user) > 16){
$errors[] = 'Your username must not be more than 16 characters long.';
}
if(preg_match('/[^a-z_\-0-9]/i', $user)){
$errors[] = 'Your username can only contain Alphanumeric characters.';
}
// email
if(filter_var($emailNex, FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'That is not a valid email type.';
}
$email_result = mysqli_query($conn, "SELECT email FROM users WHERE email = '$emailNex'");
$email_count = mysqli_num_rows($email_result);
if($email_count !== 0) {
$errors[] = 'That email is already in use.';
}
// password
if(strlen($pass) < 6){
$errors[] = 'Your password must be more than 6 characters long.';
}
if($pass !== $_POST['password_again']){
$errors[] = 'Those passwords do not match!';
}
}
and, this is the code that I use to output all of those errors:
if(!empty($errors)){
echo output_errors($errors);
}
Say that I leave all the fields blank and input a username less than 4 characters long, this is how it should be output:
Fields marked with an asterisk(*) must be filled in.
Your username must be more than 4 characters long.
this is how it is being output right now:
Fields marked with an asterisk(*) must be filled in.
Fields marked with an asterisk(*) must be filled in.
Fields marked with an asterisk(*) must be filled in.
Please select a country.
Your username must be more than 4 characters long.
All help is appreciated!
Thanks
Problem is with your foreach loop. it insert error message for every Required file.
You need to create a flag outside your foreach loop and set it to true when it comes inside your condition as
$flag=FALSE;// set it false
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required) === true){
$flag=TRUE;// set true if fulfill your condition
}
}
if($flag){// set your message
$errors[] = 'Fields marked with an asterisk(*) must be filled in.';
}
It will set your error message once instead of multiple

Creating a registration page in PHP

Hi guys so im creating this registration page for my website in php..This is the PHP script
# Script 9.5 - register.php #2
// This script performs an INSERT query to add a record to the users table.
$page_title = 'Register';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Initialize an error array.
// Check for a name:
if (empty($_POST['name'])) {
$errors[] = 'You forgot to enter your name.';
} else {
$n = mysqli_real_escape_string($dbh, trim($_POST['name']));
}
// Check for an email:
if (empty($_POST['email'])) {
$errors[] = 'You forgot to enter your email.';
} else {
$e = mysqli_real_escape_string($dbh, trim($_POST['email']));
}
// Check for a password and match against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your password did not match the confirmed password.';
} else {
$p = mysqli_real_escape_string($dbh, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your password.';
}
// Check for contact number:
if (empty($_POST['contact_no'])) {
$errors[] = 'You forgot to enter your contact no.';
} else {
$cn = mysqli_real_escape_string($dbh, trim($_POST['contact_no']));
}
if (empty($errors)) { // If everything's OK.
require 'connect_db.php';
$conn= mysqli_connect('*****' , '*****', '*****' , '*****' ,****);
// Make the query:
$q = ("INSERT INTO register_user(name, email, pass, contact_no) VALUES ('$n', '$e','$p','$cn')");
$r = #mysqli_query ($dbh, $q);// Run the query.
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Thank you!</h1>
<p>You are now registered. </p>
<p>Login </p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbh) . '<br/><br/> Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbh); // Close the database connection.
// Include the footer and quit the script:
include ('includes/footer.html');
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br>';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br>";
}
echo 'Please try again.</p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbh); // Close the database connection.
But the thing is once i register this is the output:
System Error
You could not be registered due to a system error. We apologize for any inconvenience.
Query: INSERT INTO register_user(name, email, pass, contact_no) VALUES ('', '','','')
so im kindly would glad for any assistance
You're calling mysqli_real_escape_string() BEFORE you establish your DB connection. This is not permitted. You MUST have a connection before doing the escape operations.
That means every single one of your form fields is going to be a boolean FALSE value, which signifies failure.
Your code should be structured
1. connect to db
2. process form inputs
3. if form inputs ok, insert into db
You've got #1 and #2 reversed.

Inserting PHP Session Variables into MySQL Database

I am having issues with my PHP code. I am trying to insert data into a mysql database using two session variables that I will need at a later time in the form. However whenever I submit the form I am returned with a "Unknown column in 'field list'" error.
The code is lengthy but you will likely need all of it to understand the issue.
<?php
session_start();
// Check for hazards and put them in an array if there is one selected
if($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); //connect to the db
//Check for offender first name
if (empty($_POST['pris_firstname'])) {
$errors[] = 'You forgot to enter offender first name.';
} else {
$prisf=$_POST['pris_firstname'];
}
//Check for offender last name
if (empty($_POST['pris_lastname'])) {
$errors[] = 'You forgot to enter offender last name.';
} else {
$prisl=$_POST['pris_lastname'];
}
//Check for offender date of birth
$dob = ($_POST['pris_dateofbirth']);
//Check for offender phone number
if (empty($_POST['pris_phonenum'])) {
$errors[] = 'You forgot to enter offender Phone Number.';
} else {
$prisphone=trim($_POST['pris_phonenum']);
}
//Check for offender address
if (empty($_POST['pris_address'])) {
$errors[] = 'You forgot to enter offender Address.';
} else {
//$prisaddress=trim($_POST['pris_address']);
foreach($_POST["pris_address"] as $value) {
$prisaddress .= $value . '\n';
}
}
//Check for offender next of kin first name
if (empty($_POST['pris_kinfirstname'])) {
$errors[] = 'You forgot to enter next of kin first name.';
} else {
$kinfirst=trim($_POST['pris_kinfirstname']);
}
//Check for offender next of kin last name
if (empty($_POST['pris_kinlastname'])) {
$errors[] = 'You forgot to enter next of kin last name.';
} else {
$kinlast=trim($_POST['pris_kinlastname']);
}
//Check for offender next of kin phone number
if (empty($_POST['pris_kinphone'])) {
$errors[] = 'You forgot to enter next of kin area code.';
} else {
$kinphone=trim($_POST['pris_kinphone']);
}
if (empty($_POST['pris_kinrelation'])) {
$errors[] = 'You forgot to enter next of kin relation.';
} else {
$kinrelation=trim($_POST['pris_kinrelation']);
}
//Check for offender next of kin address
if (empty($_POST['pris_kinaddress'])) {
$errors[] = 'You forgot to enter next of kin street address.';
} else {
foreach($_POST["pris_kinaddress"] as $value2) {
$kinaddress .= $value2 . '\n';
}
}
if (empty($errors)) { //if everyhing is ok
$q = "INSERT INTO prisoner_profile (pris_status,
pris_firstname,
pris_lastname,
pris_dateofbirth,
pris_phonenum,
pris_address,
pris_kinfirstname,
pris_kinlastname,
pris_kinphone,
pris_kinaddress,
pris_kinrelation
) VALUES (
'$status',
".$_SESSION['pris_firstname'].", ".$_SESSION['pris_lastname'].",
'$dob',
'$prisphone',
'$prisaddress',
'$kinfirst',
'$kinlast',
'$kinphone',
'$kinaddress',
'$kinrelation'
)";
$r = #mysqli_query ($dbc, $q); //Run the query.
Hope someone can help!
The error is pretty much self-explanatory, it means that you have got a column name wrong in your database. I recomend you echo out the error for your query just for this case as:
$r = mysqli_query ($dbc, $q) or die (mysqli_error());
One of the columns that are listed in your INSERT statement does not actually exist in the prisoner_profile. Check your table schema.
The one obvious issue I can see here is that you haven't handled the escape characters in your query, and you have used a few \n characters in your code.
Use mysqli_real_escape_string to handle that when inputting the data to the database.
Something like
$q = mysqli_real_escape_string($q);

Categories