How to work with pretty URLs - PHP - php

i followed up multiple tutorials how to make pretty URL but never actualy make it work (prolly i didnt get something).
What i want:
From something like this:
http://www.example.com/api/v1/get.php?user=UserName&id=7Ka2la2
I want to make something like this:
http://www.example.com/UserName/get/7Ka2la2
What i did try:
As I mentioned I try to follow multiple tutorials but nothing worked for me. So i try something by my self.
//.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
</IfModule>
What it does:
it checks if the request filename isn't a file
and checks if it isn't a directory
then, the RewriteRule makes a call to index.php, no matter what was written in the URL
And in my index.php file it looks like this
<?php
function parse_path() {
$path = array();
if (isset($_SERVER['REQUEST_URI'])) {
$path = explode('/', $_SERVER['REQUEST_URI']);
}
return $path;
}
$path_info = parse_path();
echo '<pre>'.print_r($path_info, true).'</pre>';
switch($path_info[1]) {
case 'get': include 'get.php';
break;
default:
include '404.php';
}
So it basicly should just split url to array and then base on URL include right file (in this example its get.php). However like this i can load a file but i have nothing in my $_GET and $_POST which make my script useless for me.
Question:
My code will somehow do what i want so base on url it load content but $_GET and $_POST will not work correctly here. So my question is did I make it wrong way? If yea how should looks the right one and if not how I can access $_GET and $_POST variabiles

You can set$_GET yourself. $_POST is unaffected by the rewrite.
Try this if you like:
<?php
function parse_path() {
$path = array();
if (isset($_SERVER['REQUEST_URI'])) {
$path = explode('/', $_SERVER['REQUEST_URI']);
}
return $path;
}
$path_info = parse_path();
echo '<pre>'.print_r($path_info, true).'</pre>';
// SET UP $_GET HERE
$_GET['user'] = $path_info[0];
$_GET['id'] = $path_info[2];
switch($path_info[1]) {
case 'get': include 'get.php';
break;
default:
include '404.php';
}
But if you can still modify the code that looks for $_GET you might want to consider not using $_GET like this, and rather set up some sort of class that contains the values.
And you also might want to consider doing your url rewriting so as to map the original request to something that has get variables.
eg
//.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/(.+)/(.+)$ /api/v1/$2.php?user=$1&id=$3 [L]
</IfModule>

Related

Understanding the front controller with PHP

I'm very new with PHP, and I've managed to create a really rough CMS. At the moment, it's using many different pages and includes.
However, if possible I'd like to use a controller rather than having lots of pages (I've already got article.php/admin.php).
As an example, I'm trying to convert to something like this:
switch ( 'admin' ) {
case 'home':
include 'view/home.php';
break;
case 'admin':
include 'view/admin.php';
break;
case 'article':
include 'view/article.php';
break;
default:
echo 'default';
break;
}
This would be used with $_GET['page'], so the admin URL looks like: http://cms.dev/?page=admin
However, what happens if I need to go to a subdirectory of admin? For example, if these were hardcoded pages, I would go admin/new-post.php. Is there an equivalent I could get, using the $_GET method?
Sorry if this has not been explained well. Let me know and I will try and edit it. I've used a smorgsaboard of tutorials so I'm not 100% on any of this.
You can have forward slashes in your $_GET['page'] variable, so https://cms.dev/?page=admin/new-post.php should work fine.
Alternatively you can put this into your .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
And then get it from the REQUEST_URI:
$uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

Implementing friendly links into custom CMS [duplicate]

