I have a simple script to allow a user to register an account. A warning about $_POST indexes being undefined occurs on the following two lines of the script that receives the form submission:
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
I've tried a var_dump($_POST), and those indexes are clearly defined. Furthermore, the following line works, and enters the information you would expect:
$id = $this->flexi_auth->insert_user($email, $username, $password, false, false, true);
If $_POST['email'] and $_POST['username'] were really undefined, there's no way that line would work. The user created in the database is with the username and email entered on the submission form. That being the case, why is it throwing obviously false warnings?
Try something like this.
$email = '';
$username = '';
if(!empty($_POST['email']) && !empty($_POST['username'])
{
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
}
It is possible that they could be undefined, hence the notices.
CodeIgniter has a function to help handle this, it returns FALSE if the item does not exist:
$this->input->post('item');
So, instead of:
$_POST['email']
You can use:
$this->input->post('email')
and so on...
You'll probably also want to check that you have valid values (not empty, for example) before creating a new user.
Related
ok, so i have a little issue here with php. I know there are alot of similar questions, but ones i found did not help.
I dont want to use anything more like javascript or something. I got mysql set up, there are 3 columns ID username and password.
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("login");
$result = mysql_query("select * from users where username='$username' and password= '$password'")
or die("failed to query DB".mysql_error());
$row = mysql_fetch_array($result);
if ($row['username'] == $username && $row['password'] == $password) {header(suc.html);
die();}else{header("Location: fail.html");die();}
?>
This code, it works but when i dont fill in any details and press submit too, it gets me to the suc.html which shows successful login. Now i want to make the following:
I'll make ID's similar to each individual html's names, then the php will go match the ID number with the file name in the directory, and show the page for the respective user.
like lets say user1.
Login userlol password 123 ID user1 file user1.html
then what code to use that it goes and matches the ID user1 with the .html name, then redirects the user to their own custom page. Is there a way? Kinda getting started with php ,so cut some slack please :)
p.s i know these codes are older php codes, but anything works for me personally.
You are getting that sort of behaviour because when a username and password is not submitted, their respective values evaluates to null and your SQL query is successful but returns 0 rows thereby making your $row['username'] and $row['password'] to be null. In general, your $row['username'],$row['password'],$username,$password would all be equal to null which fulfills all the requirements to redirect to "suc.html"
To solve this problem, simply check if mysql_num_rows($result)==1 because usually, a successful login would return just one row due to unique usernames.
But
I would not advice you to continue with deprecated mysql and SQL Injection susceptible logic. Please allow me to rewrite your logic as follows:
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
// You don't have to escape or sanitize user inputs if you use Prepared Statement plus sanitizing user password is highly discouraged.
// $username = stripcslashes($username);
// $password = stripcslashes($password);
// $username = mysql_real_escape_string($username);
// $password = mysql_real_escape_string($password);
// Initiate a PDO connection and set your error mode to exception.
$conn=new pdo("mysql:host=localhost;dbname=login;","root","",array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
try{
// Prepare your query and replace all values with ? which would be provided as an array in execute(); I added limit 1 to make sure we are getting a maximum of one row from our query.
$result_stmt = $conn->prepare("select * from `users` where (`username`=? and `password`=?) limit 1");
$result_stmt->execute([$username,$password]);
// fatch() would return a single row just like mysql_fetch_array or mysql_fetch_assoc while fetchAll() would return all rows.
$result=$result_stmt->fetch();
if(count($result)==1){
// There is no need to check this again because your query to the database already did.
// if ($row['username'] == $username && $row['password'] == $password)
// Redirect users to the same page but identify each user through session (recommended)
header("location:suc.html");
}else{
header("location:fail.html");
}
}catch(Exception $e){
echo $e->getMessage();
}
?>
If I set
$USER = (isset($_POST['username']));
with php have 0 errors BUT in db put '1' instead the it to user write on HTML input and if I put
`$USER = $_POST['username'];`
Notice: Undefined index: username in __FILE__ on line 5
this set in the db what user put in the HTML input, but get error
(Sorry for my bad English; I know it is so bad!)
Try below :-
if (isset($_POST['username'])) {
$USER = $_POST['username']);
}
As, isset() is a function which gives return values in boolean i.e; 1 or 0
When you do this :
$USER = (isset($_POST['username']));
You check if $_POST['username'] is set AND you set this result (true or false) into $USER
What you want to do is :
if (isset($_POST['username'])) // You check if username is set.
{
$USER = $_POST['username'];
// your query
}
else
{
// return error if isn't set.
}
First of all isset() is a checking operand type and returns 1 if true and 0 if false depending on something exist or not. I guess you got why this always output and saved 1 in the db.
So it should be $USER = $_POST['username'];
But the reason why you are getting Notice: Undefined index: username in __FILE__ on line 5 because when you first enter that page, it dont post anything. So as a matter of fact $_POST['username'] is unknown to php at that time. When you are submitting the form then php will know and recognize $_POST['username'].
So you need to put a check like below:
if(isset($_POST['username'])){
echo $_POST['username'];
}
Hope it will work and make you understand the problem.
Regards.
In a registration form, where you can type username password and name for example, would this:
if (isset($username) && isset($password) && isset($firstname))
be the same as: if (isset($submit))?
Side notes: $username = $_POST['username']; and so on. $submit = $_POST['submit'] - when submit button is pressed
No, if(isset($submit)) would only tell you if the form was submitted or not.
You should probably use if(isset($username,$password,$firstname)).
If you are doing $username = $_POST['username'] then $username will always be set.
Speaking of $_POST['username'] and $_POST['submit'] - no, they aren't the same. However, in usual scenario, to check only one field is enough - so, you can roughly assume they are the same.
I am just working with username-to-password validation scripting, and I don't want to mess with database connections just yet. So I'm just putting certain test emails and passwords into some arrays, then working at validating against those arrays.
I'm getting stuck on the best way to do this, because I actually want to put more pertinent data into each "user" array.
Here's what I've started so far, and you'll see what I'm shooting for:
<?php
$email = $_POST['email'];
// test emails
$logins = array('john#smith.com'=>'123456','jane#smith.com'=>'123456');
if (!array_key_exists($email, $logins)) {
echo "that email does not exist, stop here.";
}else{
echo "email exists, continue...";
}
?>
And this works fine, since it's simple, but as I needed to add more options into the array, the method changed to this:
<?php
// tester accounts
$user1 = array('email'=>'john#smith.com','password'=>'123456','fullname'=>'john smith','handle'=>'johnny');
$user2 = array('email'=>'jane#smith.com','password'=>'123456','fullname'=>'Jane Smith','handle'=>'janeyS');
// credentials passed from a form
$email = $_POST['email'];
$pass = $_POST['pass'];
/* not quite sure how to validate the $user arrays */
?>
And the user arrays probably will grow with more things related to that user, obviously.
But I'm used to working with database connections, and not straight from PHP arrays.
Can someone throw me a little advice on a simple email/pass validation from multiple php arrays like what I just did above? Or perhaps there's a better method?
Turn your users into a $users array.
$success = (bool) array_filter($users, function($user) use ($email, $pass) {
return $user['email'] == $email AND $user['password'] == $pass;
});
This code will loop through all the users in the $users array and return the subset which matched for username and password (should be either 0 or 1).
Because an empty array is falsy in PHP, casting it to Boolean should give the correct result. You could skip this if you wanted, dependent on the context of using it.
$username = $_POST["user_name"];
$password = $_POST["user_password"];
$type = $_POST["user_type"];
$query = "SELECT * FROM users WHERE user_name='$username' AND user_password='$password' AND
user_type='$type'";
When run, I get an error message that states that the first three lines of code have undefined indexes. Could someone help me figure out what went wrong here and how to fix it?
if(isset($_POST["username"]) && isset($_POST["user_password"]) && isset($_POST["user_type"])){
$username = $_POST["user_name"];
$password = $_POST["user_password"];
$type = $_POST["user_type"];
$query = "SELECT * FROM users WHERE user_name='$username' AND user_password='$password' AND
user_type='$type'";
}
else{
// required value is missing
}
When you use $_POST you must check that the required values are in $_POST in not. So you should use isset()
Well we can't see the contents of your $_POST array, but likely your form is not posting correctly, or you have misnamed your input fields, because the "user_name," "user_password," and "user_type" indexes of the $_POST array do not exist, according to the error.
Could you post the form code? Or echo $_POST and tell us what the output contains?
Change your code so it checks whether it's there or not
$username = iseet($_POST["user_name"]) ? $_POST["user_name"] : '';
$password = isset($_POST["user_password"]) ? $_POST["user_password"] : '';
$type = isset($_POST["user_type"]) ? $_POST["user_type"] : ;
//NOTE - You have an sql injection vulnerability in the below code
$query = "SELECT * FROM users WHERE user_name='$username' AND user_password='$password' AND
user_type='$type'";
Always check whether your indices are set or not.
Also, don't insert array values directly into your SQL like that. At least use mysql_real_escape_string or consider using MySQL PDO
http://php.net/manual/en/function.mysql-real-escape-string.php