note 100221 deleted from function.opendir by cmb

From: Date: Tue, 11 Jun 2019 06:40:29 +0000
Subject: note 100221 deleted from function.opendir by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-211224@lists.php.net to get a copy of this message
Note Submitter: sebastian dot kroskiewicz at gmail dot com ---- If you search for a comfortable way to include javascript code from other javascript code, here is a useful tool based on opendir(): <?php class JSIncluder { private static $included = array(); private static function ext($filename) { return pathinfo($filename, PATHINFO_EXTENSION); } public static function includeFile($file) { if (isset(JSIncluder::$included[$file])) return; JSIncluder::$included[$file] = true; $contents = file_get_contents($file); preg_match_all('/\/\*include:([^*]+)\*\//', $contents, $deps); foreach ($deps[1] as $dep) { if (is_file($dep)) { JSIncluder::includeFile($dep); } else JSIncluder::includeAll($dep); } echo '<script type="text/javascript">' . $file . '</script>' . PHP_EOL; } private static function includeAll($dir) { if (($handle = opendir($dir))) { while ($file = readdir($handle)) { clearstatcache(); if (is_file($dir . '/' . $file)) { if (JSIncluder::ext($file) == 'js') { JSIncluder::includeFile($dir . '/' . $file); } } elseif ($file != '..' && $file != '.') JSIncluder::includeAll($dir . '/' . $file); } closedir($handle); } } } ?> Now, you can just write <?php JSIncluder::includeFile('path/to/script/main.js') ?> in your <head> section and then you can include files directly from your javascript files by typing /*include:path/to/other/script/foo.js*/ anywhere! For example: /*include:scripts/lib*/ //it will include the whole lib dir and its subdirectories /*include:scripts/helloworld.js*/ //it will include only one file $(function() { $(body).html('Hello world!'); }); and in your html code: <head> <?php JSIncluder::includeFile('scripts/main.js') ?> </head> The JSIncluder should be safe, because all the work is done server-side and clients just can't affect anything. They could write /*include:/foo/bar*/ but nothing will happen, because the code does nothing but automatically generates <script> tags in specific order in your <head> section. Feel free to modify my code. I believe that it will be useful!

« previous php.notes (#211224) next »