I'm new here so I hope I do this right.
I am having some problems with sending the right message from my php to my
html.
Here you can see the php part that sould give a message back if the username isn't valid(if is uses #$%^& etc.)
$validUsername = $CurrentUser->ValidateUsername($username);
//if the input isn't filled send a message back
if(!$validUsername)
{
$messageError = "Please fill in a valid username";
header("location: ../public/index.php?messageError=$messageError");
}
and another one that should check if the username is unique
$uniqueUsername = $CurrentUser->CheckAvailableUsername($validUsername);
if (!$uniqueUsername)
{
$messageError = "Please fill in a unique username";
header("location: ../public/index.php?messageError=$messageError");
}
now the weird thing is if use #$%^&etc. as a username it will give me back a please fill in a unique username instead of please fill in a valid username and I can't find out why.
oh btw I made a class named User with these methods Ill show them below here.
public function ValidateUsername($username)
{
if (!empty($username))
{
if (isset($username))
{
if (!preg_match("/^[a-zA-Z ]*$/", $username))
{
return false;
}
return $this->username = $username;
}
return false;
}
return false;
}
And the other one.
public function CheckAvailableUsername($username)
{
$sql = "SELECT * FROM `tbl_todolist`
WHERE `username` = '$username';";
$result = $this->dataBase->query($sql)->rowCount();
if ($result == 1)
{
return false;
}
return $this->username = $username;
}
I really hope you guys can help me with this.
After header(...); you need to throw in a return; or exit; to exit right there, otherwise it continues beyond that header.
Additional Notes
You are open to SQL injection in CheckAvailableUsername, you need to sanitize the value before you get to that function and also escape/bind the value to your query instead. It looks like you are using PDO already.
As you can see in the script below, I use multiple if statements when checking registration inputs. Is there an easier, less spaghetti?
The script works as is, but i would like it to be neater.
<?php
if (isset($_POST['register'])) {
$uname = trim($_POST['uName']);
$email = trim($_POST['email']);
$pass = trim($_POST['pass']);
$passCon = trim($_POST['passCon']);
$uname = strip_tags($uname);
$email = strip_tags($email);
$pass = strip_tags($pass);
$passCon = strip_tags($passCon);
if (!empty($pass)) {
if (!empty($email)) {
if (!empty($uname)) {
if ($pass == $passCon) {
$query = "SELECT username FROM users WHERE username='$uname'";
$result = mysqli_query($conn, $query);
$checkUsername = mysqli_num_rows($result);
if ($checkUsername == 0) {
$query = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count == 0) {
$password = hash('sha256', $pass);
$queryInsert = "INSERT INTO users(id, username, email, password, date) VALUES('', '$uname', '$email', '$password', '" . time() . "')";
$res = mysqli_query($conn, $queryInsert);
if ($res) {
$errTyp = "success";
$errMsg = "successfully registered, you may login now";
}
} else {
$errTyp = "warning";
$errMsg = "Sorry Email already in use";
}
} else {
$errTyp = "warning";
$errMsg = "Sorry Username already in use";
}
} else {
$errTyp = "warning";
$errMsg = "Passwords didn't match";
}
} else {
$errTyp = "warning";
$errMsg = "You didn't enter a Username";
}
} else {
$errTyp = "warning";
$errMsg = "You didn't enter an email address";
}
} else {
$errTyp = "warning";
$errMsg = "You didn't enter a password";
}
}
Thank you,
Jay
The problem you are facing is not at all uncommon. Many programmers have faced this issue. Let me help you along the way restructuring your script.
First of all, let's get rid of the nested if-else statements. They confuse and obfuscate what is really going on.
Version 1:
if (!isset($_POST['register']))
redirect('register.php'); // Let's assume that redirect() redirects the user to a different web page and exit()s the script.
$uname = $_POST['uName'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$passRepeat = $_POST['passRepeat'];
if (empty($pass)) {
$errorMessage = "You didn't enter a password";
}
if (empty($email)) {
$errorMessage = "You didn't enter an email address";
}
if (empty($uname)) {
$errorMessage = "You didn't enter a Username";
}
if ($pass !== $passRepeat) {
$errMsg = "Passwords didn't match";
}
$query = "SELECT username FROM users WHERE username='$uname'";
$result = mysqli_query($conn, $query);
$checkUsername = mysqli_num_rows($result);
if ($checkUsername !== 0) {
$errMsg = 'Sorry Username already in use';
}
$query = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count !== 0) {
$errMsg = 'Sorry Email already in use';
}
$password = hash('sha256', $pass);
$queryInsert = "INSERT INTO users(id, username, email, password, date) VALUES('', '$uname', '$email', '$password', '" . time() . "')";
$res = mysqli_query($conn, $queryInsert);
Note that although this avoids the nested if statements, this is not the same as the original code, because the errors will fall through. Let's fix that. While we are at it, why would we want to return after the first error occurs? Let's return all the errors at once!
Version 2:
$errors = array();
if (empty($pass)) {
$errors[] = "You didn't enter a password";
}
if (empty($email)) {
$errors[] = "You didn't enter an email address";
}
if (empty($uname)) {
$errors[] = "You didn't enter a username";
}
if ($pass !== $passRepeat) {
$errors[] = "Passwords didn't match";
}
$query = "SELECT username FROM users WHERE username='$uname'";
$result = mysqli_query($conn, $query);
$usernameExists = mysqli_num_rows($result) > 0;
if ($usernameExists) {
$errors[] = 'Sorry Username already in use';
}
$query = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($conn, $query);
$emailExists = mysqli_num_rows($result) > 0;
if ($emailExists) {
$errors[] = 'Sorry Email already in use';
}
if (count($errors) === 0) {
$password = hash('sha256', $pass);
$queryInsert = "INSERT INTO users(id, username, email, password, date) VALUES('', '$uname', '$email', '$password', '" . time() . "')";
$res = mysqli_query($conn, $queryInsert);
redirect('register_success.php');
} else {
render_errors($errors);
}
Pretty clean so far! Note that we could replace the if (empty($var)) statements with a for-loop. However, I think that is overkill in this situation.
As a side note, please remember that this code is vulnerable to SQL injection. Fixing that issue is beyond the scope of the question.
Less spaghetti? Start with functional decomposition, then work towards separating the task of sanitation from that of validation. I will leave out many steps that I take (such as verifying the form / $_POST / filter_input_array() has the correct number of inputs, and the correct keys are in the $_POST superglobal / INPUT_POST, etc, you might want to think about that.). Alter some of my techniques for your exact needs. Your program should be less spaghetti afterwards. :-)
Sanitize then validate. You have to keep them separated, so to speak. ;-)
Sanitizing with Functional Decomposition
Make a single task its own block of code.
If all of your sanitization steps (trim(), strip_tags(), etc.) are the same for all of your form fields, then make a sanitizer function to do that work. Note, that the one-time way you are trimming and stripping tags can be improved upon simply by using a loop. Save the original value in a variable, then trim(), strip_tags(), etc within a while loop. Compare the results to the original. If they are the same, break. If they differ, save the current value of the form field in your variable again and let the loop run again.
function sanitize($formValue)
{
$oldValue = $formValue;
do
{
$formValue = trim($formValue);
$formValue = strip_tags($formValue);
//Anything else you want to do.
$formValue = trim($formValue);
if($formValue === $oldValue)
{
break;
}
$oldValue = $formValue;
}
while(1); //Infinite loop
return $formValue;
}
Then, simply run this function in a loop.
$sanitized = [];
foreach($_POST as $key => $value)
{
$sanitized[$key] = sanitize($value);
}
/* You can keep track your variable anyway you want.*/
Looking further down the road, it is times like this where devising an input source ($_POST, $_GET, $_SESSION, $_FILES, $_COOKIE, etc..) based sanitizing, class hierarcy really comes in handy. Moreover, basing that class hierarchy on the use of filter_input_array() really puts you a head of the game. What about validation?
Validating with Functional Decomposition
You could look at each form field as needing its own validating function. Then, only the logic required to check one form field will be contained within the block. The key, retain your Boolean logic by having the validator functions return the results of a test (true / false).
function uname($uname, &$error)
{
if(! /* Some test */)
{
$error = 'Totally wrong!'
}
elseif(! /* Another test */)
{
$error = 'Incredibly wrong!'
}
else
{
$error = NULL;
}
return !isset($error) //If error is set, then the test has failed.
}
function email($email, &$error)
{
if(! /* Some test */)
{
$error = 'Totally wrong!'
}
elseif(! /* Another test */)
{
$error = 'Incredibly wrong!'
}
else
{
$error = NULL;
}
return !isset($error) //If error is set, then the test has failed.
}
function pass($pass, &$error)
{
if(! /* Some test */)
{
$error = 'Totally wrong!'
}
elseif(! /* Another test */)
{
$error = 'Incredibly wrong!'
}
else
{
$error = NULL;
}
return !isset($error) //If error is set, then the test has failed.
}
function passCon($passCon, &$error)
{
if(! /* Some test */)
{
$error = 'Totally wrong!'
}
elseif(! /* Another test */)
{
$error = 'Incredibly wrong!'
}
else
{
$error = NULL;
}
return !isset($error) //If error is set, then the test has failed.
}
In PHP, you can use variable functions to name your function the same as the fields they are checking. So, to execute these validators, simply do this.
$errorMsgs = [];
foreach($sanitized as $key => $value)
{
$key($value, $errorMsgs[$key])
}
Then, generally speaking, you just need to see if there are any errors in the $errorMsgs array. Do this by processing the $errorMsgs array
$error = false;
foreach($errorMsgs as $key => $value)
{
if(isset($value))
{
//There is an error in the $key field
$error = true;
}
}
..and then.
if($error === true)
{
//Prompt user in some way and terminate processing.
}
// Send email, login, etc ....
Taken further, you could create a generic, Validator, super class.
All this being said. I do all of my sanitization and validation in an object oriented way to reduce code duplication. The Sanitizer super class has children (PostSanitizer, GetSanitizer, ....). The Validator super class has all the test one might perform on a string, integer, or float. Children of the Validator superclass are page/form specific. But, when something like a form token is needed, it's validating method is found in the Validator super-class because it can be used on any form.
A good validation routine keeps track of:
1) Input values in an associative array..
2) Test results (Booleans) in an associative array. Test results (true/false) can be converted to CSS classes or a JSON string of '1's and '0's.
3) Error messages in an associative array.
..then makes final decisions about what to do with the input values and/or error messages based on the test results (by key). If there are errors (false values in the a hypothetical test results array), use the error messages that have the corresponding key.
My previous example condenses the final error checking and error message data structures with one array, but using separate data structures allows more flexibility (decouples error messages from the detected errors). Simply store the results of each validating variable function into a $testResults array like this.
function sanitize($formValue)
{
$oldValue = $formValue;
do
{
$formValue = trim($formValue);
$formValue = strip_tags($formValue);
//Anything else you want to do.
$formValue = trim($formValue);
if($formValue === $oldValue)
{
break;
}
$oldValue = $formValue;
}
while(1); //Infinite loop
return $formValue;
}
$sanitized = [];
foreach($_POST as $key => $value)
{
$sanitized[$key] = sanitize($value);
}
$testResults = [];
$errorMsgs = [];
foreach($sanitized as $key => $value)
{
$testResults[$key] = $key($value, $errorMsgs[$key])
}
if(!in_array(false, $testResults, true))
{
return true //Assuming that, ultimately, you need to know if everything worked or not, and will take action on this elsewhere. It's up to you to make the correct functions/methods, but this general foundation can get you going.
}
return false; //Obviously. Do not submit the form. Show the errors (CSS and error messages).
Then, simply check for the existence of false in the $testResults array. Get the corresponding error message from $errorMsgs using the appropriate $key. Using this generic, final stub, you can create a powerful santization and validation routine, especially if you go object oriented.
Eventually, you will begin to see that the same kinds of test are being repeated among the various validation variable functions: data type, length, regular expression, exact matches, must be a value within a set, etc. Thus, the primary difference between the validating variable functions will be the minimum and maximum string lengths, regex patterns, etc... If you are savvy, you can create an associative array that is used to "program" each variable function with its set of validation parameters. That's getting a bit beyond the scope, but that is what I do.
Thus, all my variable functions perform the same basic tests via factored out logic using a method of class Validator called validateInput(). This method receives the following arguments
1) The value to be tested.
2) An associative array of the test parameters (which can specify datatype)
3) An array element, passed in as a variable (by reference), that corresponds the field being tested that will hold the error message, if any.
What's funny, is that I use a two step sanitization and a two step validation. I use a custom filter algorithm using PHP functions, then I use the PECL filter functions (filter_input_array()). If anything fails during these steps, I throw a SecurityException (because I extend RuntimeException).
Only after these filters pass do I attempt to use the PHP/PECL filter valiation functions. Then, I run my own validation routine using validating, variable functions. Yes, these only run if the previous test passed as true (to avoid overwriting previous failures and corresponding error message).
This is entirely object oriented.
Hope I helped.
As a practice, I am trying to create a script to log a user in using array.
So I have created a associate multidimensional array which holds 'user' and 'password',
The idea is to use this array to compare data entered by the user through a HTML form.
The problem I am having is that, the password entered by the user is checked against all the password stored in array not the only one the password belongs to. So I am struggling with a logic to check the password entered by the user with the values stored in array, one by one and not as a whole.
My script:
<?php
$data = Array();
$data['email'] = $_POST['email'];
$data['pass'] = $_POST['pass'];
$data['passM'] = $_POST['passM'];
$users = Array(
'tomasz' => '123',
'mario' => 'abc',
);
if($_SERVER['REQUEST_METHOD']=='POST'){
$hello='';
foreach($users as $u => $p){
if($data['passM'] == $p){
header("Location: ../home.php");
}else{
echo "nooooo";
}
}
var_dump($users);
var_dump($data['email']);
var_dump($data['pass']);
var_dump($data['passM']);
}
Could anyone please suggest a solution?
Try This code, I hope you will find answer to your question.
$data = Array();
$data['email'] = $_POST['email'];
$data['pass'] = $_POST['pass'];
$data['passM'] = $_POST['passM'];
//var_dump($_POST);
$users = Array(
'tomasz' => '123',
'mario' => 'abc',
);
if($_SERVER['REQUEST_METHOD']=='POST'){
$hello='';
if(in_array($data['passM'],$users)){
echo "Found";
}else{
echo "nooooo";
}
}
Check the username first, then the pass for these user.
Right now I don't see any logic that provides any way of knowing what user to check against. If you knew what user was logging in you could check that the username of the array was the same as the username the form provided.
$data['user'] = $_POST['user'];
foreach($users as $u => $p){
if($u == $data['user']){
if($data['passM'] == $p){
header("Location: ../home.php");
}else{
echo "nooooo";
}
}
}
I assume you know which user tries to log in.
So, you could just check if this user exists and if the password is correct.
$data['user'] = $_POST['user'];
if(array_key_exists($data['user'], $users) && $data['passM'] == $users[$data['user']]) {
header("Location: ../home.php");
} else {
echo "nooooo";
}
Well Mr. Tomari in_array() method look for only value in array. if you have stored you email in array as value then no issue. if you have store 'email' as key and 'passm' as value of the that email then you have to use this code:
if($_SERVER['REQUEST_METHOD']=='POST'){
$hello='';
if(array_key_exists($data['email'],$users) && in_array($data['passM'],$users)){
echo "Found";
}else{
echo "nooooo";
}
}
Im trying to come up with MySQL logic for a search function I got on my page. Its a simple form where the user can choose to fill in search criteria. The criteria(s) is send as arguments to a function that generates the mysql logic. This is whats inside the PHP controller file:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
So if nothing is set a complete list of all the members is generated and displayed. This is the function that is called if any of the inputs is set:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
The mysql logic is obviously wrong. I need a set of conditions (in the MySQL logic if possible) that checks the PHP variables for value and if there is none it should not be accounted for when querying the database. So if only the username is set in the form the other variables should not be included in the SQL logic.
I've looked up the MySQL IF() condition but Im still not able to come up with proper code that does what I need. If someone could point me in the right direction I would be able to do the rest myself. Any other approach for solving this kind of problem is also welcome.
If i understand your problem, then the simple way is to use if else to build sql query, for example
$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks
I am trying to write a simple function that checks if a username exists in the db and if so to call another function to generate a new username. My code seems to fall over though:
Username Function:-
$user1=create_username($fname, $company);
function create_username($surname, $company){
//$name_method=str_replace(" ", "", $surname);
$name_method=$surname.$forename;
$company_name_method=str_replace(" ", "", $company);
if(strlen($name_method)<=5)
{
$addition=rand(11,99);
$first=$addition.$name_method;
}
else
{
$first=substr($name_method,0,5);
}
if(strlen($company_name_method)<=5)
{
$addition2=rand(11,99);
$second=$addition2.$company_name_method;
}
else
{
$second=substr($company_name_method,0,5);
}
$middle=rand(100,1000);
$username=$first.$middle.$second;
return($username);
}
Check Username Function:
check_user($user1, $dbc, $fname, $company);
function check_user($user1, $dbc, $surname, $company){
$check_username="SELECT username FROM is_user_db WHERE username='$user1'";
$resultx=mysqli_query($dbc, $check_username) or die("Could not check username");
$num_rows=mysqli_num_rows($resultx);
if($num_rows>0)
{
$user1=create_username($fname, $company);
check_user($user1, $dbc, $fname, $company);
}
else
{
return($user1);
}
}
It just seems to return the original username.
You probably need to re-factor your code a little. Write out the steps on paper; that helps me. So far, I can see:
You want to check a username is unique on form submission
If it's not, generate a new username
So, check the username when your form is POSTed:
<?php
if (isset($_POST['submit'])) {
if (username_unique($_POST['username'])) {
// carry on processing form
}
else {
$suggested_username = suggest_username($_POST['username']);
// display form, with new suggested username?
}
}
And then write your functions:
<?php
// following on from code from above
function check_username($username) {
// get database connection (I use PDO)
$sql = "SELECT COUNT(*) AS count FROM users_tbl WHERE username = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($username));
$row = $stmt->fetchObject();
return ($row->count > 0); // if 'count' is more than 0, username already exists
}
function suggest_username($username) {
// take username, and add some random letters and numbers on the end
return $username . uniqid();
}
Hopefully this will help. Obviously it'll need some modification to work in your set-up, but this is the general flow you'll need.