I have this URL that give me two main parameters, folder and page, and som other tahat can variable to be present or not:
http://www.domain.com/adm/master.php?f=folder&p=page&otherparam1=somthing&otherparm2=somthing&otherparm3=somthing[...]
in my master.php-file I include a php-file based on these parameters:
$folder = $_GET['f'];
$page = $_GET['p'];
if(empty($page)) {
$page = 'dashboard';
}
$path = $folder.'/'.$page;
include_once 'pages/'.$path.'.php?otherparm1=somthing&otherparm2=somthing&otherparm3=somthing[...]';
The otherparam is to be multiple parameters given i the URL.
I want to rewrtite the URL to show somthing like this:
www.domain.com/adm/folder/page/somthing/somthing/somthing[...]
I have searched the web, but not been able to find a solution.
If you want to do it with simple .htacces then you can use following .htacces code:
RewriteEngine on
RewriteCond $1 !^(index\.php|css|favicon.ico|fonts|images|js|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
Basically what this code do is overwrite your request to your domain (ex: localhost/mysite), instead accessing folder or file it will access your index.php. Except for index.php, favoicon.ico, robots.txt files and css,fonts,image and js folder or what you define in second line on my code above.
Try this in your Root/.htaccess
RewriteEngine On
RewriteRule ^adm/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ /adm/master.php?f=$1&p=$2&otherparam1=$3&otherparm2=$4&otherparm3=$5 [NC,L]
$1 ,$2,$3... contains whateve value was matched in regex capture groups "([^/]+)".
This will rewrite
example.com/adm/folder/page/foo/bar/foobar
to
example.com/adm/master.php?f=folder&p=page&otherparam1=foo&otherparm2=bar&otherparm3=foobar
without changing the url in browser address bar.
Related
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
This is probably a very easy question. Anyway how do you use variables from a url without requests. For example:
www.mysite.com/get.php/id/123
Then the page retrieves id 123 from a database.
How is this done? Thanks in advance!
UPDATE
If i have the following structure:
support/
sys/
issue/
issue.php
.htaccess
home.php
etc.....
With .htaccess file containing:
RewriteEngine On
RewriteRule ^/issue/(.*)$ /issue/issue.php?id=$1 [L]
Why do I have to type:
http://www.mysite.com/support/sys/issue/issue/1234
In order to load a file? When I want to type
http://www.mysite.com/support/sys/issue/1234
also, how do I then retrieve the id once the file loads?
Problem
This is a very basic/common problem which stems from the fact that your .htaccess rule is rewriting a url which contains a directory which actually exists...
File structure
>support
>sys
>issue
issue.php
.htaccess
(I.e. the directory issue and the .htaccess file are in the same directory: sys)
Rewrite Issues
Then:
RewriteEngine ON
RewriteRule ^issue/(.*)/*$ issue/issue.php?id=$1 [L]
# Note the added /* before $. In case people try to access your url with a trailing slash
Will not work. This is because (Note: -> = redirects to):
http://www.mysite.com/support/sys/issue/1234
-> http://www.mysite.com/support/sys/issue/issue.php?id=1234
-> http://www.mysite.com/support/sys/issue/issue.php?id=issue.php
Example/Test
Try it with var_dump($_GET) and the following URLs:
http://mysite.com/support/sys/issue/1234
http://mysite.com/support/sys/issue/issue.php
Output will always be:
array(1) { ["id"]=> string(9) "issue.php" }
Solution
You have three main options:
Add a condition that real files aren't redirected
Only rewrite numbers e.g. rewrite issue/123 but not issue/abc
Do both
Method 1
RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^issue/(.*)/*$ issue/issue.php?id=$1 [L]
Method 2
RewriteEngine ON
RewriteRule ^issue/(\d*)/*$ issue/issue.php?id=$1 [L]
Method 3
RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^issue/(\d*)/*$ issue/issue.php?id=$1 [L]
Retrieving the ID
This is the simple part...
$issueid = $_GET['id'];
In your .htaccess you should add:
RewriteEngine On
RewriteRule ^id/([^/]*)$ /get.php/?id=$1 [L]
Also like previous posters mentioned, make sure you have your mod_rewrite activated.
You have to use a file called .htaccess, do a search on Google and you'll find a lot of examples how to accomplish that.
You will need mod_rewrite (or the equivalent on your platform) to rewrite /get.php/id/123 to /get.php?id=123.
I tried and tried the .htaccess method but to no avail. So I attempted a PHP solution and came up with this.
issue.php
<?php
if (strpos($_SERVER['REQUEST_URI'], 'issue.php') !== FALSE){
$url = split('issue.php/', $_SERVER['REQUEST_URI']);
}elseif (strpos($_SERVER['REQUEST_URI'], 'issue') !== FALSE){
$url = split('issue/', $_SERVER['REQUEST_URI']);
}else{
exit("URI REQUESET ERROR");
}
$id = $url[1];
if(preg_match('/[^0-9]/i', $id)) {
exit("Invalid ID");
}
?>
What you're looking for is the PATH_INFO $_SERVER variable.
From http://php.net/manual/en/reserved.variables.server.php:
'PATH_INFO'
Contains any client-provided pathname information trailing the actual
script filename but preceding the query string, if available. For
instance, if the current script was accessed via the URL
http://www.example.com/php/path_info.php/some/stuff?foo=bar, then
$_SERVER['PATH_INFO'] would contain /some/stuff.
explode() it and work on its parts.
EDIT: Use rewrite rules to map the users' request URLs to your internal structure and/or hide the script name. But not to convert the PATH_INFO to a GET query, that's totally unnecessary! Just do a explode('/',$_SERVER['PATH_INFO']) and you're there!
Also, seeing your own answer, you don't need any preg_mathes. If your database only contains numeric ids, giving it a non-numeric one will simply be rejected. If for some reason you still need to check if a string var has a numeric value, consider is_numeric().
Keep it simple. Don't reinvent the wheel!
Just wondering why no answer has mentioned you about use of RewriteBase
As per Apache manual:
The RewriteBase directive specifies the URL prefix to be used for
per-directory (htaccess) RewriteRule directives that substitute a
relative path.
Using RewriteBase in your /support/sys/issue/.htaccess, code will be simply:
RewriteEngine On
RewriteBase /support/sys/issue/
RewriteRule ^([0-9+)/?$ issue.php?id=$1 [L,QSA]
Then insde your issue.php you can do:
$id = $_GET['id'];
to retrieve your id from URL.
In my domain example.com , I want to put all page files in a directory at root for example named file. So for example I put about.php the file directory and want to let users to access this page with this URL : example.com/about
or for example put user directory in the file directory and put login.php in it , and want to let users to access it with : example.com/user/login
In fact I want to remove .php and the file from the URLs.
AND
If those files don't exist , it should load a default file like index.php at root. for example the URL example.com/blabla should be mapped to the index.php
In fact , I want to make two conditions in mod rewrite with the mentioned priority.
notice : of course I should be able to use variables like $_GET at files like about.php
UPDATE : in summary , it should work with this logic :
if the URI isn't a file or directory{
if file/URI.php is a file
load file/URI.php
else
load index.php
}
some body gave an answer to use ErrorDocument 404 index.php , but it's a really bad idea (and now has deleted his answer !)
Thanks for your help...
A conditional rewrite (if the pages exist) sounds like a bad and complicated idea, if it even is possible.
I would rewrite everything to /index.php and control everything from there:
If the components of the url lead to an existing page, use / include that content;
If no valid page is found, present your original index content.
Example redirect rules for your situation:
RewriteEngine on
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^.*$ /index.php?id=$1 [QSA,L]
Will include the requested path in id and append the variables from the original query string (the QSA flag).
More specific for your /user/login example would be:
RewriteRule ^([\w-]+)/([\w-]+)$ /index.php?path=$1&file=$2 [QSA,L]
[\w-+] : any word character (including _) and the -
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]);
}
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