In the last section we created a function that generates random passwords. What if we want a password generator that only displays a password of a certain length? For example, what if we only want three characters, or six or eight? This is where a function that takes arguments becomes necessary. Fortunately for us, in PHP you can create such functions. The syntax for writing functions that take arguments is as follows: function function_name($argument){ statements } The argument is usually in the form of a variable, but can also be literal, or both: function function_name($argument,'Avalue'){ statements } If you do not add an argument where it is needed, the function will display a error message. The same thing will happen if you only add three arguments when a function expects four. To call a function that takes an argument is the same as calling the ones that don't take arguments. You just need to remember to pass along the needed arguments. Let's modify our randpass() function to enable us to choose how many characters we want in our password. Script:createrndpass.php <? function randpass($length) { $chars = "1234567890abcdefGHIJKLMNOPQRSTUVWxyzABCDEF $thepass = ''; for($i=0;$i<$length;$i++) { $thepass .= $chars{rand() % 39}; } return $thepass; } //to use the function $password=randpass(); ?> The above shows the result is a six character password.
And this screen shot shows the result for an eight character password.
Shown above is what happens when you don't pass an argument to the function. There are no limits to how many arguments a function can take, and you can use multiple functions in a script. You can also create a separate file for all your functions and just include it in your scripts to use the functions.
blog comments powered by Disqus |
|
|
|
|
|
|
|