I\'m looking for a tutorial or explaination on how to do very basic php routing.
For example when I visit a link like: mywebsite.com/users I want to run the get meth
Well... there are many framework in internet for php routing. If you want you can try that from https://packagist.org/search/?q=route. But to be honest, if you are from procedural PHP world, it could be problematic for you first time.
If you like, you can use following code written by Jesse Boyer that I used to for my own projects. You application structure should follows-
[Application-folder]
* @copyright Copyright (C), 2011-12 Jesse Boyer
* @license GNU General Public License 3 (http://www.gnu.org/licenses/)
* Refer to the LICENSE file distributed within the package.
*
* @link http://jream.com
*
* @internal Inspired by Klein @ https://github.com/chriso/klein.php
*/
class Route
{
/**
* @var array $_listUri List of URI's to match against
*/
private static $_listUri = array();
/**
* @var array $_listCall List of closures to call
*/
private static $_listCall = array();
/**
* @var string $_trim Class-wide items to clean
*/
private static $_trim = '/\^$';
/**
* add - Adds a URI and Function to the two lists
*
* @param string $uri A path such as about/system
* @param object $function An anonymous function
*/
static public function add($uri, $function)
{
$uri = trim($uri, self::$_trim);
self::$_listUri[] = $uri;
self::$_listCall[] = $function;
}
/**
* submit - Looks for a match for the URI and runs the related function
*/
static public function submit()
{
$uri = isset($_REQUEST['uri']) ? $_REQUEST['uri'] : '/';
$uri = trim($uri, self::$_trim);
$replacementValues = array();
/**
* List through the stored URI's
*/
foreach (self::$_listUri as $listKey => $listUri)
{
/**
* See if there is a match
*/
if (preg_match("#^$listUri$#", $uri))
{
/**
* Replace the values
*/
$realUri = explode('/', $uri);
$fakeUri = explode('/', $listUri);
/**
* Gather the .+ values with the real values in the URI
*/
foreach ($fakeUri as $key => $value)
{
if ($value == '.+')
{
$replacementValues[] = $realUri[$key];
}
}
/**
* Pass an array for arguments
*/
call_user_func_array(self::$_listCall[$listKey], $replacementValues);
}
}
}
}
here in 2nd line, instead of '/php/cfc/' you need to put your localhost project directory name, such as 'Application-folder'
RewriteEngine On
RewriteBase /php/cfc/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?uri=$1 [QSA,L]
In index.php file, you need to write following codes-
This things work perfectly for me. Hope it will work for you too...
Happy Coding... :)