Forum Moderators: coopster

Message Too Old, No Replies

Defining a Variable inside a function

Defining a Variable inside a function

         

drooh

7:05 pm on May 9, 2007 (gmt 0)

10+ Year Member



I am having a problem dDefining a Variable inside a function. Basically I am creating a simple contac form that submits to itself and runs a few checks before sending the data.

I use a function to verify the email is in a correct format and if it fails I want to set a variable $msg1 = "error"; and have that echo on the form. it seems the current way I have my script that it is not working how I would think. Here is my code.

<?php
$msg1 = "";

if(isset($_POST['sub'])){

$name= $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$comment = $_POST['comment'];

// validate email is correct format
function check_email($email) {
$pattern = "/^[\w-]+(\.[\w-]+)*@";
$pattern .= "([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i";
if (preg_match($pattern, $email)) {
$parts = explode("@", $email);
{
// return true;
$msg1 = "good";
}
} else {
$msg1 = "error";
// return false;
}
}
check_email($email);
}

?>

<form method="POST" name="contact" action="page.php" >

Email<?php echo $msg1?><br />
<input type="text" name="email" size="32"><br /><br />

<input type="submit" value="Submit" name="sub">

---

any help is appreciated! thanks :)

StupidScript

8:57 pm on May 9, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Not too bad ... a couple of nesting things. First, pull the function out of the conditional statement. It's just confusing, in there. Second, count your curly-braces! :) And don't forget never to trust user input. Give this a whack:

<?php
$msg1 = "";
#validate email is correct format
function check_email($email) {
$pattern = "/^[\w-]+(\.[\w-]+)*@";
$pattern .= "([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i";
if (preg_match($pattern, $email)) {
$parts = explode("@", $email);
if ($parts[ 1 ]) {
$msg1 = "good";
return true;
}
else {
$msg1 = "error";
return false;
}
#end preg_match if
}
#end function
}
if(isset($_POST['sub'])){
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$subject = htmlspecialchars($_POST['subject'], ENT_QUOTES, 'UTF-8');
$comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');
return check_email($email);
#end if
}
?>
Sorry, can't post an array reference, so $parts[ 1 ] shouldn't have any spaces between the brackets ... MOD: Looks fine in preview, but not when posted.

[edited by: StupidScript at 9:04 pm (utc) on May 9, 2007]