Advertisement

Create Simple Router with PHP


 

A brief explanation of a Router on a website is calling a file or a function from a url. for example in calling a url like this:

http://example.com/index.php/content/1
The router function will process the directory after index.php and then divide it into a file caller and a parameter instead of  $_GET.

public function parseURL(){
		$url = $_SERVER['REQUEST_URI'];
		$indexPos = strpos($url, 'index.php');

		if ($indexPos !== false) {
			$path = substr($url, $indexPos + strlen('index.php'));
			
		}
		if(isset($path)){
			$url = rtrim($path, '/');
			$url = filter_var($url, FILTER_SANITIZE_URL);
			$url = explode('/', $url);
			return $url;
		}

	}

You need a __construct function on a class to distribute router conditions.

<?php
/**
 * Author   : Muhammad Deril
 * URI      : http://www.derillab.com
 * Github   : @derilkillms
 */

class Routes
{

	public $page = 'posts';
	public $params =[];

	public function __construct(){
		GLOBAL $CFG, $DB, $mustache;
		$url = $this->parseURL();

		if (isset($url)) {


			$url = array_filter($url, function($value){
				return $value != '';
			});

			$url = array_slice($url,0);

			if (isset($url[0])) {
				if(file_exists('pages/'.$url[0].'.php')){
					$this->page = $url[0];
					unset($url[0]);
				}
			}	

		}

		$this->params = $url;

		require_once 'pages/'.$this->page.'.php';

	}

	public function parseURL(){
		$url = $_SERVER['REQUEST_URI'];
		$indexPos = strpos($url, 'index.php');

		if ($indexPos !== false) {
			$path = substr($url, $indexPos + strlen('index.php'));
			
		}
		if(isset($path)){
			$url = rtrim($path, '/');
			$url = filter_var($url, FILTER_SANITIZE_URL);
			$url = explode('/', $url);
			return $url;
		}

	}
	
	
}

?>

After doing parse_url() in your __construck function you split the $url array into pages or params
after calling page / file then the array is unset and the rest will be a page parameter. You only need to specify the directory where to save the web page file, here I put it in the 'page' folder.
The final step is you only need to call the Router function to your start page, you can put it in your index.php or config file.

<?php
require_once(__DIR__ .'/routes.php');
$OUTPUT = new Routes();

Post a Comment

0 Comments