Stop a function

I created 5 functions and I run each one individually, what im trying to do is run each function and have it stop once a condition is reached.
Take a look at

  function checkFirstName($input) {
	  
	  $pattern = '/[a-zA-Z]{2,15}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['First_Name'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
	      header('Location: index.php?error=1');	
	  }
  
  }
  function checkLastName($input) {
	  $pattern = '/[a-zA-Z]{2,15}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['Last_Name'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
	      header('Location: index.php?error=2');	  
	  }
  
  }
    function checkPhone($input) {
	  $pattern = '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['Phone_Number'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
	      header('Location: index.php?error=3');	  
	  }
  
  }
    function checkCity($input) {
	  $pattern = '/[a-zA-Z]{3,20}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['City'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
		    header('Location: index.php?error=4');	  
	  }
  
  }
    function checkState($input) {
	  $pattern = '/[a-zA-Z]{2}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['State'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
	      header('Location: index.php?error=5');	  
	  }
  
  }  
  //fire off each function
  checkFirstName($_POST['First_Name']);
  checkLastName($_POST['Last_Name']);
  checkPhone($_POST['Phone_Number']);
  checkCity($_POST['City']);
  checkState($_POST['State']);

Once an error is found in the first function (screenshot) why does all the functions run:?


it makes it to the last function, how do I stop it there?

Thanks

Try adding an exit() after the header.

Off topic:-
I would also question the logic of creating 5 near identical functions, it sort of defeats the object of using functions, to re-use the same code many times.
I’m sure with a bit of modification you could come up with a single function to do the whole lot. :smile:

3 Likes

ill give it a whirl

i tried…but failed.
I changed the code for the functions to

  function checkFirstName($input) {
	  
	  $pattern = '/[a-zA-Z]{2,15}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['First_Name'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
	      header('Location: index.php?error=1');	
		  exit();  
	  }
  
  }
  function checkLastName($input) {
	  $pattern = '/[a-zA-Z]{2,15}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['Last_Name'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
	      header('Location: index.php?error=2');
		  exit();  
	  }
  
  }
    function checkPhone($input) {
	  $pattern = '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['Phone_Number'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
	      header('Location: index.php?error=3');	
		  exit();  
	  }
  
  }
    function checkCity($input) {
	  $pattern = '/[a-zA-Z]{3,20}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['City'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
		    header('Location: index.php?error=4');	  
			exit();
	  }
  
  }
    function checkState($input) {
	  $pattern = '/[a-zA-Z]{2}/';
	  if(preg_match($pattern, $input)) {
	      //set a SESSION variable
		   $_SESSION['State'] = $input;
		   return true;
	  
	  } else {
		  //refresh the page 
	      header('Location: index.php?error=5');	
		  exit();  
	  }
  
  } 

to have exit() after every header() call, but the error persists


why doesnt the pag get redirected to my index.php?error1?

Now the way I was thinking to shorten the 5 functions into 1 is like

    function validateAll($input1,$input2,$input3,$input4,$input5) {
	  $pattern1 = '/[a-zA-Z]{2,15}/';
	  $pattern2 = '/[a-zA-Z]{2,15}/';
	  $pattern3 = '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/';
	  $pattern4 = '/[a-zA-Z]{3,20}/';
	  $pattern5 = '/[a-zA-Z]{2}/';

		for ($i = 1; $i <= 5; $i++) {
			  if(preg_match($pattern.$i, $input.$i)) {
				  //set a SESSION variable
				   $_SESSION['First_Name'] = $input1;
				   $_SESSION['Last_Name'] = $input2;
				   $_SESSION['Phone_Number'] = $input3;
				   $_SESSION['City'] = $input4;
				   $_SESSION['State'] = $input5;
				   return true;
			  
			  } else {
				  //refresh the page 
				  header('Location: index.php?error='.$i.'');	
				  exit();
			  }
		}	  
	  }

Is that like what you were thinking?

Is there any html output from the script before the functions are called?
That would do it, header has to come first.

Not really, the idea of the function is not to do everything all in one go, but to be re-used over and over with different variable values on each call.
Sorry it’s a bit late here and I don’t have time to go in depth on this, but a hint.
Maybe something that starts like:-

function validae($NameOfFormField, $TypeOfRegexToUseOnIt) {...}

