Notice: Undefined index $_POST and mysql - php

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.

Related

php how to check if condition for unicode password

Iam new to php. I need to check whether newpassword(unicoded) variable is empty or null. If the value is a normal string, i could have checked as if($newpass){echo 'inside if'} but unforutnately, $newpassword value is getting a different value.
Below is the code: (which is already written by someone, i need to fix it)
if($newPassword != ""){
print_r('inside if');
$userdata["unicodePwd"] = $newPassword;
}
var_export($userdata);
I am sure there is something wrong in the code, but iam not able to fix it. Ultimately I should be able to check if $newPassword have some value, then it should go inside if. Sorry if its a dumb query.
if (isset($_POST['userpassword'])) {
// password sent from client
$userPassword = trim($_POST['userpassword']);
if ($userPassword !== '') {
// userPassword isn't empty, and spaces have been removed
$utf8Password = utf8_encode($userPassword);
}
}

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.

Notice: Undefined index: username in C:\xampp\htdocs\gpt\includes.php on line 3

I am a noob when it comes to PHP and other dev stuff. Anyways, I have tried to find a solution for it since the last two days. I searched almost everywhere. So, I was trying to integrate a design into a GPT script using XAMPP, but I am shown a bunch of errors each time I try to go to localhost/gpt where the files are. Top of the page shows this:-
"; }}}} if(isset($_SESSION['username']) && isset($_SESSION['password'])){ header("Location: members.php"); } ?>
Notice: Undefined index: username in C:\xampp\htdocs\gpt\includes.php on line 3
Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\xampp\htdocs\gpt\includes.php on line 3
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\gpt\includes.php on line 3
Notice: Trying to get property of non-object in C:\xampp\htdocs\gpt\includes.php on line 9
Notice: Trying to get property of non-object in C:\xampp\htdocs\gpt\includes.php on line 14
Notice: Trying to get property of non-object in C:\xampp\htdocs\gpt\includes.php on line 15
Notice: Trying to get property of non-object in C:\xampp\htdocs\gpt\includes.php on line 16
I tried adding error_reporting (E_ALL ^ E_NOTICE); to the top of config.php and includes.php and then the errors were reduced to this:-
"; }}}} if(isset($_SESSION['username']) && isset($_SESSION['password'])){ header("Location: members.php"); } ?>
Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\xampp\htdocs\gpt\includes.php on line 4
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\gpt\includes.php on line 4
I've also tried adding session_start(); to every page.
Anyways, these are the pages involved:-
config.php
<?
session_start();ob_start();
$hostname = "localhost"; //your hostname (normally localhost)
$data_username = "root"; //database username
$data_password = ""; //database password
$data_basename = "gpt"; //database name
$conn = mysql_connect("".$hostname."","".$data_username."","".$data_password."");
mysql_select_db("".$data_basename."") or die(mysql_error());
$bonuspoints=10; //bonus points awarded for new users
$mainpointsneeded=200; //max number of points needed before user can request voucher
?>
includes.php
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$fetch_users_data = mysql_fetch_object(mysql_query("SELECT * FROM `members` WHERE username='".$_SESSION['username']."'"));
$title= "My Voucher Geek"; //your site title
$yourdomain="http://localhost/gpt"; //your domain name where script is installed - do not use trailing slash
$tweetmsg="Get Amazon and ASOS gift vouchers for free at http://www.myvouchergeek.com"; //set text for tweet this button on homepage
$bonuspoints= 10; //amount of bonus points to give to users
$refer_points=2; //amount of points a user receives if one of their referred users completes any survey
$ref_id=$fetch_users_data->id;
if(isset($_GET['join'])){
$referral_ID = $_GET['join'];
$referral_string= "?join=".$referral_ID;
}
$membername= $fetch_users_data->username; //don't change
$memberpoints=$fetch_users_data->points; //don't change
$membersurveys=$fetch_users_data->completed_surveys; //don't change
$earnedpoints = $memberpoints - $bonuspoints;//if you want to display how many points user has earned (as opposed to bonus points)
$mainpointsneeded = 200; //total points needed before user can request a voucher
$pointsneeded= $mainpointsneeded - $memberpoints; //points left before they can request voucher
$contactemail = "YOUR_EMAIL_ADDRESS"; //contact form messages will be sent here
$requestemail = "THE_SAME_OR_ANOTHER_EMAIL_ADDRESS"; //request a voucher messages will be sent here
?>
index.php
<?
session_start();
include_once"config.php";
if(isset($_POST['login'])){
$username= trim($_POST['username']);
$password = trim($_POST['password']);
if($username == NULL OR $password == NULL){
$final_report.="Please complete both fields";
}else{
$check_user_data = mysql_query("SELECT * FROM `members` WHERE `username` = '$username'") or die(mysql_error());
if(mysql_num_rows($check_user_data) == 0){
$final_report.="This username does not exist";
}else{
$get_user_data = mysql_fetch_array($check_user_data);
if($get_user_data['password'] == $password){
$start_idsess = $_SESSION['username'] = "".$get_user_data['username']."";
$start_passsess = $_SESSION['password'] = "".$get_user_data['password']."";
$final_report.="<meta http-equiv='Refresh' content='0; URL=members.php'/>";
}}}}
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
header("Location: members.php");
}
?>
<?php include("includes.php");?>
<HTML>HTML_CONTENT</HTML>
Those are warnings that all mysql_* functions are deprecated and you shouldn't be using them anymore. If you don't want the warnings to show up you need to move your error reporting setting before you use the functions. Right now you have error_reporting (E_ALL ^ E_NOTICE); at the top of includes.php which is the last thing that gets called. You should move it to the top of config.php. Also with the error settings you have now you are showing all errors except Notices so warnings will still show up. If you want to hide warnings and/or deprecated error entries you need to change it to:
error_reporting(E_ERROR);
Also you should change these lines, you don't need the quotes:
//$conn = mysql_connect("".$hostname."","".$data_username."","".$data_password."");
//mysql_select_db("".$data_basename."") or die(mysql_error());
$conn = mysql_connect($hostname,$data_username,$data_password);
mysql_select_db($data_basename) or die(mysql_error());
Also right now your script is very insecure. $username doesn't get filtered before it is sent to the db.
You have other places where you have $variable1 = "".$variable2."" these double quotes you have a worthless. You can just say $variable = $variable2;

$_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.

Can anyone find an undefined index in this line of php code?

$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

Categories