Link to home
Start Free TrialLog in
Avatar of prowebinteractiveinc
prowebinteractiveinc

asked on

global or session variables

I have a application form and a includes functions.php file

in the appication form page I am calling a function within a if() that validates an email address
therefore I have to return a true or false, but in the function I have a errorMsg that tells them either the email is already in our database, or the email address in not valid, since I am returning a true or false already how do I get the errorMsg on my application pg from the functions.php file
// apllication.php
if(is_valid_email($myEmail))
{
     do something
}

Open in new window

// functions.php
function is_valid_email($email){		
         if(preg_match($regex, $email)){ $isvalidEmail = true; }
		else{ $isvalidEmail = false; $errorMsg = "You Have entered an invalid email address."; }
		if(mysql_num_rows($getEmailsInDbQuery) == 0){ $isAlreadyRegistered = true; }
		else{ $isAlreadyRegistered = false; $errorMsg = "The email your are trying to use is already registered in our system."; }
		if($isvalidEmail && $isAlreadyRegistered){ return true; }
		else{ return false;}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Hugh McCurdy
Hugh McCurdy
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The trick is the & in the function signature for $errorMessage.  This means that the function will update (not just use) the passed variable.  This is often called "pass by reference" instead of "pass by value."  (Without the &, it becomes "pass by value")
Avatar of prowebinteractiveinc
prowebinteractiveinc

ASKER

whats is the & sign in the function for ?
The & changes the variable to "pass by reference."

If you change the value of such a variable inside the function, the value of the variable is changed outside the function as well (which is what it appears you want).

Without the &, it is passed by value.  In that case, if you change the value of the variable inside the function, the value outside the function is left unchanged.
so does that mean I return false and I return $errorMsg ? 2 returns ?
No need for 2 returns.  The way you are setting $errorMsg in your function is perfect.

The only problem is I used $errorMessage and you used $errorMsg.  I should have used $errorMsg in my example.
When you return false, you are interested in the contents of $errorMsg.  Otherwise, it worked and you don't really care what is in that variable.
didnt work, besides the fact the method is depreciated, it doesnt work, I used $_SESSION, if you think of a better way, please let me know

thanks
You could use a SESSION variable but that requires that the user has cookies enabled.

I don't understand why the approach I gave didn't work for without.  The deprecated warning should happen if you use the & in the function call.  I wanted you to use it in the function definition.

http://php.net/manual/en/language.references.pass.php

I can look at the non-working code.  I suspect it's wrong, in that you got a deprecation warning.

Here is a working program (ran it from the shell in Linux) that works.  It's not the problem you are trying to solve but it "returns" different error messages depending on the problem.

<?php
function divide_integer ( $dividend, $divisor, &$remainder, &$errorMsg )
{
  $errorMsg = "";

  if ( ! is_int ( $dividend ))
  {
    $errorMsg = "dividend must be an integer";
    return FALSE;
  }

  if ( ! is_int ( $divisor ))
  {
    $errorMsg = "divisor must be an integer";
    return FALSE;
  }

  $remainder = $dividend % $divisor;

  $quotient = ( $dividend - $remainder ) / $divisor;

  return $quotient;
}


function test ( $dividend, $divisor )
{
  $errorMsg = "";

  echo "Attempting integer division on $dividend divided by $divisor" . PHP_EOL;

  $quotient = divide_integer ( $dividend, $divisor, $remainder, $errorMsg );

  if ( $quotient != FALSE )
  {
    echo "Quotient  is $quotient" . PHP_EOL;
    echo "Remainder is $remainder" . PHP_EOL;
  }
  else
  {
    echo "Error: $errorMsg" . PHP_EOL;
  }
  echo PHP_EOL;
}

test ( 20, 3 );
test ( 20.2, 3 );
test ( 20, 3.2 );

?>

Open in new window


Here's the output when I run the program.

Attempting integer division on 20 divided by 3
Quotient  is 6
Remainder is 2

Attempting integer division on 20.2 divided by 3
Error: dividend must be an integer

Attempting integer division on 20 divided by 3.2
Error: divisor must be an integer

Open in new window




Again, I think the updated program that didn't work has an error because the approach (as you can see, works.  If you post the program, I'll look at it.
A function can return only one variable, but the variable it returns is not limited to a scalar value.  A function can return an array or an object, or an array of objects, etc.  It just has to be a single variable.  So the array you return from an email validation could be something with TRUE or FALSE in position 0, and any error message in position 1.

But to the design of a function that tests for valid email and also checks the data base for previous registrations -- that seems like it should be two entirely different functions.

Here is my teaching example of how to test for a valid email, modified to return not only TRUE or FALSE, but also an explanatory error message.
<?php // RAY_email_validation_with_message.php
error_reporting(E_ALL);


// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
// SEE MAN PAGE: http://php.net/manual/en/intro.filter.php
function check_valid_email($email)
{
    // RETURNS A TWO-POSITION ARRAY
    $return = array();

    // LIST OF BLOCKED DOMAINS
    $bogus = array
    ( '@unknown.com'
    , '@example.com'
    , '@gooseball.org'
    )
    ;

    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
        {
            $return[0] = FALSE;
            $return[1] = "FAILED FILTER_VAR()";
            return $return;
        }
    }

    // IF LOWER-LEVEL PHP, WE CAN CONSTRUCT A REGULAR EXPRESSION
    else
    {
        $regex
        = '/'                        // START REGEX DELIMITER
        . '^'                        // START STRING
        . '[A-Z0-9_-]'               // AN EMAIL - SOME CHARACTER(S)
        . '[A-Z0-9._-]*'             // AN EMAIL - SOME CHARACTER(S) PERMITS DOT
        . '@'                        // A SINGLE AT-SIGN
        . '([A-Z0-9][A-Z0-9-]*\.)+'  // A DOMAIN NAME PERMITS DOT, ENDS DOT
        . '[A-Z\.]'                  // A TOP-LEVEL DOMAIN PERMITS DOT
        . '{2,6}'                    // TLD LENGTH >= 2 AND =< 6
        . '$'                        // ENDOF STRING
        . '/'                        // ENDOF REGEX DELIMITER
        . 'i'                        // CASE INSENSITIVE
        ;
        // TEST THE STRING FORMAT
        if (!preg_match($regex, $email))
        {
            $return[0] = FALSE;
            $return[1] = "FAILED REGEX TEST";
            return $return;
        }
    }

    // TEST TO SEE IF THE DOMAIN IS IN OUR BLOCKED LIST
    foreach ($bogus as $badguy)
    {
        if (stripos($email, $badguy))
        {
            $return[0] = FALSE;
            $return[1] = "BLOCKED DOMAIN";
            return $return;
        }
    }

    // FILTER_VAR OR PREG_MATCH DOES NOT TEST IF THE DOMAIN IS ROUTABLE
    $domain = explode('@', $email);

    // MAN PAGE: http://php.net/manual/en/function.checkdnsrr.php
    if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
    {
        $return[0] = TRUE;
        $return[1] = NULL;
        return $return;
    }

    // EMAIL IS NOT ROUTABLE
    $return[0] = FALSE;
    $return[1] = "NOT ROUTABLE";
    return $return;
}



// DEMONSTRATE THE FUNCTION IN ACTION
$e = NULL;
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    $r = check_valid_email($e);
    if ($r[0])
    {
        echo "<br/>VALID: $e";
    }
    else
    {
        echo "<br/>BOGUS: $e";
        echo "<br/>$r[1]";
    }
}


// END OF PROCESSING - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<form>
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" value="$e" />
<input type="submit" />
</form>
ENDFORM;

echo $form;

Open in new window