Normally, the practice or very old way of displaying some profile page is like this:
www.domain.com/profile.php?u=12345
where u=12345 is the user id.
In recent years, I found some website with very nice urls like:
www.domain.com/profile/12345
How do I do this in PHP?
Just as a wild guess, is it something to do with the .htaccess file? Can you give me more tips or some sample code on how to write the .htaccess file?
According to this article, you want a mod_rewrite (placed in an .htaccess file) rule that looks something like this:
RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1
And this maps requests from
/news.php?news_id=63
to
/news/63.html
Another possibility is doing it with forcetype, which forces anything down a particular path to use php to eval the content. So, in your .htaccess file, put the following:
<Files news>
ForceType application/x-httpd-php
</Files>
And then the index.php can take action based on the $_SERVER['PATH_INFO'] variable:
<?php
echo $_SERVER['PATH_INFO'];
// outputs '/63.html'
?>
I recently used the following in an application that is working well for my needs.
.htaccess
<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On
# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>
index.php
foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
// Figure out what you want to do with the URL parts.
}
I try to explain this problem step by step in following example.
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like
www.website.com/profile.php?id=username
example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
Simple way to do this. Try this code. Put code in your htaccess file:
Options +FollowSymLinks
RewriteEngine on
RewriteRule profile/(.*)/ profile.php?u=$1
RewriteRule profile/(.*) profile.php?u=$1
It will create this type pretty URL:
http://www.domain.com/profile/12345/
For more htaccess Pretty URL:http://www.webconfs.com/url-rewriting-tool.php
It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide
ModRewrite is not the only answer. You could also use Options +MultiViews in .htaccess and then check $_SERVER REQUEST_URI to find everything that is in URL.
There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.
One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].
You can easily extract the /path/to/your/page/here bit with the following bit of code:
$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));
From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)
It looks like you are talking about a RESTful webservice.
http://en.wikipedia.org/wiki/Representational_State_Transfer
The .htaccess file does rewrite all URIs to point to one controller, but that is more detailed then you want to get at this point. You may want to look at Recess
It's a RESTful framework all in PHP

URL Manipulation PHP

I have a url something like
http://something.com/abc/def/file.php/arguments
This simply executes final.php and /arguments is passed to $_SERVER['PATH_INFO'] variable.
I want to execute the same but without the '.php' i.e,
http://something.com/abc/def/file/arguments
I am guessing I need to add something to http.conf, or...?
.htaccess is your friend
Options +FollowSymLinks
RewriteEngine on
RewriteRule file/(.*) file.php?param=$1
I think the best way to do this is to adopt the MVC style url manipulation with the URI and not the params.
In your htaccess use like:
<IfModule mod_rewrite.c>
RewriteEngine On
#Rewrite the URI if there is no file or folder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
Then in your PHP Script you want to develop a small class to read the URI and split it into segments such as
class URI
{
var $uri;
var $segments = array();
function __construct()
{
$this->uri = $_SERVER['REQUEST_URI'];
$this->segments = explode('/',$this->uri);
}
function getSegment($id,$default = false)
{
$id = (int)($id - 1); //if you type 1 then it needs to be 0 as arrays are zerobased
return isset($this->segments[$id]) ? $this->segments[$id] : $default;
}
}
Use like
http://mysite.com/posts/22/robert-pitt-shows-mvc-style-uri-access
$Uri = new URI();
echo $Uri->getSegment(1); //Would return 'posts'
echo $Uri->getSegment(2); //Would return '22';
echo $Uri->getSegment(3); //Would return 'robert-pitt-shows-mvc-style-uri-access'
echo $Uri->getSegment(4); //Would return a boolean of false
echo $Uri->getSegment(5,'fallback if not set'); //Would return 'fallback if not set'
Now in MVC There usually like http://site.com/controller/method/param but in a non MVC Style application you can do http://site.com/action/sub-action/param
Hope this helps you move forward with your application.
So you want to rewrite your URL's. Have a look here: http://corz.org/serv/tricks/htaccess2.php
This URL style can be managed by the url_rewrite (called url rewriting) and it can be done with .htaccess file of your Apache server.
to do it you'll need to write this in you .htaccess file:
RewriteEngine On
RewriteRule ^http://something.com/every/name/you/like/(arguments)/?$ server_folder/page.php?argument_var=$1
The first block of code, rapresents the user called page:
^http://something.com/every/name/you/like/(arguments)/?$
The second block is the real page you want to call, where $1 is the var value inside the ()
server_folder/page.php?argument_var=$1
If the user must go to an URL where the arguments are numbers only you should insert:
^http://something.com/every/name/you/like/([0-9])/?$
If the user must go to an URL where the arguments are letters only you should insert:
^http://something.com/every/name/you/like/([a-zA-Z])/?$
To work correctly with this URL style you'll need to understand a little bit of regular expresions like in this link.
You could find useful this table to help you understand something more.
Note you can write different URL instead of the real page name like:
^http://something.com/love/([a-zA-Z0-9])/?$ section/love/search.php?$1
This should be useful to hide server pages.

