undefined index error with isset() in place? - php

Have I missed something here that I'm not seeing that would throw an undefined index error for this code? In testing a addition of code to functions.php where $_POST['sub'] is not being passed it throws the undefined index error below, but this same isset() test against the exact same POST variable "sub" is performed about 12 times above line 494 without throwing error. What am i missing?
ERROR FROM PHP
Notice: Undefined index: sub in
/home/path/public_html/dtest/includes/functions.php on line 494
CODE FOR LINE 494
if (isset($_POST['sub']) && $_POST['sub'] == "ritem") {
$id = $_POST['ritemid'];
unset($_SESSION['cart']['items'][$id]);
header("Location: ".$_SERVER['HTTP_REFERER']."");
die();
} else {
echo $_POST['sub'];
}

Remove the echo $_POST['sub']; from the else part which is responsible for this Undefined index notice and replace with the echo statement.
Should be like this..
<?php
if (isset($_POST['sub']) && $_POST['sub']=="ritem") {
$id=$_POST['ritemid'];
unset ($_SESSION['cart']['items'][$id]);
header("Location: ".$_SERVER['HTTP_REFERER']."");die();}
else
{
echo "The subject is not set";
}
That is because.. when the if fails which means the $_POST['sub'] is not set , so when it comes to the else part , you are trying to output $_POST['sub'] which was actually not set (which is actual source of this problem)

Its because of else case
if (isset($_POST['sub']) && $_POST['sub']=="ritem") {
$id=$_POST['ritemid'];
unset ($_SESSION['cart']['items'][$id]);
header("Location: ".$_SERVER['HTTP_REFERER']."");
die();
} else if(isset($_POST['sub'])) {
echo $_POST['sub'];
} else {
// Do something else here
}

Related

session is works locally but not online [duplicate]

I'm new to PHP and am even more of a beginner when it comes to sessions. I have my index.php page, which is where users can register and login. The forms are posting to validate.php and loginvalidate.php pages, respectively for registering and logging in.
I have these errors on index.php when I load it:
1) Notice: Undefined index: registered
2) Notice: Undefined index: neverused
I have tried modifying my text in many ways but I never got to solve the errors.
Index.php
<?php
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
?>
Validate.php (after submitting register form)
if (mysqli_num_rows($result) > 0) { //IF THERE IS A PASSWORD FOR THAT EMAIL IN DATABASE
$_SESSION['registered'] = "Email is already registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
Loginvalidate.php (after submitting login form)
if ($numrows!=0) //IF THERE IS A PASSWORD FOR THAT EMAIL IN THE DATABASE
{
if ($row['password'] == $password) { //IF THE PASSWORD MATCHES USER INPUT
header('Location: homepage.php');
echo "lol";
exit();
}
else{
$_SESSION['badlogin'] = "Email/password combination not valid.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
}
else { //THERE IS NO PASSWORD FOR THAT EMAIL, SO THAT EMAIL IS NOT REGISTERED
$_SESSION['neverused'] = "Email is not registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
Okay so my script does what it is intended to do. The only thing that I can't solve is these session errors. Do you see any misuse of sessions? Of course, I have started the sessions in all of my .php files.
Also, note that I am aware that there is no protection from hackers. This is only for a future prototype that won't contain any important data.
The reason for these errors is that you're trying to read an array key that doesn't exist. The isset() function is there so you can test for this. Something like the following for each element will work a treat; there's no need for null checks as you never assign null to an element:
// check that the 'registered' key exists
if (isset($_SESSION['registered'])) {
// it does; output the message
echo $_SESSION['registered'];
// remove the key so we don't keep outputting the message
unset($_SESSION['registered']);
}
You could also use it in a loop:
$keys = array('registered', 'badlogin', 'neverused');
//iterate over the keys to test
foreach($keys as $key) {
// test if $key exists in the $_SESSION global array
if (isset($_SESSION[$key])) {
// it does; output the value
echo $_SESSION[$key];
// remove the key so we don't keep outputting the message
unset($_SESSION[$key]);
}
}
If you're getting undefined index errors, you might try making sure that your indexes are set before you try comparing the values. See the documentation for the isset function here:
http://php.net/manual/en/function.isset.php
if (isset($_SESSION['registered']))
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
}
if (isset($_SESSION['badlogin']))
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
}
if (isset($_SESSION['neverused']))
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
}

PHP Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in /var/www/html/index.php on line 14

PHP Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in /var/www/html/index.php on line 14
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
include 'header.php';
include 'dbh.php';
?>
<?php
if (isset($_SESSION['id']))
{
echo "you are logged in<br>";
if (isset($_SESSION['active']==0))
echo "your account is not activated<br>";
else
echo "you are logged in and activated<br>";
}
if (!isset($_SESSION['id']))
{
echo "you are not logged in<br>";
}
?>
</body>
</html>
i'm relatively new to php and i'm having a problem with my code, i want to make sure that if active in my database is set to 0 then it will echo that they aren't activated. if you see anymore mistakes in my code then please let me know.
thanks
if (isset($_SESSION['active']==0))
Is wrong, because the argument is an expression.
if (intval($_SESSION['active']) == 0)
Parses to integer and compares it to 0: secure & short
You can use !empty() instead of !isset()
Example:
if (!empty($_SESSION['id']))
{
echo "you are logged in<br>";
}
else {
//do whatever you want
}

Undefined index (hid is not being identified)

