Why isset is printing 1? - php

Why is this line printing 1(true) and not the username variable?
$username = isset($_POST['username']);
$username = $connection->real_escape_string($username);
print_r($username);
and how can I use isset to make a mysqli query?

You are assigning 1(true) to $username. isset answer to: 'is that variable set?'.
try with :
if (isset($_POST['username'])){
$username = $_POST['username'];
$username = $connection->real_escape_string($username);
}

if (isset($_POST['username'])) {
$username = $_POST['username'];
}
Normally we do this to check if post variable is set, and if it set, we assign the value to another variable which we will pass to the query, in this case.

Related

Is there a way to call a variable that is initialised later in PHP?

I have this piece of code:
session_start();
$_SESSION["username"] = 'bob';
echo $_SESSION["username"];
if ($_SERVER['REQUEST_METHOD']=='POST') {
$username = $_POST['username'];
$password = $_POST['password'];
I want to replace where it says 'bob' with $username instead (which is initialised in line 6).
Is this possible?
Use assigning by reference, requiring only that the $username variable is declared prior to assigning it to $_SESSION['username']:
$username = 'bob';
$_SESSION["username"] =& $username; //mind the &
$username = 'foo';
echo $_SESSION["username"]; // 'foo'
That said, I recommend against an approach like this. Consider using $_SESSION["username"] = $_POST['username'] instead.
No, you can't do that.
But maybe you can change your code to:
session_start();
$_SESSION["username"] = 'bob';
if ($_SERVER['REQUEST_METHOD']=='POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// code
}
echo $_SESSION["username"];

Unable to login in PHP

Hei guys, I have been working around to figure out what's wrong here but unable to identify it. I am creating a login page and here the code. Could you please help me to identify it?thnx
<?php include 'db.php'; ?>
<?php
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
$query = "SELECT * FROM tbl_users WHERE username = '{$username}' ";
$login_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($login_query)) {
$db_username = $row['username'];
$db_password = $row['password'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$email = $row['email'];
$db_role = $row['role'];
if ($username !== '{$db_username}' && $password !== '{$db_password}' ) {
header("Location: ../index.php");
}elseif ($username == '{$db_username}' && $password == '{$db_password}') {
header("Location: ../admin");
} {
header("Location: ../index.php");
}
}
}
?>
Why are you using $username !== '{$db_username}' while you can use $username !== $db_username directly? It isn't necessary to use quotes when you are comparing strings without any modification...
Also, if you want to parse variables within quotes, DON'T use single quotes, because them will not be parsed by PHP. Using single quotes you are always comparing $username with '{$db_username}'. Instead, use double quotes which will be parsed by PHP.
Here's an example of what i'm saying:
<?php
$db_username = 'admin';
$username = $_POST['username']; // asumming it is 'admin'
if($username == '{$db_username}') // will be false because 'admin' != '{$db_username}'
if($username == "{$db_username}") // will be true because 'admin' == 'admin'
if($username == $db_username) // same as before but cleaner (and a little bit faster, maybe?)
?>
I did ask whether or not usernames were unique in the db - if they are then there would be no need for a loop and using a loop would mean that on the first iteration into the recordset the logic tests ( that were failing anyway ) would run and the redirection would occur without any further processing.
Perhaps the following might help.
<?php
if( isset( $_POST['login'], $_POST['username'], $_POST['password'] ) ) {
include 'db.php';
/*
Using prepared statements means you don't need to try to sanitize user input data prior
to executing the sql query in an attempt to prevent sql injection.
*/
$username = $_POST['username'];
$password = $_POST['password'];
/*
The original query returned many fields which were never used. When using `prepared statements` and binding
the results you need to specify a binding for all fields returned - hence returning only two fields.
*/
$query = "SELECT `username`,`password`,`role` FROM `tbl_users` WHERE `username` = ? ";
$stmt = $connection->prepare( $query );
if( $stmt ){
$stmt->bind_param( 's', $username );
$stmt->execute();
$stmt->store_result();
/* Capture db results into variables to use in logic test below */
$stmt->bind_result( $dbusername, $dbpassword, $dbrole );
$stmt->fetch();
$stmt->close();
$connection->close();
/* possible endpoints for redirection */
$redirect = 'login.php';
if( $username == $dbusername && $password == $dbpassword ) {
/* What values are held in `role` field? assumed "admin" */
$redirect = $dbrole == 'admin' ? 'admin' : 'index.php';
}
exit( header( "Location: ../{$redirect}" ) );
}
}
?>
A login generally need a session to store informations about your status.
So, first thing to do is initialize the sessions, put this code at top of the page, before all:
session_start();
After this, a few considerations must be done:
I'll expect that the field username is unique: put a unique index on your db on this field to ensure the unicity
Change your query, putting the password check inside it
Fetch only one row, without using a while: if the username is unique you will get only one row. The password can be checked inside query as said before, so if query dest not return rows, user is not registered or credentials are wrong.
If you get results, then you can check the role and redirect to the right page.
If you can authenticate the user, set a session like:
$_SESSION['user'] = array(
'is_logged' => $user_id,
'username' => $username,
'role' => $role,
'email' => $email,
);
Every time you load a page, check if(empty($session['user']['is_logged'])) { .... }. If true, the user is not logged.
Don't save user password as plain text, but hash it! You can use MySQL PASSWORD() function.
$username !== '{$db_username}' && $password !== '{$db_password}'
This code will not work, and probably is the main problem, single quotes are not parsed by PHP, use $username == $db_username && $password == $db_password instead (if you do this check inside the query, this code is not neeeded anymore)

