PHP routing not working unless using an absolute path with index.php

3.8k views Asked by At

With nikic/fast-route PHP package for url routing :

PHP url routing doesn't work unless I specify the whole path for the route instead of just the name of the route :

For example, in order to create a route for /hello-world, I have to specify the whole path : localhost/myProject/public/index.php/hello-world

$r->addRoute('GET', '/localhost/myProject/public/index.php/hello-world', function () {
        echo 'Hello World';
    });

Is there something that needs to be done in the .htaccess file ?

specifics about the current project :

I'm not using a framework but Patrick Louys' No Framework tutorial on GitHub : https://github.com/PatrickLouys/no-framework-tutorial

I'm using XAMPP on Fedora Linux as a web server

my code resides in my /home directory while the Web server is in /opt/lampp ... I've linked them with a symbolic link : sudo ln -s /home/... /opt/lampp/htdocs (if that matters)... I know that the tutorial rely on PHP built-in server (php -S localhost:8000)

3

There are 3 answers

0
Maxime Bonin On BEST ANSWER

My quick fix :

1- Create a .htaccess file in the public directory. All requests will be forwarded to index.php

2- Add a function to parse the whole URL submitted in order to retrieve the proper URI. Basically the function trims the whole url like localhost/public/index.php/hello-world and returns /hello-world. /hello-world being the route registered by our fast-route router, the appropriate controller will be called when such an url is received by our web server

Source (explanations and code example) : http://blogs.shephertz.com/2014/05/21/how-to-implement-url-routing-in-php/

0
Daniele Lupo On

Maybe it's wrong, but instead of /helloworld you must write ./helloworld

0
Art_Code On

You must put your code (files) inside the htdocs folder following this path:

/opt/lampp/htdocs/

Then create your folder named hello-world, this folder must be inside the htdocs folder this way:

/opt/lampp/htdocs/hello-world

Next open a terminal and access like root user, change directory to hello-world and then you have to give the permision to the folder like this:

chmod 667 hello-world -R

-R is used to give permision to the folder hello-world and all the file inside it. And that's all! Now when you try localhost/hello-world you will see your project now working!

Note: If this do not work try creating a php file called test.php inside the htdocs folder following the path /opt/lampp/htdocs/. That file must have this inside:

<h1><b><?php echo "hello wordl!"; ?></b></h1>

Again you must give the file the permision (chmod 667). Then copy this and paste it in your browser navigation bar:

localhost/test.php

You must see in your browser a big hello world in bold style.