Jump to content

[SOLVED] Variable scope


joesaddigh

Recommended Posts

I have stole a function from the net that generates a random password put it in its own .php file and am including it in my script.

 

The random password prints to the screen but the password variable is empty. Does anybody have any idea what the problem could be?

 

The code is as follows:

 

 

The calling script

        include "generatepassword.php";
$password = generatePassword();	
echo $password;

 

 

 

The function

<?php
function generatePassword ($length = 
{	
  // start with a blank password
  $password = "";

  // define possible characters
  $possible = "0123456789bcdfghjkmnpqrstvwxyz"; 

  // set up a counter
  $i = 0; 

  // add random characters to $password until $length is reached
  while ($i < $length) { 

	// pick a random character from the possible ones
	$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

	// we don't want this character if it's already in the password
	if (!strstr($password, $char)) { 
	  $password .= $char;
	  $i++;
	}

  }
  echo "The random password generated is " . $password;	
}
?>

 

Thanks

 

 

Link to comment
https://forums.phpfreaks.com/topic/149124-solved-variable-scope/
Share on other sites

the function doesn't return a variable, it just echos it. your main PHP script has no knowledge of the variables within the script, so you cannot echo it outside of the function.  change it to something like this

 

<?php
   function generatePassword ($length = 
   {   
     // start with a blank password
     $password = "";
   
     // define possible characters
     $possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
      
     // set up a counter
     $i = 0; 
      
     // add random characters to $password until $length is reached
     while ($i < $length) { 
   
      // pick a random character from the possible ones
      $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
         
      // we don't want this character if it's already in the password
      if (!strstr($password, $char)) { 
        $password .= $char;
        $i++;
      }
   
     }
     echo "The random password generated is " . $password;   
     return $password;
   }
?>

 

and I think that will work

Is there a way of making variables global. If you want to use variables in different .php files how do you do this. Do you need to declare them differently?

 

Why would you want it global? There is no reason, just use it like you have:

 

$password = generatePassword(); 

 

That is the point of functions, I would remove the echo $password in the function, as you do not need to echo it.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.