It's pretty hard to explain so if somebody have a better title then be my guest..
Basically I made a website with 5 pages.
1) index.html
2) page.html
3) footer.html
4) menu.html
5) contact.html
In order to access the pages you have to type the page name at the end of the domain (I bet you knew that..)
I wanted to access the pages with a code..
for example -> mywebsite.com\?page=contact
How can I do this ?
Kind Regards,
Kobi.
why don't make a index.php with following code:
<?php
include($_GET['page'].'.html');
?>
The result will be:
calling mywebsite.com/?page=contact will open mywebsite.com/index.php?page=contact because this is default
the url will stay mywebsite.com/?page=contact
the script load the file contact.html and show it
You only need to configure whatever web server you have to look for a file called index.php whenever you don't specify any. That has been a pretty standard feature of all web servers since the early 1990s. In Apache you'll use the DirectoryIndex directive; this is what mine looks like:
<IfModule dir_module>
DirectoryIndex index.php index.html
</IfModule>
Then, write PHP code in such index.php to act as router. You should check Variables From External Sources and learn about $_GET.
However, that's probably not the best layout. Friendly URLs have been around for years:
http://example.com/contact
... and it's again mostly a web server feature. In Apache you'd use the mod_rewrite module. Here's a sample rule used by some PHP frameworks:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Requested path can be parsed out of $_SERVER['REQUEST_URI'].
Once you put your hands in the index.php file there're a lot of design patterns you can use (modern frameworks often use a third-party router and template engine) but if you're to learn from scratch and just want to get something done quickly from static HTML you can use a combination of switch statements (to create a route white list) and readfile() to inject each file into the output. (Beware that PHP include construct family will handle files as PHP code, which is not what you want.)
<?php
define('INC_PATH', __DIR__ . '/../wherever/includes/are');
switch ($_GET['page']) {
case 'contact':
case 'help':
case 'whatever':
$page = $_GET['page'];
break;
default:
$page = 'error';
}
readfile(INC_PATH . '/index.html');
readfile(INC_PATH . '/page.html');
readfile(INC_PATH . '/footer.html');
readfile(INC_PATH . '/menu.html');
readfile(INC_PATH . "/$page.html");
Related
I have built a website with a homemade MVC structure and pretty urls with .htaccess aren't working at all.
I have this "front controller" (index.php) at the root of my website :
<?php
require_once('M/connect_sql.php');
if (!empty($_GET['page']) && is_file('C/'.$_GET['page'].'.php'))
{
include 'C/'.$_GET['page'].'.php';
}
else
{
include 'C/accueil.php';
}
$bdd = NULL;
C/ is my controller folder.
Example of my urls :
http://domain.com/?page=restaurants&city=paris&CP=75001
page parameter is for my controller and &city=paris&CP=75001 are POST variables.
I have tested a simple rewrite rule out of MVC and it works well.
I tried several Rewrite rules but none are working.
Here's an example for the URL above :
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.+/)/([^/.]+)/([^/.]+)/?$ /?page=$1&city=$2&CP=$3 [NC,L]
</IfModule>
I have placed an .htaccess in every folder (root, controller, views), but I can't get it.
EDIT SINCE RESPONSE :
Here's my new controller since Entwicklerpages notice a security hole. Found this solution here : http://kkovacs.eu/exploiting-web-development-worst-practices-file-inclusion
if ( isset($_REQUEST['page']) and ! is_null($_REQUEST['page']) )
{
$page = $_REQUEST['page'];
switch ($page) {
case 'restaurant':
include('C/restaurant.php');
break;
case 'restaurants':
include('C/restaurants.php');
break;
}
}
else {
include('C/accueil.php');
}
Be aware of the security hole in your implementation!
It is never a good idea to let the user decide which php files are included.
include 'C/'.$_GET['page'].'.php';
https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion
Also, a second idea from my site.
The $_SERVER Variable in PHP have a field called PATH_INFO
$_SERVER['PATH_INFO']
If your site is called as index.php/your/params/and/other/data
You can split it by the '/' and get all your data.
Also this may be a little easier to make it fancy with ModRewrite
https://secure.php.net/manual/en/reserved.variables.server.php
I use this at my own site: http://www.entwicklerpages.de/Startseite.html (German)
I have a userprofile system in which a dynamic page (profile.php) changes as the id of user changes..
For eg. profile.php?id=2 displays the profile of user having id=2.. But i want the address to be as user/user_name.php. So providing each user a unique profile-page address..
Is it possible without creating a seperate page for each user?
Thnx
Ok, let´s talk about apache´s mod_rewrite. Basically what people usually do is that they setup one php page eg. index.php and redirect all the requests there (except those that request existent files and directories) and index.php then routes these requests to proper files/presenters/controllers, etc.
I´m gonna show you a very simple example how can this be done, it´s just to give you the idea how it works in basics and ofc there are better ways to do this (for example take a look at some framework).
So here is the very simple .htaccess file, placed in the same directory as index.php:
<IfModule mod_rewrite.c>
RewriteEngine On
# prevents files starting with dot to be viewed by browser
RewriteRule /\.|^\. - [F]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?query=$1 [L]
</IfModule>
And here is the index.php:
<?php
$request = explode("/", $_GET["query"]);
// now you have your request in an array and you can do something with it
// like include proper files, passing it to your application class, whatever.
// for the sake of simplicity let me just show you the example of including a file
// based on the first query item
// first check it´s some file we want to be included
$pages = array("page1", "page2", "page3");
if(!in_array($request[0], $pages)) $request[0] = $pages[0];
include "pages/".$request[0];
But I highly recommend you not to reinvent the wheel and take a look at some existing php framework. You´ll find out that it saves you a lot of work, once you learn how to use it ofc. To mention some - Zend Framework, Symfony and the one I´m using - Nette Framework. There are many more, so choose whatever suits your needs.
I am designing a website. I want my website address to look like the following image:
I don't want my website to look like http://something.example/profile.php.
I want the .php extension to be removed in the address bar when someone opens my website. In other words, I want my website to be like: http://something.example/profile
As a second example, you can look at the Stack Overflow website address itself.
How can I get this done?
Just add an .htaccess file to the root folder of your site (for example, /home/domains/domain.example/htdocs/) with the following content:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
More about how this works in these pages: mod_rewrite guide (introduction, using it), reference documentation
First, verify that the mod_rewrite module is installed. Then, be careful to understand how it works, many people get it backwards.
You don't hide URLs or extensions. What you do is create a NEW URL that directs to the old one, for example
The URL to put on your web site will be yoursite.example/play?m=asdf
or better yet
yoursite.example/asdf
Even though the directory asdf doesn't exist. Then with mod_rewrite installed you put this in .htaccess. Basically it says, if the requested URL is NOT a file and is NOT a directory, direct it to my script:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /play.php [L]
Almost done - now you just have to write some stuff into your PHP script to parse out the new URL. You want to do this so that the OLD ones work too - what you do is maintain a system by which the variable is always exactly the same OR create a database table that correlates the "SEO friendly URL" with the product id. An example might be
/Some-Cool-Video (which equals product ID asdf)
The advantage to this? Search engines will index the keywords "Some Cool Video." asdf? Who's going to search for that?
I can't give you specifics of how to program this, but take the query string, strip off the end
yoursite.example/Some-Cool-Video
turns into "asdf"
Then set the m variable to m=asdf.
So both URLs will still go to the same product
yoursite.example/play.php?m=asdf
yoursite.example/Some-Cool-Video
mod_rewrite can do lots of other important stuff too, Google for it and get it activated on your server (it's probably already installed.)
You have different choices.
One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder.
and you can give orders to this page in this way:
Old page: http://something.example/profile.php?id=a&abc=1
New page: http://something.example/profile/?id=a&abc=1
If you are not satisfied leave a comment for complicated methods.
Here is a simple PHP way that I use.
If a page is requested with the .php extension then a new request is made without the .php extension. The .php extension is then no longer shown in the browser's address field.
I came up with this solution because none of the many .htaccess suggestions worked for me and it was quicker to implement this in PHP than trying to find out why the .htaccess did not work on my server.
Put this at the beginning of each PHP file (preferrably before anything else):
include_once('scripts.php');
strip_php_extension();
Then put these functions in the file 'scripts.php':
//==== Strip .php extension from requested URI
function strip_php_extension()
{
$uri = $_SERVER['REQUEST_URI'];
$ext = substr(strrchr($uri, '.'), 1);
if ($ext == 'php')
{
$url = substr($uri, 0, strrpos($uri, '.'));
redirect($url);
}
}
//==== Redirect. Try PHP header redirect, then Java, then http redirect
function redirect($url)
{
if (!headers_sent())
{
/* If headers not yet sent => do php redirect */
header('Location: '.$url);
exit;
}
else
{
/* If headers already sent => do javaScript redirect */
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
/* If javaScript is disabled => do html redirect */
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0; url='.$url.'" />';
echo '</noscript>';
exit;
}
}
Obviously you still need to have setup Apache to redirect any request without extension to the file with the extension.
The above solution simply checks if the requested URI has an extension, if it does it requests the URI without the extension. Then Apache does the redirect to the file with the extension, but only the requested URI (without the extension) is shown in the browser's address field.
The advantage is that all your "href" links in your code can still have the full filename, i.e. including the .php extension.
The problem with creating a directory and keeping index.php in it is that
your links with menu will stop functioning
There will be way too many directories. For eg, there will be a seperate directory for each and every question here on stackoverflow
The solutions are
1. MOD REWRITE (as suggested above)
2. use a php code to dynamically include other files in index file. Read a bit more abt it here http://inobscuro.com/tutorials/read/16/
Actually, the simplest way to manipulate this is to
Open a new folder on your server, e.g. "Data"
Put index.php (or index.html) in it
And then the URL www.yoursite.example/data will read that index.php file. If you want to take it further, open a subfolder (e.g. "List") in it, put another index.php in that folder and you can have www.yoursite.example/data/list run that PHP file.
This way you can have full control over this, very useful for SEO.
same as Igor but should work without line 2:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Tony, your script is ok, but if you have 100 files? Need add this code in all these :
include_once('scripts.php');
strip_php_extension();
I think you include a menu in each php file (probably your menu is showed in all your web pages), so you can add these 2 lines of code only in your menu file. This work for me :D
Remove a file extension through .htaccess:
Original URL: http://ravinderrathore.herobo.com/contact.php
.htaccess rule to remove .php, .html, etc. file extensions from URLs:
RewriteRule ^(.*)$ $1.php
After Rewriting: http://ravinderrathore.herobo.com/contact
RewriteEngine on
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^index(.*)?$ index.php$1 [L,QSA]
RewriteRule ^login_success(/)?$ login_success.php [L,QSA]
RewriteRule ^contact(/)?$ contact.php [L,QSA]
just nearly the same with the first answer about, but some more advantage.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
Just add up if you have a other file-extension in your sites
For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccessbut this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.
I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css,js and phpfiles even more like images or whatever you have.
Cr8Router - Simple PHP Router
I would like to quickly set up a RESTful site using PHP without learning a PHP Framework. I would like to use a single .htaccess-file in Apache or a single rule using Nginx, so I easyli can change web server without changing my code.
So I want to direct all requests to a single PHP-file, and that file takes care of the RESTful-handling and call the right PHP-file.
In example:
The user request http://mysite.com/test
The server sends all requests to rest.php
The rest.php call test.php (maybe with a querystring).
If this can be done, is there a free PHP-script that works like my rest.php? or how can I do this PHP-script?
Using Apache Mod Rewrite:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^test$ rest.php [nc]
Yes, make a 404 Redirect to a page called rest.php. Use $url = $_SERVER['REQUEST_URI']; to examine the url. In rest.php you can redirect to wherever you want.
This only requires one rule (404 in your .htaccess file).
You have to be careful and make sure that if the page requested (e.g. mysite.com/test1 doesn't have a test1.php) errors out with a 404 you don't get yourself caught in a loop.
Modified slightly from the way that Drupal does it. This redirects everything to rest.php and puts the original requested URL into $_GET['q'] for you do take the appropriate action on. You can put this in the apache config, or in your .htaccess. Make sure mod_rewrite is enabled.
RewriteEngine on
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ rest.php?q=$1 [L,QSA]
If all you then want to do is include the requested file, you can do something like this
<?php
if (!empty($_GET['q'])) {
$source = $_GET['q'] . '.php';
if (is_file($source)) {
include $source;
} else {
echo "Source missing.";
}
}
?>
You really don't want to do that, however; if someone were to request '/../../../etc/passwd', for example, you might end up serving up something you don't want to.
Something more like this is safer, I suppose.
<?php
if (!empty($_GET['q'])) {
$request = $_GET['q'];
switch ($request) {
case 'test1':
include 'test1.php';
break;
default:
echo 'Unrecognised request.';
break;
}
}
?>
ok assume i have php page
has this name name.php?get= and has get varible named get
ok
how i can make it appear like that name?get=
If you are using apache, mod_rewrite is one way to go. There is a whole bunch of mod_rewrite tricks here.
I'd seriously reconsider before using (or overusing) mod_rewrite.
In almost all of my projects I use a simple mod rewrite in the .htaccess:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^.*$ ./
AddHandler php5-script .php
This tells the server to forward all pages to / (index.php) unless a file otherwise exists.
In the root directory I have a folder called "views" with all of the pages that I use. E.g. the file used for /home would actually be /views/home.php. However, in the index.php I have a script that parses the user's url, checks for the file, and includes that.
$page = substr($_SERVER['REQUEST_URI'], 1);
if(!$page) :
header("Location: /home");
if(file_exists("views/$page.php")) :
include "views/$page.php";
else :
include "views/$page.php";
endif;
This creates a variable called $page that stores the value of everything in the URL after the domain name. I use a substr() function on the Request URI to get rid of the trailing forward slash (/) on the URL.
If the variable is empty, for example if the user is simply at http://example.com or http://example.com/ then it forwards them to /home, where the script then checks for the home.php file inside of the views folder. If that file exists, it includes it, and displays it to the user.
Else, the script will simply include the 404 page telling the user that the file doesn't exist.
Hopefully this helps you, and if you need any further explanation I'd be happy to help!
I think you're wanting to re-write the URL client-side, which would include mod_rewrite.
In the route of your website, create a file called .htaccess and place the following code in it:
RewriteEngine on
RewriteRule ^name?get=(.*) /name.php?get=$1
Now when you type http://www.example.com/name?get=something, it will actually map to http://www.example.com/name.php?get=something transparently for you.
As far as i could understand your question, you can not strip the file extension because otherwise it will not run. In other words, you can not change:
name.php?get=
into
name?get=
But if you mean to create links with query string values that you can put them in hyperlinks in this way:
Click here !!
If you're looking to create links using a variable '$get', then you can create the link like this:
<a href="name.php?get=$get>Link</a>
Or if you want to get the value of the query string variable, you can use this:
$get = $_GET['get']