Solved

global or session variables

Posted on 2012-03-10
10
140 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
ID: 37705578
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
ID: 37705580
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
ID: 37705581
whats is the & sign in the function for ?
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 37705605
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
ID: 37705616
so does that mean I return false and I return $errorMsg ? 2 returns ?
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 37705684
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
ID: 37705689
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
ID: 37705872
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
ID: 37705985
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 109

Expert Comment

by:Ray Paseur
ID: 37707276
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
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…
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…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

831 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