I have a very simple home page (index.php) with some PHP with just a session variable called 'counter ' to see how many times the page loads. So every time I manually reload the page, the counter increases by 4. I noticed this when I had a Database operation (insert new record) previously. The page was inserting 4 new records each time. So I figured out it was not the Database, it is the page itself reloading 3 extra times. I am putting the code for the index.php and the .htaccess file for you to take a look.
index.php:
<?php
use Tarator88\Core\Misc;
use Tarator88\Core\Session\Session;
if (Session::start()::started()) { // starts session and checks if it's started
if (isset($_SESSION['index_counter'])) $_SESSION['index_counter'] += 1;
else $_SESSION['index_counter'] = 1;
}
$counter = $_SESSION['index_counter'];
Misc::pre( $counter?? 0 ); // prints out $counter
?>
.htaccess file:
AcceptPathInfo On
Options -MultiViews
Options -Indexes
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?go=$1 [NC,QSA,L]
I tried removing some stuff from the .htaccess file, which did not work. Only when I disable the .htaccess file (by renaming it to something else), the page loads just fine (no multiple reloading by itself). So I think it is somehow the .htaccess file?
The files are on localhost, on my harddisk.
I would appreciate it if you could shed some light what the problem might be. Thank you.
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
I have rewritten a PHP file's URL as:
RewriteRule ^psu/(.*)/(.*)/(.*)/(.*) _psu.php?id=$1&mb=$2&cpu=$3&name=$4 [L]
This makes the page _psu.php accessible only as:
psu/path/path/path/path
Any other URLs like:
psu/path/path/path/
psu/path/path/
psu/path/
psu
gives 404 Not Found Error.
How can I rewrite the URL - psu/path/path/path/path keeping the above URL accessible?
Try this:
RewriteEngine On
RewriteBase /
RewriteRule ^psu(?:/([^/]*)(?:/([^/]*)(?:/([^/]*)(?:/([^/]*)/?)?)?)?)?$ _psu.php?id=$1&mb=$2&cpu=$3&name=$4 [L]
In _psu.php
<?
$id = $_GET["id"];
$mb = $_GET["mb"];
$cpu = $_GET["cpu"];
$name = $_GET["name"];
echo "id: $id<br>
mb: $mb<br>
cpu: $cpu<br>
name: $name";
?>
Check Accessible URLs:
/psu/1/2/3/4
/psu/1/2/3
/psu/1/2
/psu/1
/psu
Satisfies all mentioned retirements.
To handle dynamic length path after psu use this rule in site root .htaccess:
AcceptPathInfo on
RewriteEngine On
RewriteRule ^psu(/.*)?$ _psu.php$1 [L,NC]
In inside php code of _psu.php use:
$_SERVER["PATH_INFO"]
to get path info. You can split it by / to get list of path components.
You can use:
RewriteRule ^psu(?:/([^/]*)(?:/([^/]*)(?:/([^/]*)(?:/([^/]*)/?)?)?)?)?$ _psu.php?id=$1&mb=$2&cpu=$3&name=$4 [L]
I have an instance running on EC2 that I want to password protect.
my .htaccess file;
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
RewriteCond %{REQUEST_URI} !^/healthcheck\.html$
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
AuthName "Restricted"
AuthUserFile /var/www/html/mydirectory/.htpasswd
Require valid-user
<Files "my_healthcheck_file.php">
Allow from all
Satisfy any
</Files>
.htpasswd is username:password for just now. As I am running ELB I have allowed all connections to my healthcheck file so the instance will be healthy and not blocked by password. I've needed to open this connection otherwise it returns 503 error.
I believe my problem lies with the AuthUserFile. however I have tried both /var/www/html/mydirectory/.htpasswd and the absolute path: /var/app/current/mydirectory/.htpasswd & both return error 500.
unsure what I am doing wrong, I have even checked the path is correct by doing:
<?php
$dir = dirname(__FILE__);
echo "<p>Full path to this dir: " . $dir . "</p>";
echo "<p>Full path to a .htpasswd file in this dir: " . $dir . "/.htpasswd" . "</p>";
?>
Any suggestions is much appreciated! Thanks!
TL;DR: My URL rewriting breaks if a subdirectory without a file is requested. Instead of loading a default home page as expected, I'm getting a 403 Forbidden error.
I'm using Apache URL rewriting to build a site using the Front Controller pattern. So far, my .htaccess looks like this:
Options -Indexes
RewriteCond %{REQUEST_URI} ^/(subdir|subdir/.*|subdir2|subdir2/.*).*$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+) index.php?request=$1 [QSA]
So this is working for all requests except requests for subdirectories:
mydomain.com/ results in ->
mydomain.com/index.php with home.inc content
mydomain.com/page1 results in ->
mydomain.com/index.php with /pages/page1.inc content
mydomain.com/subdir/ results in ->
403 Forbidden
mydomain.com/subdir/page1 results in ->
mydomain.com/index.php with /subdir/pages/page1.inc content
More details below that probably don't matter, since the issue is likely in the .htaccess.
In index.php, I'm catching the request and using that to grab the corresponding include page from a directory /pages which has files with the content of each page. Here's the (somewhat simplified) code from index.php:
//grab the actual HTTP request
$request = $_GET['request'];
//if the request has slashes, isolate the directory part into $dir
$slashPos = strrpos($request, "/");
if($slashPos !== false){
$dir = substr($request, 0, $slashPos) . "/";
$page = basename($request, ".inc");
} else {
$dir = "";
$page = request;
}
//use "home" if no filename is specified.
if($page==""){$page="home";}
//build path to content include
$content = $dir . "pages/" . $page . ".inc";
//output page
require("header.php");
require($content );
require("footer.php");
This works perfect for the root directory. A request for mydomain.com/page1 results in mydomain.com/index.php being served with the contents of mydomain.com/pages/page1 included.
It also works for pages within a subdirectory: a request for mydomain.com/subdir/page1 results in mydomain.com/index.php being served with the contents of mydomain.com/subdir/pages/page1 included.
It all breaks when the request is for an actual directory. So mydomain.com/subdir/ returns 403 Forbidden. Why is it doing that? I expect it to load $dir with subdir and $page with home (I set as a default for when $page=="").
Yes, Options -Indexes is probably causing the 403, but why only on subdirectories? It doesn't 403 on root. And the line RewriteCond %{REQUEST_URI} ^/(subdir|subdir/.*|subdir2|subdir2/.*).*$ in .htaccess should catch it, right?
Ok, I figured it out. The problem is that subdir wasn't actually at web root. My entire site is actually working in its own subdirectory. In other words, I wasn't working in
mydomain.com/
as the root, I was working in
mydomain.com/mydivision/
as a root. So obviously in this line:
RewriteCond %{REQUEST_URI} ^/(subdir|subdir/.*|subdir2|subdir2/.*).*$
the ^ made it look for subdir at the actual webroot. To fix I removed ^ or add my actual subdomain to that line after ^.