I'm quite new to HTTP/PHP coding and I'm having a little trouble with isset in PHP.
This is my current code below, it's supposed to check if the username and password is Admin and Password, if so, it will echo them some info.
However, it doesn't work. There is no errors, it just accepts all usernames and passwords.
$username = isset($_POST['password']);
$password = isset($_POST['username']);
$date = date('d-m-y');
$time = date('h:m:s');
$day = date('l');
if($username == 'Admin' and $password == 'Password')
{ //echo bla bla bla..
isset just checks if a variable is set. Your usercase, on the otherhand, needs to check the actual values:
if(isset($_POST['username']) and
$_POST['username'] == 'Admin' and
isset($_POST['password']) and
$_POST['password'] == 'Password') {
// echo...
In order to use isset() being passed in your variable(s) as you have it now, you need to use a ternary operator.
I.e.:
$username = isset($_POST['password']) ? $_POST['password'] : "default";
Consult Example #3 and others on
http://php.net/manual/en/language.operators.comparison.php
You can read the use isset in php isset , where it appears that isset has a value of true or false . so the value of the variable $username be true or false , so also in the variable $password. So if you will check value of the POST action you can use
if(isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$date = date('d-m-y');
$time = date('h:m:s');
$day = date('l');
if($username == "Admin" && $password == "Password")
{ //echo bla bla bla..
}
}
try this,
if(isset($_POST['password']) && isset($_POST['username'])){
$username = $_POST['password'];
$password = $_POST['username'];
$date = date('d-m-y');
$time = date('h:m:s');
$day = date('l');
// code here
if($username == 'Admin' and $password == 'Password'){
// Okay
}else{
// not Okay
}
} else {
// error
}
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.
Hey guys I am new to PHP and trying to figure out how to implement $_session in a very basic login system:
<?php
session_start();
include 'dbconn.php';
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
$row = $result->fetch_object();
if($username == "$row->username" && $password == "$row->password") {
$_SESSION['loggedin'] = "$username";
header('Location: admin.php');
} else {
header('Location: index.php?msg=wrong-username-or-password');
}
The problem is that when if I use local variables like:
$admin_userName = 'admin';
$admin_password = '1234';
and then making the comparison
if($username == "$adminusername" && $password == "$adminpassword") {
$_SESSION['loggedin'] = "$username";
header('Location: admin.php');
The $_session works perfect. But when I use this:
if($username == "$row->username" && $password == "$row->password") {
$_SESSION['loggedin'] = "$username";
header('Location: admin.php');
The session does not work. Without session the above statement works perfectly!
login.php
<?php
session_start();
include 'dbconn.php';
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
$row = $result->fetch_object();
if($username == $row->username && $password == $row->password) {
$_SESSION['loggedin'] = $username;
header('Location: apptify.php');
} else {
header('Location: index.php?msg=wrong-username-or-password');
}
logout.php
<?php
session_start();
unset($_SESSION['loggedin']);
header('Location: index.php');
?>
I am really lost, any help is appreciated.
The problem is that when if I use local variables like:
$admin_userName = 'admin';
$admin_password = '1234';
and then making the comparison
if($username == "$adminusername" && $password == "$adminpassword") {
The problem is that, you're using:
$admin_userName = 'admin';
$admin_password = '1234';
then using:
if($username == "$adminusername" && $password == "$adminpassword")
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
You forgot the underscores and not matching the variables lettercase.
Variables are case-sensitive.
if($username == "$admin_userName" && $password == "$admin_password")
My test script, with success:
<?php
session_start();
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME)
or die(mysqli_connect_error());
$_POST['username'] = "John";
$username = $_POST['username'];
$_POST['password'] = "Johnny";
$password = $_POST['password'];
$_SESSION['loggedin'] = "$username";
echo $username; // echo'd John
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $con->query($sql);
$row = $result->fetch_object();
if($username == "$row->username" && $password == "$row->password") {
$_SESSION['loggedin'] = "$username";
// header('Location: admin.php');
echo "Match!";
} else {
// header('Location: index.php?msg=wrong-username-or-password');
echo "No match.";
}
I need to point out that:
You should look into using mysqli with prepared statements, or PDO with prepared statements, they're much safer.
In regards to password storage.
If you're not already hashing passwords rather than what may be a plain text method you may be using, I suggest you look into CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
It should be without quotes:
if($username == $row->username && $password == $row->password) {
$_SESSION['loggedin'] = $username;
header('Location: index.php');
}
I doing simple log in system. Username and passwords are saved in txt file (array format).
When I m log in I got "Fatal error: Maximum execution time of 30 seconds exceeded". here is my code. Thank for any hint.
$clean = array();
if(isset($_POST["submit"])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$user = isset($_POST['username']);
$pass = isset($_POST['password']);
$toread = fopen('filewriting.txt','r');
while(!feof($toread))
{
$username = isset($clean['username']);
$password = isset($clean['password']);
}
if($user == $username && $pass == $password)
{
$_SESSION['sess_user']=$user;
/* Redirect browser */
header("Location: page2.php");
}
} else {
echo "Invalid username or password!";
}
} else {
echo "All fields are required!";
}
The below lines are not correct
$user = isset($_POST['username']);
$pass = isset($_POST['password']);
isset() returns true or false and hence the variables will be set to true or false
http://php.net/manual/en/function.isset.php
You have same
$username = isset($clean['username']);
$password = isset($clean['password']);
And values of $user and $pass is setting as true or false in all cases and further down the line its failing. Correct these first.
I trying to create a simple user registration, that saves data into a database.
But I have an error I cant defeat.
Its says
Notice: Undefined index: pass_conf in C:\wamp\www\book\reg.php on
line 27
But my pass_config seems to be right.
Any ideas whats the problem ? this is the php code
/// Updating my code, this one works
<?php
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "pagination";
$connection = mysql_connect($host,$dbuser,$dbpass);
$db = mysql_select_db($dbname,$connection);
/*
$name = $_POST["username"];
$pass = $_POST["password"];
$pass_conf = $_POST["pass_conf"];
$email = $_POST["email"];
$ip = $_POST["ip"]; */
$name = isset($_POST['username']) ? $_POST['username'] : 0;
$pass = isset($_POST['password']) ? $_POST['password'] : 0;
$pass_conf = isset($_POST["pass_conf"]) ? $_POST["pass_conf"] : 0; // 0 equals your default off value.
$email = isset($_POST['email']) ? $_POST['email'] : 0;
$ip = isset($_POST['ip']) ? $_POST['ip'] : 0;
if($name == false || $pass == false || $pass_conf == false || $email == false){
echo "Please fill in all the required fields.";
};
if($pass != $pass_conf){
echo "Passwords do not match.";
}else {
$connection = mysql_connect($host,$dbuser,$dbpass);
$db = mysql_select_db($dbname,$connection);
$sql = "INSERT INTO user (username,password,email,ip) VALUES ($name, $pass, $email, $ip)";
$result = mysql_query($sql);
echo "Thank you for your registration to Our Site";
};
?>
I Will add my form.php also since I got a request for it.
<?php
$IP = $_SERVER['REMOTE_ADDR'];
?>
<form name=reg action=reg.php method=post>
Username : <input type=text name=username><br>
Password : <input type=password name=password><br>
Confirm :<input type=password name=pass_conf><br>
Email : <input type=text name=email><br>
<input type=hidden name=ip value='<?php echo $IP ?>'>
<input type=submit value='Register'>
</form>
Thanks
instead of $x = $_POST['x'] use $x = isset($_POST['x']) ? $_POST['x'], null.
Or use:
function post($key, $default = null) {
return isset($_POST[$key]) ? $_POST[$key] : $default;
}
First off, good job on using E_ALL while creating your app! Your "pass_conf" value is probably a checkbox that isn't selected when submitting your form and so no value is ever sent. A simple:
$pass_conf = isset($_POST["pass_conf"]) ? $_POST["pass_conf"] : 0; // 0 equals your default off value.
That message means that the value you are trying to get is not present in the array. So either the value is not filled in or is not passed thru correctly (check the fields name, it has to be exactly the same).
Have you tried:
if (array_key_exists("pass_conf", $_POST))
$pass_conf = mysql_real_escape_string($_POST["pass_conf"]);
else
$pass_conf = null;
$sql =
"INSERT INTO events (username, password, email, ip) " .
"VALUES ('{$name}','{$pass}','{$email}','{$ip}')";
See this question that I asked for my full example and scroll down to how it was answered by user dldnh; it's similar to yours, so maybe it will help you: [link] Undefined index notice
I can't figure out what is wrong with program. The password I know is correct but for some reason I am receiving an error saying it is incorrect.
here is my signup.php
$UserName = $_POST['UserName'];
$password = $_POST['password'];
$msd5Password = $md5[$password];
$email = $_POST['email'];
if ($UserName == null || $password == null || $email == null) {
echo 'Please Fill In All The Values';
}
else {
$sql = mysql_query("SELECT * FROM login WHERE email = '$email'");
$numrows = mysql_num_rows($sql);
if($numrows !=0)
{
die("There already is an account created with the email you entered.");
}
else
{
mysql_connect("localhost", "root") or die (mysql_error);
mysql_select_db ("thereview");
mysql_query("INSERT INTO login (UserName, password, email) VALUES ('$UserName', '$md5Password', '$email')")
or die(mysql_error());
header("Location:login.php");
}
}
And here is my login.php
session_start();
$UserName = $_POST['UserName'];
$password = $_POST['password'];
if($UserName == null|| $password == null) {
echo 'Please fill in UserName and Password';
}
else{
mysql_connect("localhost", "root") or die (mysql_error);
mysql_select_db ("thereview");
$query = mysql_query ("SELECT * FROM login WHERE UserName = '$UserName'");
$numrows = mysql_num_rows($query);
if($numrows != 0) {
while($row = mysql_fetch_assoc($query)) {
$dbEmail = $row['email'];
$dbUserName = $row['UserName'];
$dbPassword = $row['password'];
$dbId = $row['id'];
}
if($UserName = $dbUserName && md5($password) == $dbPassword) {
$_SESSION['UserName'] = $dbUserName;
$_SESSION['email'] = $dbEmail;
}
else {
echo 'UserName or Password is incorrect';
}
}
else {
echo 'User does not exist, Create an Account';
}
}
Looks like you have a typo here:
$msd5Password = $md5[$password];
should probably be:
$md5Password = md5($password);
Keep in mind MD5 is not good for password security any longer and you have VERY POOR security for this script, open to injection and other issues.
Are you sure about this?
$msd5Password = $md5[$password];
I think it should be:
$md5Password = md5($password);
$msd5Password = $md5[$password]; should probably read: $md5Password = md5($password); (careful about the details - dollars and parenthesis)
$UserName = $dbUserName should probably be $UserName == $dbUserName
In the sign up script you write $md5$password
I'm not strong in php, but shouldn't that be md5($password) as you write in the login script?
if($UserName **=** $dbUserName && md5($password) == $dbPassword)
will always give you false...
Try $UserName **==** $dbUserName instead.
Try this. You need to put parenthesis around these commands to make sure that its a test of only those values. Also where you have $UserName = $dbUserName you need to have it be == instead of =. Otherwise it will always be set to true rather then be testing it.
if(($UserName == $dbUserName) && (md5($password) == $dbPassword))
Also, at the top the code you have is this:
$msd5Password = $md5[$password];
You have two typos in there. First of all your variable later on is md5Password so you need to remove the s. Also the syntax for md5 is md5($password). Finally md5 is a function not a variable so you don't need the $.
Correct Syntax:
$md5Password = md5($password);
I hope this is helpful!