PHP Notice in MailChimp_API->post() when email is invalid
-
I found a bug that is triggered by entering an invalid email address. Both [email protected] and “test” on it’s own trigger the problem.
Error:
Notice: Undefined index: field in /[SITE]/wp-content/plugins/mailchimp/lib/mailchimp/mailchimp.php on line 91
Here is line 91 that causes the problem:
elseif ($merge['tag'] == $body['errors'][0]['field']) {
Here is the problem line with context above and below to make the problem clear:
if (empty($body['errors'])) { //Email address doesn't come back from the API, so if something's wrong, it's that. $field_name = 'Email Address'; $body['errors'][0]['message'] = 'Please fill out a valid email address.'; } elseif ($merge['tag'] == $body['errors'][0]['field']) { $field_name = $merge['name']; }
The error happens because when an email is invalid there’s nothing in
['errors'][0]['field']
, but this code assumes that any time$body['errors']
isn’t empty it means that there is a “tag” in['errors'][0]['field']
which can be compared with$merge['tag']
.So when there IS something in
['errors']
, but[0]['field']
isn’t there, we get a PHP notice.Here is some code that “fixes” the problem by checking
isset()
on the contents of['errors']
before comparing them:/** * JERHACK: Test the existence of $body['errors'][0]['field'] before comparing it's value to avoid PHP Notice * Triggered when an invalid email is submitted, in which case [0] contains only array('message'=>"Please fill out a valid email address.") */ // elseif ($merge['tag'] == $body['errors'][0]['field']) { elseif (isset($body['errors'][0]['field']) AND ($merge['tag'] == $body['errors'][0]['field'])) { $field_name = $merge['name']; }
This is a very superficial fix, but should solve my immediate problem.
On a deeper level, it is vital that when coding PHP, we avoid making assumptions about the contents of arrays. Missing array items being compared causes Notices, which may be harmless, but indicate sloppy coding and are easy to fix.
Making it a habit to evaluate arrays like this before interacting with them will avoid these surprises.
Please remember to use
WP_DEBUG
while developing your plugins, as I’ve encouraged in previous threads.WP_DEBUG
surfaces Notices so you see them while developing, rather than waiting for your users to tell you about them.https://codex.wordpress.org/Debugging_in_WordPress
P.S. Please don’t ask me for more info about my setup until a developer has reviewed this ticket. The problem is glaring once you look at it 🙂
- The topic ‘PHP Notice in MailChimp_API->post() when email is invalid’ is closed to new replies.