Within the function:-

	  $pattern1 = '/[a-zA-Z]{2,15}/';
	  $pattern2 = '/[a-zA-Z]{2,15}/';
	  $pattern3 = '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/';
	  $pattern4 = '/[a-zA-Z]{3,20}/';
	  $pattern5 = '/[a-zA-Z]{2}/';

If this were actually an associative array instead of just a bunch of variables, that would be neat.
You could call it with: $RegexArray[$TypeOfRegexToUseOnIt]
As in: if(preg_match($RegexArray[$TypeOfRegexToUseOnIt], $NameOfFormField)) {...}

An example of a similar function:-

    function sani($name, $type) {
        $regarr = array(
            'int' => '0-9',
            'bin' => '0-1',
            'alph' => 'a-z',
            'date' => '0-9A-Z .a-z/',
            'text' => 'A-Za-zÀ-ÿ 0-9,.',
            'phone' => '0-9 +'
        ) ;
        if(isset($_POST[$name])) {
            $name = preg_replace('#[^'.$regarr[$type].']#iu', '', $_POST[$name]);
            return $name ;
        }
        else {
            // Someone is being naughty, what shall I do??
            exit() ; // Yep, it ends in exit ;)
        }
    } // End sani

Well it appears that the header() works ok as its redirected to index.php?error=5 as in the last of the functions though so I guess thats not the issue.

In terms of the other function…
damn, thats such a nice way to do it, is this better

function validateAll($Input_Name, $Regex) {

    $RegArray= array(
    'First_Name' => '/[a-zA-Z]{2,15}/',
    'Last_Name' => '/[a-zA-Z]{2,15}/',
    'Phone_Number' => '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/',
    'City' => '/[a-zA-Z]{3,20}/',
    'State' => '/[a-zA-Z]{2}/'
    );

    if(preg_match($RegArray[$Regex], $_POST[$Input_Name])) {
      //set the SESSION variable
    $_SESSION{$Input_Name] = $_POST[$Input_Name]
      //return ?
    } else {
      header('Location: index.php?'.$Input_Name.'')
      exit();
    } 
}

Is that better?

Two things stand out for me in that:

  1. Because you pass $Input_Name in as a parameter, there’s no need to reference the global $_POST array any more, so you’d just use the direct variable. Like you’ve done in the line where you set the $_SESSION variable (and you’ve a typo there, curly-brace instead of square)

  2. In my opinion, and it might just be that, the function shouldn’t be doing the final part. You should set a return code and have the main code look at whether the function returned “good” or “bad” and then act accordingly. The function you have written is fine for what it does, but what if you want the same check somewhere else, but at the end it needs to redirect somewhere else, or not redirect but do something else on error? For me you’d do something like:

if (preg_match ......
 { 
 return true;
 }
else {
  return false;
  }

Then in your calling code:

if (validateAll("First_Name", $_POST['firstname'])) { 
  // do whatever the true return code indicates, set session var, etc.
  }
else {
  // do whatever false should, redirect etc. 
  }

So you don’t need to have separate versions of the function for different outcomes. Think of the function as doing the validation and nothing else - it checks the string against the regex, and says “good” or “bad”.

As First_Name and Last_Name have identical regex, it could be shortened further.

    $RegArray= array(
    'Name' => '/[a-zA-Z]{2,15}/',
    'Phone_Number' => '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/',
    'City' => '/[a-zA-Z]{3,20}/',
    'State' => '/[a-zA-Z]{2}/'
    );

So in the script you would call the function something like:-

if( validateAll('First_Name', 'Name')) {...}
if( validateAll('Last_Name', 'Name')) {...}

ok, did some changing around on this function so it can be used in an if

function validateAll($Input_Name, $Regex) {

    $RegArray= array(
    'Name' => '/[a-zA-Z]{2,15}/',
    'Phone_Number' => '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/',
    'City' => '/[a-zA-Z]{3,20}/',
    'State' => '/[a-zA-Z]{2}/'
    );

    if(preg_match($RegArray[$Regex], $_POST[$Input_Name])) {    
      return true;
    } else {      
      return false;
    } 
}

then I call the function five times

if( validateAll('First_Name', 'Name')) { $_SESSION['First_Name'] = $_POST['First_Name']; } else { header('Location: index.php?error=1');  }
if( validateAll('Last_Name', 'Name')) { $_SESSION['Last_Name'] = $_POST['Last_Name']; } else { header('Location: index.php?error=2');  }
if( validateAll('Phone_Number', 'Name')) { $_SESSION['Phone_Number'] = $_POST['Phone_Number']; } else { header('Location: index.php?error=3');  }
if( validateAll('City', 'Name')) { $_SESSION['City'] = $_POST['City']; } else { header('Location: index.php?error=4');  }
if( validateAll('State', 'Name')) { $_SESSION['State'] = $_POST['State']; } else { header('Location: index.php?error=5');  }

Droopsnoot, your saying to change the function to

$RegArray= array(
'Name' => '/[a-zA-Z]{2,15}/',
'Phone_Number' => '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/',
'City' => '/[a-zA-Z]{3,20}/',
'State' => '/[a-zA-Z]{2}/'
);

if(preg_match($RegArray[$Regex],$Input_Name)) {    
  return true;
} else {      
  return false;
} 

}

