0

Im trying to read css files from a directory and create the respective html markup, like

<link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap.css"> 

PHP

 $css_dir = 'application/resources/css';

$fp = opendir($css_dir);
while ($file = readdir($fp)) 
{
if (strpos($file, '.css',1))
$results[] = $this->base.'/'.$file;                 
}
closedir($fp);

print_r($results);

this works correctly creating an array with results like [1] => Directory/name.css which is fine but if I change the results line to something like

$results[] = '<link rel="stylesheet" type="text/css" media="screen" href="'.$this->base.'/'.$file.'">';

I get am empty array, the problem is with the '<' '>' symbols is there no way to do this in one go without having to then do a foreach through the results array?

7
  • Be aware - and this is just a warning - that if you plan on making this a public-facing application, it is very insecure to blindly load files in a directory. Good luck Commented Dec 28, 2013 at 20:36
  • 3
    What? Did you check the source code, since <link ..> probably won't show on the screen - but nevertheless it should work. However, it can be simplified by using glob Commented Dec 28, 2013 at 20:37
  • @David can you explain how? A user will not be able to place any files into that directory without root access. Commented Dec 28, 2013 at 20:39
  • 2
    Try echo '<pre>' . htmlentities(print_r($results, true)) . '</pre>'; to see the results literally. Commented Dec 28, 2013 at 20:41
  • @Barmar thanks this is just what I needed, i forgot link will just get rendered and won't show up on the print_r. Commented Dec 28, 2013 at 20:42

1 Answer 1

1

Instead of using < and > use &lt; and &gt; accordingly, or htmlspecialchars()

Improvement in your functional code

 /* This is the WRONG way to loop over the directory. */
    while ($entry = readdir($handle)) {
        echo "$entry\n";
    }

 /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }

Reference

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.