2

I'm building a class that returns an string that will include files in a folder automatically, kinda like a loader for an HTML file.

Here's the method that will be called:

function build_external_file_include($_dir){
    $_files = scandir($_dir);
    $_stack_of_file_includes = "";//will store the includes for the specified file.
foreach ($_files as $ext){
    //split the file name into two;
    $fileName = explode('.',$ext, 1);//this is where the issue is.

    switch ($fileName[1]){
        case "js":
            //if file is javascript
             $_stack_of_file_includes =  $_stack_of_file_includes."<script type='text/javascript' src='".$dir.'/'.   $ext ."'></script>";

            break;
        case "css";//if file is css
             $_stack_of_file_includes =  $_stack_of_file_includes."<link rel=\"stylesheet\" type=\"text/css\" href=\"".$dir.'/'. $ext."\" />";
            break;
        default://if file type is unkown
             $_stack_of_file_includes =  $_stack_of_file_includes."<!-- File: ".  $ext." was not included-->";
    }


}
return $_stack_of_file_includes;
}

So, this runs without any errors. But, it doesn't do what it's supposed to do... or at least what I intend it to do. Technically speaking here,

$fileName[1] should be the extension js

$fileName[0] should be name of the file main

but

$fileName[0] is main.js.

does explode not recognize .?

Thank you in advance.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Philll_t
  • 4,267
  • 5
  • 45
  • 59
  • Change `$fileName = explode('.',$ext, 1);` to `$fileName = explode('.',$ext);` – Gabriel Santos May 03 '12 at 04:36
  • i'll suggest you to use [`pathinfo()`](http://php.net/manual/en/function.pathinfo.php) instead of explode – xkeshav May 03 '12 at 04:38
  • @felipe.. what will you with these filenames `jquery-.1.7.1.min.js` – xkeshav May 03 '12 at 04:40
  • diEcho, hi, thank you for your interest! This particular class builds a set of HTML external file references for CSS and JS files. As you can see here, the script is set to loop through files in a specified directory and return a string that has HTML tags that reference external files, in this case the files in that folder. – Philll_t May 05 '12 at 04:38

2 Answers2

6

You're forcing your resulting array to have 1 element, which causes it to have the entire filename.

explode( '.', $ext, 1 )

should instead be

explode( '.', $ext );

Proof: http://codepad.org/01DLpo6H

Sampson
  • 265,109
  • 74
  • 539
  • 565
0

You've limited the explode to producing 1 array entry, so it can never do anything:

print_r(explode('.', 'a.b', 1));
Array
(
    [0] => a.b
)

The limit should be at least 2. or, better yet, you should be using the pathinfo() function, which properly handles filename components for you.

Marc B
  • 356,200
  • 43
  • 426
  • 500