How is it websites use dashes like in this Reddit URL(https://www.reddit.com/r/AskReddit/comments/7onp85/what_can_you_add_to_mac_n_cheese_to_make_it_even/) rather than using $_GET statements in PHP(www.google.com?post=mac_n_cheese_to_make&vartwo=test)?
-
1Can you clarify your question with further examples? PHP is not the only server side language. Also - that example contains no dashes "-" but lots of underscores "_" that are simply placeholders for spaces in english. – Andrew M Jan 26 '18 at 09:11
-
FYI: it's the `7onp85` that tells the server what to load, the `what_can_you_add_to_mac_n_cheese_to_make_it_even/` bit can be altered without changing the content of the page. In this case the server will redirect to an unchanged version of the url. – KIKO Software Jan 26 '18 at 09:13
-
1see this: https://stackoverflow.com/questions/812571/how-to-create-friendly-url-in-php – Rizwan Khan Jan 26 '18 at 09:16
1 Answers
In PHP you can get the path used to access a resource with the $_SERVER global variable.
In your case :
PHP File: /r/AskReddit/comments/7onp85/what_can_you_add_to_mac_n_cheese_to_make_it_even/index.php
<?php
echo $_SERVER['REQUEST_URI'];
should return :
/r/AskReddit/comments/7onp85/what_can_you_add_to_mac_n_cheese_to_make_it_even/
The only problem is that if the folders don't exist, or the file index.php
doesn't exist in path /r/AskReddit/comments/7onp85/what_can_you_add_to_mac_n_cheese_to_make_it_even/
you will end up with a 404 Not Found Error.
To remedy on this, you usually tell your WebServer (Apache, Nginx, etc.) that every request has to be processed by one single script, say /index.php
on document root.
For Apache, this can be done with a simple .htaccess
file in the root of the web server :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d # if the request [-d]irectory !exists
RewriteCond %{REQUEST_FILENAME} !-f # or if the request [-f]ile !exists
RewriteRule . /index.php [L] # then execute /index.php
This basically tells apache to redirect every request with an invalid path to the /index.php file in the root of you webserver. Instead of ending with a 404, the /index.php script will be executed.
You can then parse the $_SERVER['REQUEST_URI'] variable and print different outputs depending on the path the script has been accessed with.

- 87
- 1
- 11
-
1by far it is easyer to use a PHP router which support wildcard like fastroute :) – Ngob Jan 26 '18 at 09:57
-
1I think routers are easier to use when you understand the basics behind it. And you still need to rewrite nevertheless. – ClemB Jan 26 '18 at 10:14