Jump to content

Best way to stop undefined variable errors?


garyed

Recommended Posts

I have a lot form variables where I'm having the errors show up since I updated my php version on my webhost server.  

Since I have well over 100 variables, it's going to take a lot of time to correct them so i just disabled errors for now in the php.ini file to keep things working.  

I was wondering that since form variables are in kept an array, if there isn't an easy way to have them all initiated when the page loads.

I think that would solve the majority of the errors & there wouldn't be that many left.

Any ideas appreciated?

Link to comment
Share on other sites

unconditionally doing this will end up hiding programming mistakes and when hackers/bot-scripts submit form data that doesn't include expected fields. you would want to see (when developing) or log (when on a live server) the errors so that you know what is occurring and can fix problems.

where exactly are the errors occurring at? if it is when you are populating form field values, before the form has ever been submitted, the ideal solution would be to use php's null coalescing operator at the point of using the value.

however, your example above indicates you are copying post variables to discrete variables (inside the form processing code?). you should instead keep the form data as a set, in a working array variable, usually having been trimmed, then operate on elements of this array variable throughout the rest of the code. doing this supports dynamically validating and processing the data.

Edited by mac_gyver
Link to comment
Share on other sites

You can use the empty function now to kill 2 birds with one stone.

 

if (!empty($_POST['var1']) {
  // Make some use of $_POST['var1']
}

There is also the "null coalescing" syntax (php >= 7) you can use for assignments like this:

$user = $_POST['user'] ?? 'Guest';

// This is equivalent to

$user = isset($_POST['user']) ? $_POST['user'] : 'Guest';

 

Link to comment
Share on other sites

I really appreciate the ideas but I have to admit that I don't understand the examples.  I have no idea what the :

?? 'Guest';

does or even means.

I am actually learning as I'm going, sort of on an as needed basis. 

Things that may seem obvious to the experienced programmer, are not obvious to me. 

I'm going to do a little testing with some of this stuff & see if i can make it work.   

Link to comment
Share on other sites

4 hours ago, garyed said:

I have no idea what the [??] does or even means

The Null Coalescing operator provides a fallback value if the previous value is null (or doesn't exist). 

$displayName = $_POST['displayName'] ?? 'Anonymous';

Using ?? there is a shorter way of writing

if (isset($_POST['displayName'])){
    $displayName=$_POST['displayName'];
} else {
    $displayName='Anonymous';
}

Using ?? to provide a fallback value prevents PHP from complaining about undefined variables/indexes.

If you don't have an appropriate default value to provide, you can just use null.

Link to comment
Share on other sites

6 hours ago, kicken said:

The Null Coalescing operator provides a fallback value if the previous value is null (or doesn't exist). 

$displayName = $_POST['displayName'] ?? 'Anonymous';

Using ?? there is a shorter way of writing

if (isset($_POST['displayName'])){
    $displayName=$_POST['displayName'];
} else {
    $displayName='Anonymous';
}

Using ?? to provide a fallback value prevents PHP from complaining about undefined variables/indexes.

If you don't have an appropriate default value to provide, you can just use null.

"Now I see", says the blind man :) 

Thanks for the explanation. 

Now it looks like the only problem I'll have to be careful about is not having this type of universal fix to affect my sessions too.  

Link to comment
Share on other sites

I've tried these two options & they seem to work OK. 

The null option works better if I'm using the variable for any mathematical calculations.

Is there anything wrong with declaring all variables that might be used in a form with the null fallback value as I did below?  

$var=$_POST['var']; ?? '';

$var=$_POST['var']; ?? null;

 

Link to comment
Share on other sites

As for whether you should set POST variables to null vs '', an argument could be made that they have similar strengths and weaknesses.   I would suggest always setting empty form variables initially to '' rather than null for 2 reasons.  From the browser point of view everything coming from a POST method is in string format.  It is up to you to synchronize your form code with the datatypes you received.  That's a different topic, but suffice it to say that loose typing and ease of conversion between types is one of the features of working with PHP, so long as you are consistent.

This issue exists when using null and comparing to a variable that doesn't even exist.

<?php

$foo = '';
$bar = null;

echo $foo === $baz ? "=" : "!=";
echo PHP_EOL;
echo $bar === $baz ? "=" : "!=";

//output
// !=
// =

 

In PHP 8, they changed things, so this now produces a warning, but in prior versions, trying to use a variable that was never declared just produces a notice.  This is where it gets muddy with PHP, in that a variable set = null is equivalent to a variable that doesn't even exist.   In general null exists to support the concept of "no value".    There is no intrinsic value to setting a variable you intend to use as a number = null vs. '' other than that with '' it's internally typed initially as a string.   

Perhaps a more important comment to you is that, having lots of variables floating around isn't great. 

Typically it is better if you have some sort of object or at least an array that supports your form handling.  It's also pretty far from DRY when you are writing the same statement 10x because you are processing a form with 10 elements.

I would start down this path, using an array, with a name like $postData or $formData.  Look at the benefit of something like this:

function getPostData($fields) {
  $postData = [];
  foreach ($fields as $field) {
     $postData[$field] = $_POST[$field] ?? '';
  }
  return $postData;
}

$fields = ['name', 'description', 'email_address'];
$postData = getPostData($fields);

It's a lot easier to build upon or expand this concept, then to write code with a bunch of independently named variables.  Using an array will provide you many benefits.  Classes can do even more for you, and if you look at frameworks you will find they always wrap the underlying HTTP request/response mechanics for you using classes.

Link to comment
Share on other sites

39 minutes ago, garyed said:

I've can have as much as 1,000 variables on one page so it's  going to be a lot of work no matter what I do now.

when you have more than about 2-3 form fields, you should use a data-driven design and dynamically validate and process the form data.

based on the copying of post variables to discrete variables, apparently this information was not seen -

On 12/14/2021 at 5:56 PM, mac_gyver said:

however, your example above indicates you are copying post variables to discrete variables (inside the form processing code?). you should instead keep the form data as a set, in a working array variable, usually having been trimmed, then operate on elements of this array variable throughout the rest of the code. doing this supports dynamically validating and processing the data.

at the point of populating form field values, again, if you have more than just a few of them, you need to switch to a templating system where you would supply an array of values as the input to the template, rather than use a discrete variable for each one.

Link to comment
Share on other sites

39 minutes ago, garyed said:

It's a calculation program that defaults to about 50 inputs

this is a set of data where you will be operating on each element in the set in the same/similar way. arrays are for sets of data. you should be using arrays for the form fields and loop over the submitted arrays of data.

  • Great Answer 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.