November 27th, 2008 at 12:53 pm
What is a dynamic variable, or a variable variable, as they are sometimes called? When you create a variable, you give it a name. Consider this PHP example:
The first line will create the variable $foo and assign the string value 'test' to it. In the second line, the content of the variable $foo will be printed. So far, nothing exciting. But now consider this:
PHP:
-
<?php
-
$bar = 'foo';
-
$$bar = 'test';
-
-
?>
(Note the double $ sign at the beginning of the second line.) What happens here? First, the value 'foo' is assigned to the variable bar. In the second line, a variable is created, and this variable's name will be the content of the variable $bar. This means, the variable $foo is created. Hence, the third line will output testfoo. You can also have dynamic variables in arrays and objects, even as function aliases:
PHP:
-
<?php
-
$foobar = $foo[$bar];
-
$foobar = $foo->$bar;
-
-
// want to match case sensitive or not?
-
$stripos_func = ($casesensitive) ? 'strpos' : 'stripos';
-
var_dump( $stripos_func('ABC',
'ab') );
// true if $casesensitive==false
-
?>
0
Various
dynamic, PHP, variable
November 19th, 2008 at 12:29 pm
Here's a snippet of PHP code that can create passwords. It can create passwords of different lengths, it can use different sets (uppercase and lowercase letters as well as numbers), and it can be told to exclude potentially confusing characters.
PHP:
-
<?php
-
function passgen($length=8, $reqsets='uln', $noconfusing='true')
-
{
-
$length = (int)$length;
-
if ($length> 20 || $length <3) $length = 8;
-
-
// some characters look alike. let's optionally exclude them.
-
$confusing = ($noconfusing === 'true') ? 'O01Il' : '';
-
-
$randchars = $token = '';
-
-
-
'u' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
-
'l' => 'abcdefghijklmnopqrstuvwxyz',
-
'n' => '0123456789'
-
// you can even add an own set
-
);
-
-
if ($reqsets)
-
{
-
$reqsets = str_split($reqsets);
-
-
-
$randchars .= $sets[$availset];
-
}
-
-
if (!$randchars)
-
-
-
for ($i=0; $i<=$length; $i++)
-
{
-
do
-
{
-
-
$letter =
substr($randchars,
$lpos,
1);
-
}
-
while ( in_array($letter, str_split
($confusing) ) );
-
-
$token .= $letter;
-
}
-
return $token;
-
}
-
-
echo passgen
($_GET['length'],
$_GET['sets'],
$_GET['noconfusing']);
-
?>
If you intend to use this in a script, please keep in mind that mt_rand() needs to be seeded/initialized properly.
0
Codebits
generator, password, PHP