I have a 'registration' page in PHP and I would like the script to run when an HTML button is clicked.
The PHP basically checks if all fields are filled, checks if the password and email confirmations are the same and saves to the database.
This is the code:
<?php
$Name = isset($_POST['Name']);
$Surname = isset($_POST['Surname']);
$Username = isset($_POST['Username']);
$Email = isset($_POST['Email']);
$C_Email = isset($_POST['C_Email']);
$Password = isset($_POST['password']);
$C_Password = isset($_POST['c_password']);
$SecQ = isset($_POST['SecQ']);
$SecA = isset($_POST['SecA']);
$con = mysql_connect('localhost', 'admin', 'storefile1234');
mysql_select_db ("storefile");
$check_username = mysql_query("SELECT FROM users WHERE username = '$Username'");
$check_email = mysql_query("SELECT FROM users WHERE Email = '$Email'");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if ($Name == null || $Surname== null || $Username == null || $Password == null || $C_Password == null || $Email == null || $C_Email == null || $SecQ == null || $SecA == null ) {
echo "Missing details. Please enter all fields.";
} else {
if(mysql_num_rows($check_username) != 0 && mysql_num_rows($check_email) != 0)
{
echo "Username/Email already exists";
}
if ($Email == $C_Email && $Password == $C_Password) {
$query = "INSERT INTO users (Username, Name,Surname, Password, Email, SecQ, SecA) VALUES ('NULL', ".$Username."', ".$Name."', ".$Surname."', ".$Password."', ".$SecQ."', ".$SecA."', ".$Email.')"';
mysql_query($query) or die ('Error registering.');
echo "Greetings, ".$Name.", you have been registered. ";
} else {
echo "Error registering your account. Please try again.";
}
}
?>
Also, is it recommended?
Whenever I run this page Missing details. Please enter all fields. displays, without having entered any details.
How do you do this?
You tying to get values by isset($_POST['Username']); and like this functions...
But documentation says: Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
So check on true, nut null. And escape your POST data after.
You can do like this:
$Name = isset($_POST['Name']) ? mysql_real_escape_string($_POST['Name']) : null;
P.S. Please again. Do not use mysql_* function. They are DEPRECATED.
Look on PDO (or mysqli_*)
For the issue of printing that message when you first load the page, use the array_key_exists function to test if the user has already submited something before checking if any field is null. Something like this:
if (array_key_exists('Name', $_POST) || array_key_exists('Surname', $_POST) || ... )
if ($Name == null || $Surname== null || ... )
echo "Missing details. Please enter all fields.";
Observation: you cannot use the isset function for the same purpose since, according to php documentation, it "determine if a variable is set and is not NULL"
You misuse isset
Try something like this:
$Name = null;
if (isset($_POST['Name'])) {
$Name = $_POST['Name'];
}
isset is only to check if a value is set.
Related
This question already has answers here:
PHP: check if any posted vars are empty - form: all fields required
(9 answers)
Closed 2 years ago.
I have a select action and I want to check if the fields username and password are both empty. My issue is that if one of them is empty echo msg pops but, but if both are empty it goes straight to the next page.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if ($_POST['submit']) {
include_once("connexion.php");
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$sql = "SELECT id, username, password FROM users where username = '$username' and password ='$password'";
$query = mysqli_query($dbCon,$sql);
if ($query) {
$row = mysqli_fetch_row($query);
$userId = $row[0];
$dbUsername = $row[1];
$dbPassword = $row[2];
}
if ($username == $dbUsername && $password == $dbPassword) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
} else {
echo "wrong username or password";
}
}
?>
Edit : I used Dharmesh Goswami solution :
if ($username == $dbUsername && !empty($username) && $password == $dbPassword && empty($password) )
It works like a charm ! Thank you.
Just check in if condition that both are not empty.
if ($username == $dbUsername && !empty($username) && $password == $dbPassword && !empty($password) )
{
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
}else
{
echo "wrong username or password";
}
You can apply empty() condition right after form posted.
if (isset($_POST['submit'])) {
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$username = trim($username);
$password = trim($password);
if (empty($username) || empty($password)) {
// Print your error.
}
}
|| will check if any one or both the fields are empty.
You can use the empty() function to check if input string is empty or not. To check if one of the fields is empty, you could use the XOR(^) operator. Failing which, the control should pass to AND(&&) operator which checks if both the fields are empty. If that fails too, you could say that none of the fields is empty. Hope this helps.
if(isset($_POST['submit']){
if(empty($_POST['username'] ^ empty($_POST['password']){
// code here to perform task if one field is left empty
} else if(empty($POST['username'] && empty($_POST['password']){
// code here to perform task if both fields are empty
} else {
// code here to perform task when none of the fields is empty
}
}
You do like that
extract($_POST);
if($_POST['submit']) :
if($Username == "" && $Password == ""):
$_SESSION['error'] = "Can't Be Blanked User Name Or Password";
endif;
endif;
I would suggest using mysqli_real_escape_string
if(!empty($_POST['username'])) $username = mysqli_real_escape_string($dbCon, $_POST['username']);
same for password
$sql = 'SELECT id, username, password FROM use...';
$result = $dbCon->query($sql);
$count = $conn->affected_rows;
if ($count == 1)
{
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
}else echo "wrong username or password";
also, wouldn't save username in sessions. Look up more on securing session.
I am working on a project and I have a registration form for users to fill out. The form then also populates the database with other variables.
For the life of me though, I cant figure out why the screen is loading a blank white page.. I have been following some tutorials from youtube and trying to apply them to my existing pages but so far no dice.
Here's the PHP code Im working with. The tutorial I followed worked flawlessly when used on a blank page, but once I edited it for my own use, it no longer wants to run:
<?php
if(isset($_POST['register'])){
$username = protect($_POST['username']);
$password = protect($_POST['password']);
$email = protect($_POST['email']);
$email2 = protect($_POST['email2']);
$password2 = protect($_POST['password2']);
$commname = protect($_POST['commname']);
$outpostname = protect($_POST['outpost']);
$special = protect($_POST['specialty']);
if($username == "" || $password == "" || $email == "" || $password2 == "" || $email2 == "" || $commname == "" || $outpostname == "" || $special == "no"){
echo "Please supply all required fields!";
}elseif(strlen($username) > 20){
echo "Username must be less than 20 characters!";
}elseif(strlen($email) > 100){
echo "E-mail must be less than 100 characters!";
}elseif(strlen($email2) > 100){
echo "E-mail verify must be less than 100 characters!";
}else{
$register1 = mysql_query("SELECT `id` FROM `user` WHERE `username`='$username'") or die(mysql_error());
$register2 = mysql_query("SELECT `id` FROM `user` WHERE `email`='$email'") or die(mysql_error());
if(mysql_num_rows($register1) > 0){
echo "That username is already in use!";
}elseif(mysql_num_rows($register2) > 0){
echo "That e-mail address is already in use!";
}else{
$spec = mysql_real_escape_string($_POST['specialty']);
$comnam = mysql_real_escape_string($_POST['commname'[);
$postnam = mysql_real_escape_string($_POST['outpost'[);
$ins1 = mysql_query("INSERT INTO `stats` (`credits`,`food`,`land`,`energy`,`turns`,`turns_max`,`gas`,`ore`,`population`,`buildeff`,`offpts`,`defpts`,`score`) VALUES (2000,2000,100,2000,30,30,2000,2000,500,100,0,0,0)") or die(mysql_error());
$ins2 = mysql_query("INSERT INTO `unit` (`trainee`,`juggernaut`,`infantry`,`marauder`,`terminator`,`reconsq`,`prisoner`,`destroyer`,`colossus`) VALUES (100,0,50,0,0,0,0,0,0)") or die(mysql_error());
$ins3 = mysql_query("INSERT INTO `user` (`colonynum`,`username`,`password`,`email`,`specialty`,`commname`,`outpostname`) VALUES (0,'$username','".md5($password)."','$email','$spec','$comnam','$postnam')") or die(mysql_error());
$ins4 = mysql_query("INSERT INTO `structure` (`agridome`,`spaceport`,`barrack`,`researchfac`,`laserbat`,`factory`,`infirmary`,`trainingfac`) VALUES (1,0,5,0,0,0,1,1,)") or die(mysql_error());
header('Location: aurora/main.php');
}
}
} ?>
I know its pretty "ugly" but I am trying to learn :)
if you need the form Im using let me know.. shouldnt matter though. I have all the ID's set right with correct spelling etc.
You have invalid syntax in your code, that is why showing blank screen. Replace this, Use $_POST['commname'] instead of $_POST['commname'[
$comnam = mysql_real_escape_string($_POST['commname']);
$postnam = mysql_real_escape_string($_POST['outpost']);
instead of
$comnam = mysql_real_escape_string($_POST['commname'[);
$postnam = mysql_real_escape_string($_POST['outpost'[);
Note: Use mysqli_* or PDO instead of using mysql_* functions(deprecated)
Hi guys i've been working for straight 12 hours, i can't seem to find fix.
i'm trying to compare user-input to database result for example $username == $result echo "Username is aldready taken, but the problem is it's passing through 2 statements without a break, and if i put a break to exit the loop, it always check for $email == $result2 despite of not entering any email in the field.
if (isset($_POST['username']) or isset($_POST['email'])) {
$extract = mysql_query("
SELECT
`username`, `email`
FROM `users`
WHERE `username`='$username' OR `email`='$email'
");
$resultq = mysql_num_rows($extract);
while ($row = mysql_fetch_array($extract)) {
$result = $row['username'];
$result2 = $row['email'];
echo " " . $result;
echo " " . $result2;
if ($username == $result) {
echo " Username is already Taken!";
// break; //whenever i put break, it always gives me the else if statement echo, despite not entering any email in the field
} //$pass = $_POST['pass'];
else if ($email == $result2) {
echo "Email Address is already used!";
// break;
} else {
}
}
}
Upgrade from mysql to either MySQLi, or PDO.
However;
$extract= mysql_query("SELECT username, email FROM users where username='$username' or email='$email'");
$resultq = mysql_num_rows($extract);
if($resultq > 0) {
echo 'Either your username, or email is already taken!';
return;
}
See sniko for the answer to your initial problem. However, see the following...
You're not defining $username or $email
if ($username == $result ) should be
if ($_POST['username'] == $result )
or you could define $username and $email at the beginning of the conditional.
You should also change this:
isset($_POST['username']) or isset($_POST['email'])
to this:
isset($_POST['username']) && isset($_POST['email'])
because you depend on both in your query.
and as sniko said, switch to mysqli or PDO. mysql_ is deprecated.
full sample:
if(isset($_POST['username']) && isset($_POST['email']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$extract= mysql_query("SELECT username, email FROM users where username='$username' or email='$email'");
$resultq = mysql_num_rows($extract);
if($resultq > 0) {
echo 'Either your username, or email is already taken!';
return;
}
}
Also note, you're not sanitizing the input. You could be hacked with this input. switching to mysqli or pdo and using prepared statements would help this.
What is the wrong in my code. it's say... (1) Username required (2) Password is not correct if i click Log in button without username and password, but it' should be show All filed required.
<?php
if(isset($_POST['action']) && isset($_POST['action']) == "Sign in")
{
include("../secure/content/database/db.php");
$uname = mysql_real_escape_string(trim($_POST['uname']));
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
/// check user name
$sql = mysql_query("SELECT uname FROM members WHERE uname = '$uname'");
$num_u = mysql_num_rows($sql);
// check user password
$sql2 = mysql_query("SELECT pass FROM members WHERE pass = '$pass'");
$num_p = mysql_num_rows($sql2);
$err = array();
if(isset($uname) && isset($pass))
{
if( empty($uname) && empty($pass))
{
$err[] = "All field required";
}
else
{
if(empty($uname))
{
$err[] = "Username required";
}
else
{
if($num_u == 0) $err[] = "Username is not correct";
}
if(empty($pass))
{
$err[] = "Password required";
}
else
{
if($num_p == 0)
$err[] = "Password is not correct";
}
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red>$er</font><br>";
}
}
else
{
include("content/include/newsession.php");
$tm = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$rt = mysql_query("insert into plus_user_login(id,uname,ip,tm, status, tm_out) values ('$_SESSION[id]','$_SESSION[uname]','$ip','$tm', 'ON', '')");
echo mysql_error();
print "<script>";
print " self.location='content/index.php';";
print "</script>";
}
}
}
Any idea or Solution..
On this line:
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
You are calling md5() which will always return a value, even if $_POST['pass'] was empty. So empty($pass) will never be true.
The md5() sum of an empty string or NULL does not result in an empty value, so you always have a value in $pass, even if $_POST['pass'] was empty.
// Never empty
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
// Because:
var_dump(md5(""));
string(32) "d41d8cd98f00b204e9800998ecf8427e"
When you check for the presence of $uname & $pass, use the $_POST values instead:
// instead of
if( empty($uname) && empty($pass))
// do
if(empty($uname) && empty($_POST['pass']))
please remove this md5 from following line, md5 create a string if pass is empty.
md5(mysql_real_escape_string(trim($_POST['pass'])));
use this.
mysql_real_escape_string(trim($_POST['pass']));
use md5 in another.
Your are running into this problem because empty strings are hashable see this.
Change
if(isset($uname) && isset($pass))
to
if(isset($uname) && isset($_POST['pass']))
I would like to accomplish the following:
If a username or password field is null, notify the user. If user name already exists, do not insert into the database and notify user to create a different name. if the username is unique and password is not null, return the username to the user.
As of now it always returns "Please enter a different user name." I believe the issue has to do with the database query but I am not sure. If anyone can have a look and see if I am making an error, I greatly appreciate it, thanks.
if ($userName or $userPassword = null)
{
echo "Please enter a user name and password or return to the homepage.";
}
elseif (mysql_num_rows(mysql_query("SELECT count(userName) FROM logininfo WHERE userName = '$userName'")) ==1)
{
echo "Please enter a different user name.";
}
elseif ($userName and $userPassword != null)
{
echo "Your login name is: $userName";
}
if ($userName or $userPassword = null)
This checks if the $userName is true (equivalent to $userName == true), and you're assigning null to $userPassword. You want something like $userName == '' || $userPassword == ''.
"SELECT count(userName) FROM logininfo WHERE userName = '$userName'"
Risk of SQL injection. Use mysql_real_escape_string before plugging values into queries!
Also, mysql_num_rows will always return 1 row, hence this expression is always true. You need to look at the value of this one row.
elseif ($userName and $userPassword != null)
If this check was what you'd intend it to be, it'd be redundant with the first check.
Use something like this:
function validateUser($username, $password) {
if ($username == '' || $password == '') {
return 'Please enter a user name and password or return to the homepage.';
}
$query = sprintf("SELECT COUNT(*) as `count` FROM `logininfo` WHERE `userName` = '%s'",
mysql_real_escape_string($username));
$result = mysql_query($query);
if (!$result) {
trigger_error(mysql_error());
return false;
}
$result = mysql_fetch_assoc($result);
if ($result['count'] > 0) {
return 'Please enter a different user name.';
}
return "Username: $username";
}
$result = validateUser($username, $password);
if (!$result) {
// something went wrong, deal with it
} else {
echo htmlentities($result);
}
Note that this is still far from ideal code, but I hope you get the idea.
if ($userName or $userPassword = null)
should be
if (($userName == null) or ($userPassword == null))
However, I suspect you don't actually want to check if these are null. Assuming you're filling these variables from input fields, an empty text field is NOT null; it's an empty string. You can do !empty($userName) to check for an empty text field.
If you want to check two variable in single conditional, you have to write out each check separately - ($userName and $userPassword != null) won't work the way you expect it to, it should be ($userName != NULL and $userPassword != null).
Also, when you're checking if a variable is equal to something, you have to use the == operator. Otherwise, you're assigning the variable to that value, which is pretty much never what you want to do.
You might need the below. Very basic, though.
isset($_POST['username']) or die('username not given'); //#1
isset($_POST['password']) or die('password not given'); //#2
$escapedUsername = mysql_real_escape_string($_POST);
$result = mysql_fetch_array(mysql_query("SELECT count(userName) FROM logininfo WHERE userName = '$escapedUsername'"))
if ($result){
echo "Hello, $escapedUsername"; //#3
}else{
echo "Invalid Password"; //#4
}
But may I suggest something different. Will require you to change some portions of your app though.
have this file as some login.php
Use this for login/password reset/register/etc..
have a GET to differentiate between these requests
Use AJAX.
In that case replace the following something like the below:
#1 : die('{"RESULT":"ERROR", "DESC" : "USERNAME NOT GIVEN"}');
#2 : die('{"RESULT":"ERROR", "DESC" : "PASSWORD NOT GIVEN"}');
#3 : die('{"RESULT":"ERROR", "DESC" : "INVALID USERNAME/PWD"}');
#4 : die('{"RESULT":"SUCCESS", "DESC" : "$escapedUsername"}'); // can also use json_encode($result) here.
These are just my suggestions. I have assumed mysql doesnt give you any problem. :-)