so your saying $_POST['First_Name'] is the same as $First_Name?

No, I’m saying you should pass the contents of the variable in, rather than just the index within the $_POST array.

function validateAll($Input_Name, $Regex) {
...
if (preg_match($RegArray[$Regex], $Input_Name])) {
.. 

then call it like:

if (validateAll($_POST['First_Name'], 'Name')) ....

What if you want to validate a variable using this function when the variable isn’t in the $_POST array? This way will still work, your way can only validate $_POST member variables.

1 Like

ooohhh, thanks (I was soo wrong, thanks for the confirmation)

ok, made the changes, submitted the form (so I should’ve been redirected to index.php?error=1 but got redirected to index.php?error=5
Did I miss something?
Heres the function & code to run it 5 times…

function validateAll($Input_Name, $Regex) {

    $RegArray= array(
    'Name' => '/[a-zA-Z]{2,15}/',
    'Phone_Number' => '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/',
    'City' => '/[a-zA-Z]{3,20}/',
    'State' => '/[a-zA-Z]{2}/'
    );

    if(preg_match($RegArray[$Regex], $Input_Name)) {    
      return true;
    } else {      
      return false;
    } 
}  //fire off each function
if( validateAll($_POST['First_Name'], 'Name')) { $_SESSION['First_Name'] = $_POST['First_Name']; } else { header('Location: index.php?error=1');  }
if( validateAll($_POST['Last_Name'], 'Name')) { $_SESSION['Last_Name'] = $_POST['Last_Name']; } else { header('Location: index.php?error=2');  }
if( validateAll($_POST['Phone_Number'], 'Phone_Number')) { $_SESSION['Phone_Number'] = $_POST['Phone_Number']; } else { header('Location: index.php?error=3');  }
if( validateAll($_POST['City'], 'City')) { $_SESSION['City'] = $_POST['City']; } else { header('Location: index.php?error=4');  }
if( validateAll($_POST['State'], 'State')) { $_SESSION['State'] = $_POST['State']; } else { header('Location: index.php?error=5');  }

ok, think I almost have this function figured out, entered in some junk data which should have trigerred a false but look what happened


Why did the 2nd function get run, shouldnt the first run until it hit exit()?
Heres the function

function validateAll($Input_Name, $Regex) {

    $RegArray= array(
    'Name' => '/[a-zA-Z]{2,15}/',
    'Phone_Number' => '/\([0-9]{3}\) [0-9]{3}-[0-9]{4}/',
    'City' => '/[a-zA-Z]{3,20}/',
    'State' => '/[a-zA-Z]{2}/'
    );

    if(preg_match($RegArray[$Regex], $Input_Name)) {    
      return true;
    } else {      
      return false;
    } 
}  

and heres where I call it 5 times

if( validateAll($_POST['First_Name'], 'Name')) { $_SESSION['First_Name'] = $_POST['First_Name']; } else { header('Location: index2.php?error=1'); exit();  }
if( validateAll($_POST['Last_Name'], 'Name')) { $_SESSION['Last_Name'] = $_POST['Last_Name']; } else { header('Location: index2.php?error=2'); exit(); }
if( validateAll($_POST['Phone_Number'], 'Phone_Number')) { $_SESSION['Phone_Number'] = $_POST['Phone_Number']; } else { header('Location: index2.php?error=3'); exit(); }
if( validateAll($_POST['City'], 'City')) { $_SESSION['City'] = $_POST['City']; } else { header('Location: index2.php?error=4'); exit(); }
if( validateAll($_POST['State'], 'State')) { $_SESSION['State'] = $_POST['State']; } else { header('Location: index2.php?error=5');exit();  }

Does it work any better if you get rid of the var_dump() you can see in the top left corner? If you’ve already sent output to the screen, your header() function won’t work.

I have 2 functions

  function checkFirstName($input) {
	  
	  $pattern = '/[a-zA-Z]{2,15}/';
	  if(preg_match($pattern, $input)) {
		   return true;	  
	  } else {
		  return false;
	  }
  
  }
    function checkState($input) {
	  $pattern = '/[a-zA-Z]{2}/';
	  if(preg_match($pattern, $input)) {
		   return true;	  
	  } else {
		  return false;
	  }
  }  

I run them like…

if(checkFirstName($_POST['First_Name'])) {  $_SESSION['First_Name'] = $input; } else { header('Location: index.php?error=1'); } 
if(checkState($_POST['State'])) {  $_SESSION['State'] = $input; } else { header('Location: index.php?error=5'); } 

I have 2 problems, when I submit the form, this is what happens


why is the SESSION variable not set? heres that field

<input type="text" name="First_Name" class="form-control" id="name" value="<?=$_SESSION['First_Name']?>">

Where did you define $input, I don’t see it anywhere?

I merged the topics, as they appear to be the same.

1 Like

I have 2 functions

  function checkFirstName($input) {
	  
	  $pattern = '/[a-zA-Z]{2,15}/';
	  if(preg_match($pattern, $input)) {
		   return true;	  
	  } else {
		  return false;
	  }
  
  }
    function checkState($input) {
	  $pattern = '/[a-zA-Z]{2}/';
	  if(preg_match($pattern, $input)) {
		   return true;	  
	  } else {
		  return false;
	  }
  }  

I run them like…

if(checkFirstName($_POST['First_Name'])) {  $_SESSION['First_Name'] = $input; } else { header('Location: index.php?error=1'); } 
if(checkState($_POST['State'])) {  $_SESSION['State'] = $input; } else { header('Location: index.php?error=5'); } 

I have 2 problems, when I submit the form, this is what happens


why is the SESSION variable not set? heres that field

<input type="text" name="First_Name" class="form-control" id="name" value="<?=$_SESSION['First_Name']?>">

As my understanding, you are appending a variable that does not exist. The problem is that you believe your function will return a variable along with the value of it based on your input, but that is not true. Since you don’t have a returning variable, $input becomes invalid. Even if you return the value of $input inside your function, you would then need to globalize it in order for it to be called outside of the function. Unless you specifically give the function checking that variable and then reference it. This whole idea won’t work. I am not sure how it’s going to be done in procedural, but if it’s just like OOP, then you would have to separate your function checking from the actual logic. Like so

$input = checkFirstName($_POST['First_Name']);
if($input == false) {

    header('Location: index.php?error=1');

} else {

    $_SESSION['First_Name'] = $input;

}

However, this will only give $_SEESSION['First_Name'] the value of true. So you would have to do more work. Also, if you want the user’s post value, why not create a variable for $_POST['First_Name'] and then just reference that variable and append it to $_SESSION['First_Name']?


NOTE


This example snippet is not tested since I am on my phone. So don’t blame me if it doesn’t work.

1 Like

Exactly that.

Function parameters exist only within that function - you should perhaps have a read up on variable scope:

// this is your mainline code
// here, $input does not exist
if (checkFirstName($_POST['First_Name'])) { .. do some some } else { .. do not}
..
..
function checkFirstName($input, $regex) { // this is where $input starts to exist
// it contains whatever you pass in as the first argument.
.. 
..
..
} // and this is where $input ceases to exist, at the end of the function,

In the same way that your function doesn’t need to know about any variables outside of the function, any variables inside the function are only available within that function unless you specifically declare them as global. This is why, in the example above, you don’t need to care whether or not your main code also contains a variable called $input - the one declared as a parameter for the function will not overwrite the other one.

All you need to do to fix the code simply is

if(checkFirstName($_POST['First_Name'])) {  $_SESSION['First_Name'] = $_POST['First_Name']; } else { header('Location: index.php?error=1'); } 
3 Likes