.htaccess Rewrite Rule not affecting GET on page - php

Sample Code
Here is a sample of my .htaccess file:
RewriteEngine On
RewriteRule ^home/?$ index.php?intro=true [L]
RewriteRule ^home/([^/]*)$ index.php?location=$1&intro=true [L]
RewriteRule ^wedding/?$ wedding.php [L]
RewriteRule ^wedding/([^/]*)$ wedding.php?location=$1 [L]
And here is some sample code that is featured on both the index.php and wedding.php page:
index.php:
if(!$_GET["location"]) { $location = "London"; } else { $location = ucwords($_GET["location"]); }
[....]
<h1>Ben Pearl, <?php echo $location; ?> Magician</h1>
wedding.php:
if(!$_GET["location"]) { $location = "London"; } else { $location = ucwords($_GET["location"]); }
....
<h1><?php echo $location; ?> Wedding Magician</h1>
What is supposed to happen
The $location string should be effected by the $_GET value 'location'.
What is happening
The rewrite is working fine on index.php; if a user goes to example.com/home/place, $location is replaced by place.
However, on every other page (including the page with script pasted above), the string is replaced by "london", implying that the page hasn't received the $_GET data and the rewrite rule is not working correctly.
What's stranger is that the exact same code, unaltered, worked fine on my localhost.

Try turning off Multiviews, which turns on mod_negotiation's "fuzzy" request URI to file mapping. When mod_negotiation sees /wedding/ and then it sees that there's a file /wedding.php, it'll kick in and send the request directly there, completely bypassing mod_rewrite and your rules.
On top of your htaccess file, add:
Options -Multiviews
That may also explain why it works for the rewrite to index.php, since /home doesn't look much like /index.php (whereas if you had a home.php, mod_negotiation would try to map to that instead).

Related

HTTP status code 404 but contents are loading perfectly fine

I am running a site, where I am trying my own slug mechanism.
here are my .htaccess file contents
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L,QSA]
</IfModule>
and in my index.php I have following code
$_REQUEST['action'] = trim($_SERVER['REQUEST_URI'],"/");
...
if (!empty( $_REQUEST['action'] )) {
$action = explode("/", $_REQUEST['action']);
$slug = $action[0];
$pageName = $slug.".php";
if (file_exists($pageName)) {
require_once $pageName; // 404 status code
}
else {
echo 'Your page is not found'; // 200 status code
}
} else {
require_once 'welcome.php';
}
now how it will work is
/school will be mapped on school.php
/mobile will be mapped on mobile.php
/about will be mapped on about.php
apparently this work perfectly fine, contents are loaded fine, but issue with HTTP status code which is 404
on the other hand if I type some thing random like
/some-thing-random it shows this line echo 'Your page is not found'; with 200 status code (please note some-thing-random.php does not exist)
What strangely worked for me is as follows, I just added following line in .htaccess file and its working fine now with 200 message
Options +FollowSymLinks -MultiViews
for all those concerned about manually setting header: I had not. and it should not, all sort of urls will be intercepted by index.php, at least this is what my understaing is about my .htaccess file
one more strange thing is that might help you to respond to my question is
let say
if url is as follows
www.mysite.com/about and if rename file about.php as xabout.php and then just perform following
$fileName = 'x'.$slug.'.php';
require_once($fileName);
it works fine
Now my question is what on earth is happning? can any one please explain this to me (also note that I am using GoDaddy hosting)
To send a 404 code, it must be indicated in the header.
header("HTTP/1.0 404 Not Found");
More infos on http://php.net/manual/fr/function.header.php

$_GET navigation without the use of ?page=

Solved!
first of all, I know I can use "?page=..." but I do not like that variable in my URL. Now after some searching I found a site which uses the $_GET['page'] without showing the "?page=" in the url.
But I'm having a bit of a struggle with the code. I cannot seem to get this code to work. I know it works on an other site, but not on my site. I cannot seem to find how it works on the other site.
this is the menu code:
<li>Home</li>
<li>Even voorstellen</li>
<li>De kennismaking</li>
and this is the php code:
$sExpressie = "(http:|ftp:|shttp:|www.|.php|.pl|.cgi|.asp|index.php)";
if(isset($_GET['pagina']) && eregi($sExpressie,$_GET['pagina']))
{
include("pages/home.php");
}
else
{
if(isset($_GET['pagina']) && file_exists('Pages/' . $_GET['pagina'] . ".php"))
{
include('pages/' . $_GET['pagina'] . ".php");
}
else
{
include("pages/home.php");
}
}
I don't understand how this code works. In my website the "$GET['pagina']" is never filled, which is logical. But how can it be filled in the other website?
Thanks a lot everyone!
Solution:
Add the following to your .htaccess file:
RewriteEngine On
RewriteRule ^([A-Za-z0-9-]+)/?$ pages/$1.php [NC,L]
You'll need to add the following to your .htaccess file:
RewriteEngine On
RewriteRule ^([A-Za-z0-9-]+)/?$ pages/$1.php [NC,L]
For example, if you now navigate to http://yourwebsite.com/fubar, your website will load the page located at pages/fubar.php without changing the URL.
You can use a RewriteRule within your .htaccess file.
For example:
RewriteEngine On
RewriteRule ^/(.*)$ index.php?pagina=$1 [L, QSA] #(.*) is lazy and you may want to just catch [a-z0-9].
This will "rewrite" a request like http://example.com/?pagina=even_voorstellen into something like http://example.com/even_voorstellen. Your index.php can then use $_GET['pagina'] to call the respective page.

PHP File request from url directory

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.

Help rewriting urls

So what I am trying to do is create a website where the index.php will piece all the pages together with based upon parameters sent by query string.
I want to "rewrite" the urls from the form: http://example.com/index.php?p=cat1/page1 to something like http://example.com/cat1/page1
I am attempting to make use of .htaccess mod_rewrite rules, but have been unable to make anything work.
I know there are mountains of info on this stuff.. I have spent a few hours already reading about it and tinkering, but I feel stuck. Nothing I am doing seems to yield any results.
Mod_rewrite IS loaded on the server (says phpinfo())
My .htaccess code:
RewriteEngine On
RewriteRule ^/([home|cat1|cat2]/)?([a-zA-Z]+_?)*/?$ /index.php?p=$1/$2 [L]
My index.php code:
<?php
if (isset($_GET["p"])){
$page = htmlspecialchars($_GET["p"]);
}else{
$page = "home";
}
include('./template/header.php');
if (is_dir("./pages/$page")){
include("./pages/$page/overview.php");
}else{
if (file_exists("./pages/$page.php")){
include("./pages/$page.php");
}else{
//not found
echo '<h1 id="pageNotFound">Page Not Found</h1>';
}
}
include('./template/footer.php');
?>
Here's your .htaccess fix:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !\.(jpg|jpeg|gif|png|css|js|pl|txt)$
RewriteRule ^(home|services)/([a-zA-Z_\-]+)(\/?)$ /NEP2/index.php?p=$1/$2 [NC,QSA,L]
About the PHP, can you move the pages below the public_html folder?

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