Are these the same? - php

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.

Related

Header won't work with conditions

I have been trying to get a page working for a number of days now, and there doesn't seem to be much help from the "related" questions on this site.
I have made a signup.php page, which has a form for inputting user credentials to signup up for the site I am building, when the form is filled out and the user presses the 'submit' button, the form uses the action "signupsuccess.php" which has all of the php code for inserting the credentials into the database, and then redirects the user to the "Login.php" page.
My problem:
I have written code to say that if the user has not put in any data for one of the fields in the form, then they are brought back to the signup.php page by using this code:
<?php
if(!isset($_POST['fname'])&&($_POST['lname'])&&($_POST['email'])&&($_POST['pass'])){
header('Location:Signup.php');
exit;
}
else{
$host = "localhost";
$user = "******";
$password = "******";
$conn = mysql_connect($host, $user, $password);
$db = mysql_select_db('*****', $conn);
if(! get_magic_quotes_gpc() )
{
$fname = addslashes ($_POST['fname']);
$lname = addslashes ($_POST['lname']);
$email = addslashes($_POST['email']);
$pass = addslashes($_POST['pass']);
}
else
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass= $_POST['pass'];
}
$query = mysql_query("select * from users where pass='$pass' AND email='$email'", $conn);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$errors[] = 'That user already exists, try another email';
}else
{
$sql = "INSERT INTO users ".
"(fname,lname, pass, email) ".
"VALUES('$fname','$lname','$pass','$email')";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
}
mysql_close($conn);
?>
But the header() just won't bring the user back when they haven't put anything in to the fields. Is there anything I am doing obviously wrong or can anyone help me sort out the redirection of the user if they haven't entered anything.
Your if statement is incorrect. If you're just trying to check to see if those variables are set you need to call isset() on all of them.
You can do this with individual calls to isset() or all in one call.
if(!isset($_POST['fname'],$_POST['lname'],$_POST['email'],$_POST['pass'])){
header('Location:Signup.php');
exit;
}
FYI, you are wide open to SQL injections. addslashes() does not prevent SQL injections. Also, the mysql_* funcstions are obsolete and you should not be writing new code using them. Look into mysqli or PDO instead.
I don't think you really need a redirection, you probably should overcome this issue from the frontend, maybe a js validation could do the trick and is way simpler.
1.- change the action of submit to run the function "validate()"
2.- create the function that will be something like:
$(document).ready(function(){
function validate(){
if ($.trim($("#inputid").val()) == ""){
$(this).css('border', '2px solid red');
} else if ($.trim($("#inputid2").val()) == "") {
$(this).css('border', '2px solid red');
} else if ($.trim($("#inputid3").val()) == "") {
$(this).css('border', '2px solid red');
} else {
submit();
}
}
});
Where '#input?' is the selector for the input you want to validate and null is the value that you want to avoid, in this case, no value, just empty input. Then if all the inputs are filled it will execute submit() function which you should create to do whatever he has to.
Note: This kind of selectors are for jquery so you must include it in your code as well, put this in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
Note 2: This is the frontend approach. I don't know if this is convenient but at least is an option and helps.
Good luck!
Your if statement was the problem. because the isset was only affecting
$_POST['fname'],
the if statment was being skipped so
header('Location:Signup.php')
was not being reached.
I like to put
echo 'test';
in my code while i am testing it and move it around the code. That way, if it is not echoing 'test', i know that the code isn't even being reached. That could have helped you in this case, showing you that the problem wasn't the header, it was the if statement. Also, consider using PDO for mysql connections. It is more secure against mysql injections.
Your condition (if corrected according to the previous answers) would still always result in the else case. Since you are checking for $_POST fields, those will always be present. isset()returns false if the variable is not set (but it is: it comes from your form) or is NULL (which it is not: it contains an empty value). So, isset() will return true fopr every field. What you need is, for each field: if (empty(trim($_POST['fname']))) || ... )empty() returns false when the variable is not set or empty (i.e NULL, an empty string, 0, 0.0, false, etc, see here: http://php.net/manual/en/function.empty.php)Plus, you need to do something about the deprecated mysql_functions and your vulnerability to attacks.

PHP warns of undefined index when the index is clearly defined

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.

PHP login script without using database

I use PHP code below for login without using database.
It redirects to home.php in two cases:
1. When I input correct username and password
2. When I input any character/s as username (except real username) and leave password textbox blank.
In other cases, except the second, code works properly.
How to make the code work properly in the second case?
<?php
session_start();
$userinfo = array(
'user1'=>'pass1',
);
if(isset($_GET['logout'])) {
$_SESSION['username'] = '';
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(isset($_POST['username'])) {
if($userinfo[$_POST['username']] == $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
header('Location: home.php');
}else {
header('Location: login.php');
}
}
?>
You could change
if($userinfo[$_POST['username']] == $_POST['password']) {
to
if(isset($userinfo[$_POST['username']]) && $userinfo[$_POST['username']] == $_POST['password']) {
The reason it is failing is because if the username entered is not in your array, $userinfo['idontexist'] returns null, which evaluates to an empty string, so you are ultimately comparing null == '' which is true.
With the modified code, you are first checking to make sure the username entered actually exists in your array. If it does not, the password check is never run and they are redirected to the login page.
You could alternatively use === to compare the two, but a new vulnerability could be introduced where someone edits the form and removes the password field so that $_POST['password'] becomes null and then entering a non existent user would end up comparing null to null which would allow them to log in. Use the isset check to make sure the username exists in the array, then compare the password.
Just for the sake of security, you may want to check to see if the password was empty and skip the password check and immediately return to the login page.
EDIT:
To allow the 2 cases you want, try:
if ((isset($userinfo[$_POST['username']]) && $userinfo[$_POST['username']] == $_POST['password']) || (!isset($userinfo[$_POST['username']]) && strlen($_POST['username']) > 0 && $_POST['password'] === '') {
This checks if the username is in the array, if so make sure the password matches, OR check that the username is NOT in the array, and make sure the password is empty.

$_SESSION equals value from database?

when a person logs into my site i need to check a value in a database for their roleid, and dependent on that i need to allow/deny access to a page.
I have this code but it says that the $_SESION variable 'Access' is undefined, i cant see why?
$email = mysql_real_escape_string($_POST['email']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM person WHERE email = '" . $email . "' AND password2 = '" . $password . "'");
if (mysql_num_rows($checklogin) == 1) {
$row = mysql_fetch_array($checklogin);
$roleid = $row['roleid'];
$_SESSION['Email'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['Access'] = $roleid;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='2;index.php' />";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
This is the if statement that is saying the session in undefined:
if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Email']) && $_SESSION['Access'] == '2')
EDIT
Sorry, should have mentioned, session_start() is called in my base.php file which is included in this file.
EDIT
I don't know what the problem is, i can assign the variable $email to the other session variable and display that so the user can see who they are logged in as?
Does anybody have any suggestions? Both of the other session variables work fine.
From the code you have posted, you are missing session_start()
If this is not within a framework that performs this for you, it must be called on every page that will utilize the session before any session calls are made.
I assume the error is occurring after the redirect, in your logic that is checking for it using isset() or empty(). Add session_start() to both pages before any session logic is performed.
EDIT:
Ok, you have session_start(). Can you print_r() your $_SESSION and check the output?
Also, the file you mention that runs the session start should be included in both files, as its necessary for setting and checking values from the session.
Make sure before running any empty() conditionals, you also run isset(). Empty does not check if the key is present.
EDIT AGAIN:
Is it possible your value for $y isn't coming out of the database as a single value? can you die() at that point, just printing the value of $y out to see what is output?
Just add another check to your if statement, !empty($_SESSION['Access'])
if (!empty($_SESSION['LoggedIn'])
&& !empty($_SESSION['Email'])
&& !empty($_SESSION['Access'])
&& $_SESSION['Access'] == '2')
Check the spelling of $row['roleid']. Is the field name in the database table EXACTLY like it ?
Change
SELECT * FROM person WHERE
to
SELECT roleid FROM person WHERE
see if it breaks... :-)
This might not be related to your problem but I think it's worth mentioning: Your username / password SQL statement can be dangerous. Although you escape the input variables it is usually better practice to do it this way:
$checklogin = mysql_query("SELECT * FROM person WHERE email='".$email."'");
$row = mysql_fetch_array ($checklogin, MYSQL_ASSOC);
if (mysql_num_rows ($checklogin) == 1 && $row['password'] == $password)
{
// you are logged in
}
else
{
// wrong email or password
}
Reason being is that your current statement only needs to return ANY row in your table whereas this statement needs to return one specific row in the table.

Password reset script only fires half the time

I had an inefficient piece of code for resetting passwords based on a user entering either their username or their email address. The PHP script branched depending on the identifier used. I collapsed it into one which now works if the user enters their username but not if they enter their email address. Here is the salient code:
$identifier = isset($_POST["username"])?"username":"email";
$ident = isset($_POST["username"])?trim(mysqli_real_escape_string($mysqli,(check_chars_username($_POST["username"])))):trim(mysqli_real_escape_string($mysqli, (check_chars_email($_POST["email"]))));
//create and issue the query
$sql = "SELECT * FROM aromaMaster WHERE $identifier = '$ident'";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if(mysqli_num_rows($sql_res) == 0) {
//wrong login info
header("Location: password_reset_form.html/error=$ident");
exit();
}
$info = mysqli_fetch_array($sql_res);
$userid = $info["id"];
$username = stripslashes($info["username"]);
$email = stripslashes($info["email"]);
I have checked and doubled checked that the email form field is called email and it is. It's got me scratching my head. Particularly interesting is the header redirect. When I enter an email address and am redirected, the variable $ident appears empty.
As you've noted in your comment, you have to check for the username variable of the $_POST array to be empty.
It's also a good idea to check if the variable is even there in the first place in addition to and before you test against it being blank.
$identifier =
(isset($_POST["username"]) && !empty($_POST["username"])) ? "username":"email";
When you're sending your form across, all of the text input fields will come through, even if they're blank. Blank is not the same as empty. That's the reason the first part of the ternary operator is always true in your initial code.

Categories