I have a domain www.domain.com and I have users who create profiles on it with a username. I have created a mechanism for them to access their public profile as www.domain.com/username using htaccess and some code in index.php file.
My .htaccess file looks like this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L,QSA]
An additional feature is that users can select a design (1st or 2nd design) for their profile. So I store the chosen design in database and redirect www.domain.com/username to www.domain.com/1/ or www.domain.com/2/ and load the users profile on that URL. The logic for that in PHP is
//Load profile of user
$requestURI = $_SERVER['REQUEST_URI'];
$parameterArray = explode('/', $requestURI);
$username = $parameterArray[1];
if($username != "")
{
//Get chosen design from database and store it in a variable
$chosenDesign = *Selected design value*;
header("Location: $chosenDesign/");
}
else
{
//Username not found, hence redirect to error page
header("Location: 404.html");
}
My problem is, how can I redirect in such a way that the URL is always www.domain.com/username and it loads the design in the background (logically) and displays it.
It is not possible to hide information in a visible link.
You can use a link like that:
www.domain.com/username-1 redirect to -> www.domain.com/page.php?user=username&design=1
For that kind of stuff, I use cookies...
Related
I know that similar questions were already asked, but i could not find any information for my specific "problem".
What i want to do is the following in a very dynamic way, which means that a "SuperUser" should be able to define new routes in a admin interface:
If a user enters http://www.example.com/nice-url/
he should get redirected to http://www.example.com/category.php?id=123 without changing the url.
Now there are a few ways i can achieve this. Either i use .htaccess like this:
RewriteEngine on
RewriteRule ^nice-url category.php?id=123 [L]
This works, but is not very dynamic. I would need to let a php script append new rules at the bottom which is not something i would like to do.
Or this:
.htaccess
FallbackResource /process.php
process.php
$path = ltrim($_SERVER['REQUEST_URI'], '/');
$elements = explode('/', $path);
if(count($elements) == 0) {
header("Location: http://www.example.com");
exit;
}
$sql = sprintf("SELECT Target FROM urlrewrites WHERE Source = '%s' LIMIT 1", array_shift($elements));
$result = execQuery($sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$target = $row['Target'];
header("Location: ".$target);
exit;
This also works, but sadly the url in the address bar gets changed. Is there a way in the middle of both? Having the flexibilty of PHP and the "silentness" of RewriteEngine? How do great CMS like joomla do it? Do they generate a htaccess file for each new page you create?
Thanks!
You can have this code in root .htaccess:
RewriteEngine on
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ category.php?uri=$1 [L,QSA]
PS: Note this will route /nice-url to /category.php?uri=nice-url. Then inside category.php you can dip into your database and translate $_GET['uri'] to id.
It would be more dynamic if you use regular expressions. That's how it works in CMS systems like Joomla. Good idea is to install Joomla with 'nice' URLs on and look over .htacces file to get to know how does it work.
You can start here:
http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/
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
Using mod_rewrite to use a $_GET['variable'] to grab info / pages is easy enough. How do you give a user the option to do this. For example: There URL is blah.com/user?id=74378 by default. Now they can manually create there own URL if available. How is this done? Thank you
You could maintain a table with the list of urls used. This is to check and warn the user if url is unavailable. Then, if the user tries blah.com/user/myspecialurl the htaccess should call blah.com/user?url=myspecialurl. Then use the table to find the userid and get the contents using the GET variable.
All this is under the assumption that you have a fixed format/restrictions for the url
The first part, anything, on this page will help where anything = user defined string and u process that string as a GET variable on a fixed page.
http://www.sitepoint.com/guide-url-rewriting-2/
use php module mod_rewrite, and rules in htaccess:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
and in index.php:
$page = isset($_GET['page']) ? $_GET['page'] : 'index';
// filter var $page
// ..
// then include needed page
include './pages/'.$page;
// or get content from sql
sql(..WHERE page = $page..)
I am running into the following issue:
Our members have a desire for personalized sites directly from our primary domain in the form of http://www.example.com/membername. I am looking at possibly solutions in two ways but neither are ideal (will be explained below).
Method 1 - ?Member=
In this method, I simply create a custom URL and store the information in the member's database profile. For example: if I want my "custom" URL to be jm4, for a consumer to visit my site, they must type in http://www.example.com?Member=jm4.
The site, of course, does a $_GET['Member'] to lookup the member information, stores the primary data in Session from the index page, then redirects to a homepage. The consumer no longer sees the membername in the URL but instead sees all the page names for www.example.com as if they simply visited the parent domain to start (each member's page has custom information however).
While this method works it presents the following problems:
The URL is not nearly as easy as /jm4
and any errors typing out the
wildcard ?Members= will result in
page error. Also, This method keeps
that particular member's information
in session (which is necessary
browing from page to page on that
particular member domain) and
prevents somebody from simply typing
http://www.example.com?Member=name2 to
visit another site without clearing
their session or closing the browser.
Method 2 - /membername
While the preferred method, currently the only way we know how to create is to manually generate an index file in a subfolder, redirect to the primary index then allow the consumer to view the member's personal site.
For example, if I visit www.example.com/jm4, I am hitting the /jm4 folder which contains index.php. Within this file simply contains:
<?php
session_start();
ob_start();
$_SESSION['AgentNumber'] = "779562";
header("Location: ../index.php");
exit;
?>
the primary index recognizes this with:
<?php
session_start();
ob_start();
if ($_SESSION['MemberNumber'] == NULL) {
header("Location:ac/");
exit;
}
$conn = mysql_connect("localhost", "USER", "PW");
mysql_select_db("DB",$conn);
$sql = "SELECT * FROM table WHERE MemberNumber = $_SESSION[MemberNumber]";
$result = mysql_query($sql, $conn) or die(mysql_error());
while ($newArray = mysql_fetch_array($result)) {
$_SESSION['MemberName'] = $newArray['MemberName'];
$_SESSION['MemberPhone'] = $newArray['MemberPhone'];
$_SESSION['MemberMobile'] = $newArray['MemberMobile'];
$_SESSION['MemberFax'] = $newArray['MemberFax'];
$_SESSION['MemberEmail'] = $newArray['MemberEmail'];
$_SESSION['MemberAddress'] = $newArray['MemberAddress'];
$_SESSION['MemberCity'] = $newArray['MemberCity'];
$_SESSION['MemberState'] = $newArray['MemberState'];
$_SESSION['MemberZip'] = $newArray['MemberZip'];
$_SESSION['MemberAltName'] = $newArray['MemberAltName'];
}
mysql_close($conn);
header("Location: home/");
exit;
?>
We would certainly prefer to use the second method in terms of 'ease' for the member but keep running into the following issues:
We are forced to manually create a
sub-folder and unique index.php file
for each new member we onboard
While the above probably could be
automated (when new member creates
profile, automatically generate php
file and folder) but this is more
complicated and we don't want to
have 3000 subfolders on the primary
domain.
Has anybody run into similar issues? If so, how did you go about solving it? What would you recommend based on my details above? Any advice is appreciated.
Also - using as subdomain (membername.example.com) is not preferred because our current SSL does not allow for wildcards.
EDIT 1 - EXISTING .HTACCESS FILE
My existing .htaccess file on the site looks like this for reference:
ErrorDocument 404 /404.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteRule ^(.*)$ /?Member=$1 [L]
You can do your prefered method by just adding some lines to the .htaccess in your root directory:
This site should get you started
Or this one
If you are using apache, then you could use mod_rewrite to change urls like http://host/membername to http://host/memberpage.php?name=membername.
You could use this in a .htaccess file for your second method. It will rewrite http://yoursite.com/membername to http://yoursite.com/?Member=membername
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /?Member=$1 [L]
</IfModule>
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