Super simple routing with PHP

Aug 29, 2020 PHP Routing

First of all

“Is this kind of routing? (´・_・`)”

That’s the kind of Tsukkomi I accept. **I recommend it. **

“Recommend? ('・_・`)”

Thing you want to do

For example

/pages/index.php?page=1

Not a URL like

/pages/1/

I want to process it. That’s it. That’s all (´・_・`)

.htaccess

It is necessary to control the server side to process with index.php instead of 404 even if a strange URL is accepted, rather than the program itself. For that, set .htaccess.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /pages/
RewriteRule ^index\.php$-[L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ./pages/index.php [L]
</IfModule>

Actually, this is just .htaccess of Wordpress. With this setting, the directory where you installed Wordpress will handle all requests with index.php under the root. The root of a huge system called Wordpress is routing, and I feel like I’m watching this.

index.php

By the way. Since every request is processed by index.php, we will receive the URL at that time as a string, process it, and use it as a parameter.

<html>
<?php
  $url = $_SERVER['REQUEST_URI'];
  $url = str_replace("/pages/", "", $url);
  $url = str_replace("/", "", $url);
  
  if (ctype_digit($url)) {
    echo "page number → ". $url;
  } else {
    echo "non-numeric";
  }
?>
</html>

Convert the received URL string to a numerical value after removing unnecessary characters by replacement. It’s just that program.

This time, I gave the Ichiou sample program to the free server. Please change various pages/ and change appropriately. http://tabelog2001.php.xdomain.jp/pages/ Please change this part to an appropriate number /

that’s all