Variable Scope

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

Variable Scope

Post 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:
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Variable Scope

Post 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.
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

Re: Variable Scope

Post by gautamz07 »

Thank you .
Post Reply