Solved

global or session variables

Posted on 2012-03-10
10
139 Views
Last Modified: 2012-04-05
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

0
Comment
Question by:prowebinteractiveinc
  • 6
  • 3
10 Comments
 
LVL 13

Accepted Solution

by:
Hugh McCurdy earned 500 total points
Comment Utility
function is_valid_email ( $email, &$errorMessage )
{
    ....
}

$errorMessage = "";  // Always a good idea to initialize variables.

if ( is_valid_email ( $email, $errorMessage )
{
    // good section
}
else
{
    echo $errorMessage . "<br />" . PHP_EOL;
}


Does that work for you?
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
Comment Utility
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")
0
 

Author Comment

by:prowebinteractiveinc
Comment Utility
whats is the & sign in the function for ?
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
Comment Utility
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.
0
 

Author Comment

by:prowebinteractiveinc
Comment Utility
so does that mean I return false and I return $errorMsg ? 2 returns ?
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 13

Expert Comment

by:Hugh McCurdy
Comment Utility
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.
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
Comment Utility
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.
0
 

Author Comment

by:prowebinteractiveinc
Comment Utility
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
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
Comment Utility
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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now