Search code examples
phprouteshttp-status-code-404

PHP Routes Not Working On Published Site (Vanilla PHP)


I have this index.php:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Title</title>
  </head>
  <body>
    <?php 

      $routes = [];

      route('/', function () {
        require_once "pages/homepage/homepage.php";
      });

      route('/gallery', function () {
        require_once "pages/gallery/gallery.php";
        echo "gallery";
      });

      route('/about_us', function () {
        require_once "pages/about_us/about_us.php";
      });

      route('/404', function () {
        require_once "pages/404/404.php";
      });

      function route(string $path, callable $callback) {
        global $routes;
        $routes[$path] = $callback;
      }

      run();

      function run() {
        global $routes;
        $uri = $_SERVER['REQUEST_URI'];
        $found = false;
        foreach ($routes as $path => $callback) {
          if ($path !== $uri) continue;

          $found = true;
          $callback();
        }

        if (!$found) {
          $notFoundCallback = $routes['/404'];
          $notFoundCallback();
        }
      }
      ?>
  </body>
</html>

NOTE: Project requires vanilla PHP.

My problem is with the routing. It works fine when I run in it on localhost ex: localhost:3000/gallery, etc. but it returns a 404 error when ran on published site ex: url.com/gallery. Is this a proper way of routing in PHP?


Solution

  • This approach is generally fine for small websites and apps. If it ever tends to grow I would recommend considering using a framework like Laravel for example.

    But for your problem, my guess is that you are lacking an .htaccess file. You need to tell the server that regardless of the URL the site visitor is trying to get, it should try and run index.php and not some other file.

    Have a look at this thread

    Also, second thing to try is to append yourwebsite.com/gallery**.php** just to see if that helps before anything. But even if it does, still you need an htaccess file to remove the .php file. Good and safe practice