HTTP status code 404 but contents are loading perfectly fine - php

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

Related

Pretty URL Conditional Rewrite

Our site allows for a pretty url 'etest.me/1234' where '1234' is a client id. As you can see below it redirects to our route.php file where we do our redirect. The problem is when a client uses 'etest.me' without the '/1234' they get the apache 'The requested URL /go/ was not found on this server.' message. I would like the url to go to another page when the '/1234' is missing.
Note that we have the domain and path forwarded to the non-existing '/go' directory so the rules below will catch it. The following is in our .htaccess file in the root directory.
RewriteEngine On
#restrict rewriting URLs ONLY to paths that DO NOT exist
RewriteCond %{SCRIPT_FILENAME} !-d
# commented out to speed up looking since we are not processig file names anyway
#RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^go/([a-zA-Z0-9/]+)$ ./route\.php?go=$1
Working perfectly fine for me. Hope this will work for you as well.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^go/([a-zA-Z0-9]+)$ /route.php?go=$1 //when client id exist
RewriteRule ^([a-zA-Z0-9]+)$ /index.php // when no client id
You can add a new rule to handle this situation:
RewriteRule ^go/$ ./another_script\.php
I accepted the answer by Sahil and posted the entire logic below for others to use:
Domain: etest.me
Pretty URL: etest.me/1234 (where '1234' is a client id)
Forwarded to: etesting.io/go (with forward path option selected so the '/1234' will be include in the forward)
Note: There is no '/go' directory on the server, '/go' is used to trigger the redirect.
Wanted 'etest.me' (without client id) to go to index file in root directory.
Here is the rewrite rules in .htaccess:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^go/([a-zA-Z0-9/]*)$ ./route\.php?go=$1
Here is the route.php code:
<?php
if($_GET['go']){
$a = explode('/', $_GET['go']);
$c = count($a);
if($c == 1 || $c == 2){
header('location: ../../index.php?aid=' . $a[0] . '&tid=' . $a[1]);
exit;
}
else{
die('Invalid URL');
}
}
else{
header('location: ../index.php');
exit;
}
And finally the index.php file:
if($_GET['aid'] && $_GET['tid']){
header('location: test/register.php?aid=' . $_GET['aid'] . '&tid=' . $_GET['tid']);
exit;
}
elseif($_GET['aid']){
header('location: test/index.php?aid=' . $_GET['aid']);
exit;
}
else{
header('location: account/index.php?' . $_SERVER['QUERY_STRING']);
exit;
}
Hope this helps somebody in the future.
I would like a more elegant solution but it's behind me for now...

Avoiding 302 redirect when setting up multiple 404 pages

My error page is a PHP file, the entirety of which is
<?php
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$parts = explode('/', $path_parts['dirname']);
if (in_array("abcde", $parts))
{
header('Location: https://example.com/vwxyz/abcde-error-page.php');
exit();
}
else
{
header('Location: https://example.com/vwxyz/error-404-page.php');
exit();
}
?>
I want users who go to a non-existent URL in the "abcde" directory to see a particular error page, and the URL should be https://example.com/vwxyz/abcde-error-page.php and the status code should be 302. This is working just fine.
I want users who go to any other non-existent URL (in the "vwxyz" directory, or anywhere else on example.com) to see https://example.com/vwxyz/error-404-page.php, but for a 404 status code to be returned, and the URL in their browser should still be whatever they erroneously typed in. Of course, that doesn't work with header('Location ... and I can't use file_get_contents or include because the result empties the shopping cart and logs out the user (if they were logged in).
I feel that there is a simpler way to have multiple 404 pages without editing the .htaccess file (though the argument will probably be made that that is indeed the simpler way). And it is vital that the main error page behave exactly like a normal error page, but that the other (for the "abcde" directory) be a redirect, and that that special error page for the "abcde" directory NOT be in that directory (the user gets redirected out of the directory and then shown the "error"page, which should NOT return a 404 status).
If I understand the question correctly it is pretty simple via a root .htaccess file.
# enable mod_rewrite and route the request
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ^/abcde/?.*$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /vwxyz/abcde-error-page.php [R=302,L]
# sets a custom 404 page
ErrorDocument 404 /vwxyz/error-404-page.php
First you need to switch the rewrite engine on, then perform 3 checks:
Does the URL begin with /abcde/
Is the URL not a file
Is the URL not a directory
If those things are all true then you want to route (with a 302) to /vwxyz/abcde-error-page.php
For any genuine 404 error you can just use the default ErrorDocument 404 ... syntax.
(OK this was 6 lines in .htaccess - twice as complicated as I guessed)

.htaccess Rewrite Rule not affecting GET on page

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).

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

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