how do I create the following .htaccess file

I have written the following code in my .htaccess file
Options +FollowSymLinks
RewriteEngine on
RewriteRule page/(.*)/ index.php?page=$1&%{QUERY_STRING}
RewriteRule page/(.*) index.php?page=$1&%{QUERY_STRING}
The url "xyz.in/index.php?page=home" will look like this in the address bar of browser "xyz.in/page/home"
If I want to pass a variable through URL than I will have to write as "xyz.in/page/home?value=1" or "xyz.in/page/home?value=1&value2=56&flag=true"
The initial part of url (xyz.in/page/home) is clean(search engine friendly), but if I pass some more variables in the url then it doesn't look nice.
I want to make this url like
"xyz.in/page/home/value/4/value2/56" and so on.
The variables value and value2 are not static they are just used for example over here. Name can be anything.
Is it possible to do this ?
Please help me form the ".htaccess" file
(any corrections related to title or language or tags used in this question are welcome)
Thanks
The easiest would be to parse the URL path with PHP. Then you would just need this rule to rewrite the requests to your PHP file:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index\.php$ index.php [L]
The condition will ensure that only requests to non-existing files are rewritten.
Your PHP script could than look like this:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', ltrim($_SERVER['REQUEST_URI_PATH']));
for ($i=0, $n=count($segments); $i<$n; $i+=2) {
$_GET[rawurldecode($segments[$i])] = rawurldecode($segments[$i+1]);
}

How to create friendly URL in php?

Normally, the practice or very old way of displaying some profile page is like this:
www.domain.com/profile.php?u=12345
where u=12345 is the user id.
In recent years, I found some website with very nice urls like:
www.domain.com/profile/12345
How do I do this in PHP?
Just as a wild guess, is it something to do with the .htaccess file? Can you give me more tips or some sample code on how to write the .htaccess file?
According to this article, you want a mod_rewrite (placed in an .htaccess file) rule that looks something like this:
RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1
And this maps requests from
/news.php?news_id=63
to
/news/63.html
Another possibility is doing it with forcetype, which forces anything down a particular path to use php to eval the content. So, in your .htaccess file, put the following:
<Files news>
ForceType application/x-httpd-php
</Files>
And then the index.php can take action based on the $_SERVER['PATH_INFO'] variable:
<?php
echo $_SERVER['PATH_INFO'];
// outputs '/63.html'
?>
I recently used the following in an application that is working well for my needs.
.htaccess
<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On
# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>
index.php
foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
// Figure out what you want to do with the URL parts.
}
I try to explain this problem step by step in following example.
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like
www.website.com/profile.php?id=username
example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
Simple way to do this. Try this code. Put code in your htaccess file:
Options +FollowSymLinks
RewriteEngine on
RewriteRule profile/(.*)/ profile.php?u=$1
RewriteRule profile/(.*) profile.php?u=$1
It will create this type pretty URL:
http://www.domain.com/profile/12345/
For more htaccess Pretty URL:http://www.webconfs.com/url-rewriting-tool.php
It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide
ModRewrite is not the only answer. You could also use Options +MultiViews in .htaccess and then check $_SERVER REQUEST_URI to find everything that is in URL.
There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.
One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].
You can easily extract the /path/to/your/page/here bit with the following bit of code:
$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));
From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)
It looks like you are talking about a RESTful webservice.
http://en.wikipedia.org/wiki/Representational_State_Transfer
The .htaccess file does rewrite all URIs to point to one controller, but that is more detailed then you want to get at this point. You may want to look at Recess
It's a RESTful framework all in PHP

Categories