I think the question is fairly self-explainatory, here's the code:
HTTP Request: localhost/execute.php?password=testing&command=create&api=api
This is part of the execution code.
try
{
$TFA_SAMP->createUser($_GET['email'], $_GET['cellphone'], $_GET['area_code']);
}
catch(Exception $createError)
{
echo $createError->getMessage();
}
Here's the class method:
function createUser($email, $cellphone, $areaCode = 1)
{
if(!isset($email))
throw new BadMethodCallException('(CTFA_SAMP->createUser) email ('. $email .') is missing.');
if(!isset($cellphone))
throw new BadMethodCallException('(CTFA_SAMP->createUser) cellphone ('. $cellphone .') is missing.');
$authyLibrary = new Authy_Api($this->API, $this->connectionURL);
$requestResult = $authyLibrary->registerUser($email, $cellphone, strval($areaCode));
if($requestResult->ok())
{
echo $requestResult->id();
}
else
{
foreach($requestResult->errors() as $field => $message)
echo "$field = $message";
}
}
The PHP pages prints:
Notice: Undefined index: email in D:\xampp\htdocs\tfasamp\execute.php on line 46
Notice: Undefined index: cellphone in D:\xampp\htdocs\tfasamp\execute.php on line 46
Notice: Undefined index: area_code in D:\xampp\htdocs\tfasamp\execute.php on line 46
(CTFA_SAMP->createUser) email () is missing.
How do I prevent PHP from giving me those notices as I am using exceptions to show them?
$TFA_SAMP->createUser($_GET['email'], $_GET['cellphone'], $_GET['area_code']);
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
The non-existing variables are accessed here. Nobody cares that you're later checking for isset on completely different variables and are throwing exceptions, the problem is in the above line. You need to fix it there. For example:
$args = $_GET + array('email' => null, 'cellphone' => null, 'area_code' => null);
$TFA_SAMP->createUser($args['email'], $args['cellphone'], $args['area_code']);
Alternatively, use isset statements here and throw exceptions for missing user input.
Basically, the code which touches $_GET deals with completely unpredictable user input. That's your first line of defence in which you need to check for existing or non-existing values. You can't roll this as responsibility into code which comes later.
Related
I am new in this site, and i found some questions that are connected to my system error but unfortunately they can't fix the error. I am creating an offline web-based information system for my capstone project and I don't understand why P_Bday is undefined.. Here is my code
This is my code for inputting Birthdate:
input type="text" id = "P_Bday" name = "P_Bday" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" data-mask placeholder="dd/mm/yyyy" required
And here's my code for calculating age:
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
$dob = $_POST["P_Bday"];
And I call my function here, where it should display the calculated age depending on the inputted birthdate:
input type='text' name = 'P_Age' id='disabledTextInput' class='form-control' value='".ageCalculator($dob)."' readonly
Every time I ran my code it says:
Notice: Undefined index: P_Bday in
C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php on line
47
If the line $dob = $_POST["P_Bday"]; is being run on the page before anything is sent via POST, then $_POST[foo] is invalid.
Change the line to:
if(isset($_POST["P_Bday"])) $dob = $_POST["P_Bday"];
else $dob = null;
Or:
$dob = isset($_POST["P_Bday"]) ? $_POST["P_Bday"] : null;
An Undefined index error is pretty simple to debug. You start at the file mentioned in the error message C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php and go to the line mentioned in the error message line 47 and find the undefined index in question on that line P_Bday and know with absolute certainty that up to this point in your code you have not defined that index for that variable. You can work your way backwards through the code to try and figure out your mistake. The mistake can be a typo (you used the wrong case/variable name) or it can be that you just forgot to initialize the variable properly.
The best way to avoid undefined variable/index errors is to initialize always and initialize early. In the few cases where you cannot be sure that variables are properly initialized (for example with $_POST/$_GET or other external variables under control of client input) you want to use isset to avoid the error and that way you can coalesce null values or write logic that prevents the code from continuing with an uninitialized value in case of user error.
Example
if (!isset($_POST['P_Bday'])) {
die("You forgot to fill out your birthday!");
} else {
echo "Yay!";
}
Some good initialization techniques with $_POST/$_GET
A good best practice for "initialize always and initialize early" when dealing with user input is to setup a default set of values for the expected input from your form and initialize from that in order not to fall into this trap.
Example
$defaultValues = [
'P_Bday' => null,
'Option1' => 'default',
'Option2' => 1,
];
/* Let's say the user only supplied Option1 */
$_POST = ['Option1' => 'foo'];
/* This makes sure we still have the other index initialized */
$inputValues = array_intersect_key($_POST, $defaultValues) + $defaultValues;
/**
* Now you can pass around $inputValues safely knowing all expected values
* are always going to be initialized without having to do isset() everywhere
*/
doSomething(Array $inputValues) {
if (!$inputValues['P_Bday']) { // notice no isset() check is necessary
throw new Exception("You didn't give a birthday!!!");
}
return (new DateTime)->diff(new DateTime($inputValues['P_Bday']))->y;
}
You are declaring the variable $dob after calling function. You have to declare your variable before function call and also use conditional statement like following:
Please write your code as follows:
if(isset($_POST["P_Bday"])){
$dob = $_POST["P_Bday"];
} else {
$dob ="";
}
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
Notice (8): Use of undefined constant inList - assumed 'inList' [CORE\Cake\Utility\ClassRegistry.php, line 168]
This notice has been bugging me for a while know, and I do not know how to fix it.. It was not really affecting my project earlier since its just a notice msg, but now, it is not letting me show an error message which I am trying to display to the user.
Iv got this function
public function validate_form(){
if($this->RequestHandler->isAjax()){
$this->request->data['Donor'][$this->params['form']['field']] = $this->params['form']['value'];
$this->Donor->set($this->data);
if($this->Donor->validates()){
$this->autoRender = FALSE;
}else{
$error = $this->Donor->validationErrors;
$this->set('error',$error[$this->params['form']['field']]);
}
}
}
The above is the action to which my post request submits to. Then it executes the following to display the error
if (error.length > 0) {
if ($('#name-notEmpty').length == 0) {
$('#DonorName').after('<div id="name-notEmpty" class="error-message">' + error + '</div>');
}
}else{
$('#name-notEmpty').remove();
}
The problem is that instead of the relevant error in my newly created div... I get that notice 8 from cake! Please if anyone knows why this is happening, I appreciate your aid on this one..
TLDR:
Do a project-wide find for 'inList' and find the spot where it either doesn't have quotes around it, or, if it's supposed to be a variable, is missing it's $.
Explanation:
You get that error when you try to use a PHP Constant that doesn't exist. Usually you're not actually TRYING to use a constant, but instead just forgot to wrap quotes around something or forgot to add the $ before a variable.
Examples:
$name = "Dave";
echo name; // <-- WOAH THERE, there is no Constant called name (missing $)
$people = array('Dave' => 'loves pizza');
echo $people[Dave]; // <-- WOAH THERE, no Constant called Dave (missing quotes)
Most likely somewhere else in your code you are using 'inList' as an array key but you don't have it quoted.
Example: $value = $myArray[inList];
It still works without quoting inList but it causes the notice message you're seeing.
trying to get every post and comment from a facebook page, I made this function that should go through the pagination:
$req = $facebook->api("/" . $pagename . "/?fields=posts.fields(message,link,created_time,shares,likes,comments)");
function parcours_arbre($ab)
{
GLOBAL $facebook;
GLOBAL $pagename;
$next = create_request($ab['posts']['paging']['next']);
$next_req = $facebook->api($pagename.$next);
$ab_next = $next_req['data'];
$prev = create_request($ab['posts']['paging']['previous']);
$prev_req = $facebook->api($prev);
$ab_prev = $prev_req['data'];
if (empty($ab)) {
display_results($ab['posts']['data']);
} else {
parcours_arbre($ab_next);
parcours_arbre($ab_prev);
}
}
I unfortunately get the following error:
Notice: Undefined index: posts in /form.php on line 36
Notice: Undefined offset: 3 in /utils.php on line 20
Notice: Undefined offset: 4 in /utils.php on line 20
Fatal error: Uncaught GraphMethodException: Unsupported get request. thrown in /sdk/src/base_facebook.php on line 1271
Any idea how i could avoid it or what is going on? Would this go away if i use the "until" statement in my api request?
Thanks a lot,
To explain each error
the variable $ab which is an argument to the function, does not have a "posts" index. You should try to var_dump this variable so you can see what it actually looks like.
same as above
same as above
the api function takes 3. The path which should just be #pagename. The method ("GET" or "POST") most likely POST because GET is causing an error. The parameters, which should be array("fields" => "posts.fields(message,link,created_time,shares,likes,comments)")
I noticed that for next you have the code
$next_req = $facebook->api($pagename.$next);
but for previous you have
$prev_req = $facebook->api($prev);
Might want to look into this.
I'm getting a series of:
"Undefined variable: loginError in /Library/WebServer/Documents/clients . . ."
entries in my Apache error_log which I would like to prevent. I have a simple login.php page which, if there's an error logging in sets the $loginError variable as such:
$loginError = '<p class="text-error">Login Error: '. $layouts->getMessage(). ' (' . $layouts->code . ')</p>';
If there's no error logging in it does this:
$loginError = '';
I then output any errors as such:
if ($loginError !== '') { //line 112
echo $loginError; /line 113
}
I'm getting the entries for the line 112 and 113 noted in my comments above. Anyone tell me how I can prevent the entries appearing? I'm using PHP Version 5.3.6.
thanks
Its saying you should check it is set before using:
One way is with isset()
if (isset($loginError) && $loginError !== '') {
echo $loginError;
}
But in your particular case you may as well use !empty()
if (!empty($loginError)) {
echo $loginError;
}
Hard to say without seeing the rest of your code. Trace through your logic to make sure that every possible branch initializes loginError at some point in its execution. Even better, set it to a default value before you go through the logic.
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 3 years ago.
Notice: Undefined index: subject in /var/www/mailer.php on line 12 Notice: Undefined index: message in /var/www/mailer.php on line 13 Notice: Undefined index: from in /var/www/mailer.php on line 14 Notice: Undefined index: verif_box in /var/www/mailer.php on line 15 Notice: Undefined index: tntcon in /var/www/mailer.php on line 23 no variables received, this page cannot be accessed directly
BELOW IS THE CODE
<?php
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
// -----------------------------------------
// The Web Help .com
// -----------------------------------------
// remember to replace you#email.com with your own email address lower in this code.
// load the variables form address bar
$subject = $_POST["subject"];
$message = $_POST["message"];
$from = $_POST["from"];
$verif_box = $_POST["verif_box"];
// remove the backslashes that normally appears when entering " or '
$message = stripslashes($message);
$subject = stripslashes($subject);
$from = stripslashes($from);
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon']){
// if verification code was correct send the message and show this page
mail("abhijit.infogence#gmail.com", 'TheWebHelp.com Form: '.$subject, $_SERVER['REMOTE_ADDR']."\n\n".$message, "From: $from");
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
} else if(isset($message) and $message!=""){
// if verification code was incorrect then return to contact page and show error
header("Location:".$_SERVER['HTTP_REFERER']."?subject=$subject&from=$from&message=$message&wrong_code=true");
exit;
} else {
echo "no variables received, this page cannot be accessed directly";
exit;
}
?>
You're trying to access parts of a variable which don't exist. You may want to check before using them, if they exist.
The error is simply because the message $_POST array does not have a key called 'message'. It probably comes from the fact that the form has not been submitted. The error is only a notice and won't stop the program from working.
You should check what $_POST contains before you address some particular fields, take a look at the isset function. Or simply turn off display_errors ;)
It seems that you call this PHP file without submitting a form via the POST method. Make sure that your mailing form has the proper method set:
<form method="POST" action="yourfile.php">
etc.
</form>
You should also sanitize the user input before calling mail() (i. e. remove newlines and tags), otherwise you are calling for trouble.
Your $_POST and $_COOKIE arrays do not contain those indexes.
Do:
print_r($_POST);
print_r($_COOKIE);
to see what is contained in those arrays
foreach(array('subject', 'message', 'from', 'verif_box') as $val)
{
if (isset($_POST[$val]))
{
$$val = trim($_POST[$val]);
continue;
}
// some sort of error checking, like telling the end user that
// not all fields were correctly given
}
Check user-submitted data
$subject = (isset($_POST["subject"]) ? $_POST["subject"] : '');
$message = (isset($_POST["message"]) ? $_POST["message"] : '');
$from = (isset($_POST["from"]) ? $_POST["from"] : '');
$verif_box = (isset($_POST["verif_box"]) ? $_POST["verif_box"] : '');
You can even make your own function to do that
function checkPost($fieldname)
{
return (isset($_POST[$fieldname]) ? $_POST[$fieldname] : '');
}
And then do
$subject = checkPost("subject");
I recommend as well that you check required POST fields
if (!isset($_POST["xxx"]) || trim($_POST["xxx"]) == '')
{
// throw exception, display error...
}
etc.
FYI, instead of using stripslashes() to avoid "magic_quotes", you can use a simple function such as this one http://snippets.dzone.com/posts/show/5256 which will do the job for all fields.
//checking if array elements are set and changing variables values if so
$subject = isset($_POST["subject"])?$_POST["subject"]:null;
$message = isset($_POST["message"])?$_POST["message"]:null;
$from = isset($_POST["from"])?$_POST["from"]:null;
$verif_box = isset($_POST["verif_box"])?$_POST["verif_box"]:null;
// check to see if verificaton code was correct and if cookie value on 'tntcon' is set
if(isset($_COOKIE['tntcon']) && md5($verif_box).'a4xn' == $_COOKIE['tntcon']){
Changes are on lines 12-15 and in 23.