0

I've been working on a php dynamic drop down list that scans a folder on the web server and list its contents it works hears relevant selection of the code.

<?php


foreach(glob(dirname(rootdir) . '/path/username/*') as $filename){
$filename = basename($filename);
echo "<option value='filepath/username/" . $filename . "'>".$filename."</option>";
}
?>

However if i use a variable to populate part of the file path the variable doesn't get added to the path.

<?php
$name = "jsmith";

foreach(glob(dirname(rootdir) . '/path/$name/*') as $filename){
$filename = basename($filename);
echo "<option value='filepath/$name/" . $filename . "'>".$filename."</option>";
}
?>

$name = "jsmith"

The result I'm looking for is /path/$name/* = /path/jsmith/ and filepath/$name/ = filepath/jsmith/

How do I get the glob(dirname) and option value=' recognize the variables?

2 Answers2

3

You need to either concatenate the variable with the string or wrap the string in double quotes so the variable is parsed.

Double Quotes

<?php
$name = "jsmith";

foreach(glob(dirname(rootdir) . "/path/$name/*") as $filename){
$filename = basename($filename);
echo "<option value='filepath/$name/" . $filename . "'>".$filename."</option>";
}
?>

Concatenate

<?php
$name = "jsmith";

foreach(glob(dirname(rootdir) . '/path/' . $name . '/*') as $filename){
$filename = basename($filename);
echo "<option value='filepath/$name/" . $filename . "'>".$filename."</option>";
}
?>
slapyo
  • 2,979
  • 1
  • 15
  • 24
1

Single quotes do not interpolate. (i.e. Variables in the string will not be replaced with their values.) However, double-quotes do interpolate.

You'll need to change '/path/$name/*' to "/path/$name/*" or use string concatenation with '/path/' . $name . '/*' instead.

Also, you should be careful with accepting user-controlled input for $name as it may lead to a directory traversal attack.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115