server.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. if(PHP_SAPI !== "cli-server") {
  3. header("Location: /");
  4. exit();
  5. }
  6. error_reporting(E_ALL & ~E_DEPRECATED);
  7. $name = basename(__FILE__);
  8. $uri = $_SERVER["REQUEST_URI"];
  9. $uri_parts = explode("?", $uri);
  10. $_REQUEST["path"] = $uri_parts[0];
  11. chdir(__DIR__);
  12. $file_path = realpath(ltrim($uri_parts[0], '/'));
  13. error_log($file_path);
  14. if($file_path && is_dir($file_path)) {
  15. // attempt to find an index file
  16. foreach(['index.php', 'index.html'] as $index_file) {
  17. if($file_path = realpath($file_path . DIRECTORY_SEPARATOR . $index_file)) {
  18. break;
  19. }
  20. }
  21. }
  22. if($file_path && is_file($file_path)) {
  23. // 1. check that file is not outside of this directory for security
  24. // 2. check for circular reference to self
  25. // 3. don't serve dotfiles
  26. $is_current_directory = strpos($file_path, __DIR__ . DIRECTORY_SEPARATOR) === 0;
  27. $is_this_file = $file_path == __FILE__;
  28. $is_dot_file = substr($name, 0, 1) == '.';
  29. if($is_current_directory && !$is_this_file && !$is_dot_file) {
  30. $extension = strtolower(substr($file_path, -4));
  31. if($extension === '.php') {
  32. // php file; serve through interpreter
  33. include $file_path;
  34. }
  35. else {
  36. if($extension === ".css") {
  37. header("Content-Type: text/css");
  38. }
  39. if($extension === ".js") {
  40. header("Content-Type: text/javascript");
  41. }
  42. // asset file; serve from filesystem
  43. readfile($file_path);
  44. }
  45. }
  46. else {
  47. // disallowed file
  48. header("HTTP/1.1 404 Not Found");
  49. echo "404 Not Found";
  50. }
  51. }
  52. else {
  53. // rewrite to our index file
  54. include __DIR__ . DIRECTORY_SEPARATOR . 'index.php';
  55. }