On running the following code I'm getting the following error:
Notice: Undefined index: hid in E:\Program Files\xampp\htdocs\cont.php
echo "<table align='right'><tr><td><a href='cont.php?hid=101'><input type='button' value='Account Settings'></a></td></tr></table>";
cont.php code:
$con = mysql_connect("localhost","Rahul","");
mysql_select_db("ebusiness", $con);
if($_SESSION['id']==1)
{
include 'business.php';
}
else if($_GET['hid']==101)
{
session_start();
include 'edprofile.php';
}
You are directly checking on $_GET['hid'] without checking if it is set or not.
else if(isset($_GET['hid']) && $_GET['hid'] == 101)
Try this code :
added : $hid = isset($_GET['hid'])?$_GET['hid']:"";
edited : $_GET['hid'] to else if($hid==101)
$con = mysql_connect("localhost","Rahul","");
mysql_select_db("ebusiness", $con);
$hid = isset($_GET['hid'])?$_GET['hid']:"";
if($_SESSION['id']==1)
{
include 'business.php';
}
else if($hid==101)
{
session_start();
include 'edprofile.php';
}
Change this line:
else if($_GET['hid']==101)
to:
else if(isset($_GET['hid']) && $_GET['hid']==101)
Remember that when you are using GET or POST on your page, there is no guarantee that a certain variable has been sent, as the HTTP protocol is stateless by default.
It is there for important to checn that a variable exists, and also that the variable is validated. To this end the isset() method is quite useful. I would recommend you do a
isset($_GET['hid'])
in your code in an if statement.
you are also missing to pass hid variable in you get request ( in URL). check it out. It shuld content ?hid=101 or &hid=101 some where.
and replace your else if condition with
else if(isset($_GET['hid']) && $_GET['hid']==101)

line of error appears when passing a message in php

i been working in the login code .. it works fine except this message that appears when openenig the login page !!
Notice: Undefined index: msg in C:\xampp\htdocs\thesite\login.php on line 103
it has appeard when i typed this in loginExcution.php
else {
//Login failed
header("location:login.php? msg=*invalid name or password");
exit();
}
and this to show the message in the login form page
<?php
$msg = $_GET['msg'];
print $msg;
?>
Don't put spaces in your header("Location:.
else {
//Login failed
header("Location: login.php?msg=invalid%20name%20or%20password");
exit();
}
EDIT: The %20s are actually spaces. Look at the PHP function urlencode() if you want more info. The code above is equivalent to this:
else {
//Login failed
header("Location: login.php?msg=" . urlencode("invalid name or password"));
exit();
}
beside removing first space mentioned in simplyianm answer. if the code reaches this line $_GET['msg'] and msg is not defined index, it will trigger the notice. you can do this instead
if (isset($_GET['msg'])){
$msg=$_GET['msg'];
print $msg;
}
though, passing the message content through the url is not a good idea. users can pass some javascript and send the link to unsuspecting user. Instead you could make it a code login.php?msg=invalid
then in the code
if (isset($_GET['msg'])){
switch ($msg){
case "invalid":
echo "Invalid username or password";
break;
}
}

PHP notice - Undefined index on index.php

I'm running into a server notice that doesn't seem to effect the loading of my pages but nonetheless creates a new entry in the error log every time a page is loaded... That error is:
PHP Notice: Undefined index: thing in C:\File Location\htdocs\index.php on line 1
I'm not sure whether the problem is actually on the first line or on a subsequent line, so I included a modified version of the whole file. The weird thing for me is that there's an identical line of code on several other files and it doesn't raise an issue in them. Also, the value is correctly extracted and all is well, I just don't know what to change in order to avoid the notice.
$thingvalue = $_REQUEST['thing'];
include("mdetect.php");
$iphoneTierHomePage = 'mobilemain.php';
$iphoneTierMobilePage = 'mobilepage.php?thing=' . $thingvalue;
$genericMobileDeviceHomePage = 'mobilemain.php';
$genericMobileDeviceMobilePage = 'mobilepage.php?thing=' . $thingvalue;
$line1 = define('WP_USE_THEMES', true);
$line2 = require('./wp-blog-header.php');
$desktopPage == $line1 + $line2;
$uagent_obj = new uagent_info();
function AutoRedirectToProperHomePage()
{
global $thingvalue, $uagent_obj, $iphoneTierHomePage, $genericMobileDeviceHomePage, $iphoneTierMobilePage, $genericMobileDeviceMobilePage, $desktopPage;
if ($thingvalue == ''){
if ($uagent_obj->isTierIphone == $uagent_obj->true)
header ('Location: '.$iphoneTierHomePage);
else if ($uagent_obj->DetectMobileQuick() == $uagent_obj->true)
header ('Location: '.$genericMobileDeviceHomePage);
else
header ('Location: '.$desktopHomePage);
}
if ($thingvalue != ''){
if ($uagent_obj->isTierIphone == $uagent_obj->true)
header ('Location: '.$iphoneTierMobilePage);
else if ($uagent_obj->DetectMobileQuick() == $uagent_obj->true)
header ('Location: '.$genericMobileDeviceMobilePage);
else
header ('Location: '.$desktopPage);
}
}
AutoRedirectToProperHomePage();
It's referring to the array index for the first line in index.php:
Try this:
$thingvalue = empty($_REQUEST['thing']) ? '' : $_REQUEST['thing'];
It is trying to reference the index thing inside the $_REQUEST superglobal. If someone is viewing that page directly and was not posted via a form or directed with a ?thing=foobar in the query string, PHP will show that notice. I'd recommend not using $_REQUEST as it checks both $_GET and $_POST which is not very secure/practical - then check if it is set, and if not, taking some failsave action:
try
{
if(!isset($_POST['thing']))
{
throw new Exception('No direct access. Please use our Contact form');
}
else
{
$thingvalue = $_POST['thing'];
}
}
catch(Exception $e)
{
echo $e->getMessage();
exit();
}
The issue is that you are trying to get the value of thing here
$thingvalue = $_REQUEST['thing']; before checking if the value exists first.
try this first
if( !isset( $_REQUEST['thing']) )
{
do something because its missing
}

Categories