Page 1 of 1

Variable Scope

Posted: Thu May 22, 2014 2:36 pm
by gautamz07

Code: Select all

<?php

$mypass = 'purplevalley';

function thecheck()  {

if (isset($_POST['password'])){
	$password = $_POST['password'];
	if(!empty($password)){
		if($mypass == $password){
			echo "Match found ";
		}
		else{
			echo "security breach";
		}
	}
	else {
		echo "You need to try entering something .. ALL THE
		BEST";
	}
}

}



?>

<form action="post.php" method="POST">
	Password :<br/>
	<input type="password" name="password"><br/><br/>
	<input type="submit" value="Submit">
</form>

<?php

thecheck();

 ?>

this is the error i get when i enter a wrong password

"Undefined variable: mypass in C:\xampp\htdocs\Trial\post.php on line 10"

Why ? is't $mypass a global variable ?? :banghead:

Re: Variable Scope

Posted: Thu May 22, 2014 2:52 pm
by requinix
No. PHP does not have a global variable scope* - variables defined outside functions are not available inside functions. There is file scope and there is function scope and they are completely separate**.

Pass $mypass as an argument to your function.

* Except the special "superglobal" variables $_GET, $_POST, etc.
** There are ways around this that you should not use.

Re: Variable Scope

Posted: Thu May 22, 2014 3:12 pm
by gautamz07
Thank you .