Unable to Login when passing credentials in a web url

Creating a user login, when I use username and password within PHP file then, I am getting Done as user exists. Which is GOOD
<?php
.....
/*** for sample */
// $_POST["username"] = "sun";
// $_POST["password"] = "live";
$username = $_POST['username'];
$password = $_POST['password'];
$strSQL = "select * from test_users where username = '".$username."' and password = '".$password."' ";
$objQuery = mysql_query($strSQL);
$intNumRows = mysql_num_rows($objQuery);
if($intNumRows==0)
{
echo "Not Done" ;
}
else
{
echo "Done" ;
}
mysql_close($objConnect);
?>
But, when I pass these values in web url, I am always getting, Not Done as message. WHY
http://mydomain.info/retrofit_user/login.php?username=sun&&password=live
You have to ampersands in your query strings, that's an issue.
login.php?username=sun&&password=live
Not to mention that POST and GET are different method.
You can use $_REQUEST two access both.
You are getting your variables in PHP as $_POST.
$username = $_POST['username'];
$password = $_POST['password'];
But in your link, it's the $_GET method.
login.php?username=sun&password=live
So, it should be:
Also, remember to prevent MySQL Injection, using mysql_escape_string().
$username = mysql_escape_string($_GET['username']);
$password = mysql_escape_string($_GET['password']);
Please use MySQLi instead as MySQL has already been deprecated.
Hope this helps, thanks!
try this for more read http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
$username = $_GET['username'] ?? $_POST['username'] ?? 'sun';
$password = $_GET['password'] ?? $_POST['password'] ?? 'live';

Parse Error on isset? [PHP]

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
}

i am getting errors im running on PHP

$submit = $_POST['submit'];
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = strip_tags($_POST['confirmpassword']);
$date = date ("Y-m-d");
i get **"Notice: Undefined index"**
but when i do this
if(isset($_POST['submit']))
{
$submit = $_POST['submit'];
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = strip_tags($_POST['confirmpassword']);
$date = date ("Y-m-d");
}
the undefined index gets fixed but Notice: Undefined variable: submit is my new error why is that???
It's notice because you want to use variable which is not set you can fix it by checking it with isset() function
$submit = null;
if(isset($_POST['submit'])
$submit = $_POST['submit'];
or with short syntax
$submit = isset($_POST['submit']) ? $_POST['submit'] : null;
same applies to other variables passed via $_POST
Try with
$submit = isset ( $_POST ['submit'] ) ? $_POST ['submit'] : null ;
Change:
if(isset($_POST['submit']))
In:
if(isset($_POST) && isset($_POST['submit']))
This is due to no value for 'submit' being passed by POST.
Check if $_POST['submit'] is empty prior to assigning its value to a variable.
Do You have in your form
<input type = 'submit' name = 'submit' />
if you have placed only
<input type = 'submit' />
It will not work
Changed it to start with this
<?php
if(isset($_POST['submit']) != "")
{
$submit = $_POST['submit'];
......
}
?>

Categories