0

I'm breaking my head here. First time toying with PHP. I have a form with several fields that are required. If a user tries to send an empty field, it needs to be caught. If I type a space, the form goes through. Any help will be truly appreciated.

This is the code for one field

if( isset($_POST['first_name']) and !empty($_POST['first_name']) and trim($_POST['first_name']) != '' ) $first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_MAGIC_QUOTES);
else {
  $redirect = SITE_URL . substr($section, -4) . '/' . substr($section, 0, -4) . '/' . $referPage . 'first_name=' . $first_name . '&last_name=' . $last_name . '&email=' . $email . '&phone' . $phone . '&country=' . $country . '#mailingList' and header ( "Location: $redirect" );
}
ndm
  • 59,784
  • 9
  • 71
  • 110
robb
  • 294
  • 2
  • 14
  • Just a note, you don't have to check both `isset` and `empty`: [Why check both isset() and !empty()](http://stackoverflow.com/questions/4559925/why-check-both-isset-and-empty) – FirstOne Nov 06 '15 at 19:27
  • What doesn't work? What are you asking for here? – whitwhoa Nov 06 '15 at 20:01

2 Answers2

1

You are setting $redirect to what the expression

$redirect = SITE_URL . substr($section, -4) . '/' . substr($section, 0, -4) . '/' . $referPage . 'first_name=' . $first_name . '&last_name=' . $last_name . '&email=' . $email . '&phone' . $phone . '&country=' . $country . '#mailingList' and header ( "Location: $redirect" );

evaluates to. When you do

header ( "Location: $redirect" );

$redirect has not been set yet.

For example:

php > $x = 'a' && 'a' . $x;
PHP Notice:  Undefined variable: x in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0

You need to just break it up:

$redirect = SITE_URL . substr($section, -4) . '/' . substr($section, 0, -4) . '/' . $referPage . 'first_name=' . $first_name . '&last_name=' . $last_name . '&email=' . $email . '&phone' . $phone . '&country=' . $country . '#mailingList';
header("Location: $redirect");

or make it evaluate the expression before the and first:

($redirect = SITE_URL . substr($section, -4) . '/' . substr($section, 0, -4) . '/' . $referPage . 'first_name=' . $first_name . '&last_name=' . $last_name . '&email=' . $email . '&phone' . $phone . '&country=' . $country . '#mailingList') and header ( "Location: $redirect" );
dave
  • 62,300
  • 5
  • 72
  • 93
0

Just an advice since you're a beginner on PHP robb, take a look at some framework to work with PHP, like Codeigniter, they'll have a few features that can help you, like a form validation. Another advice, you also have to do this validation before you send the form to the server ok, using Javascript (jQuery will give you a hand).

Regards, and good luck with PHP!!

  • Hey Daniel. Thanks for the suggestion. I will take on your advice. I'm ok with the front end part of the validation but the backend is a different beast. Haha. – robb Nov 06 '15 at 22:09