Apache mod_rewrite Example: Friendly URL using .htaccess
Given URL "hello/cfsuman" & want to Redirect to URL "hello.php?visitor=cfsuman"
make a file named ".htaccess" and copy & paste the below code:
RewriteEngine On RewriteRule ^hello/([a-z]+)/?$ hello.php?visitor=$1
Explanation of .htaccess file
RewriteEngine On : this line of code enables rewriting engine RewriteRule ^hello/([a-z]+)/?$ hello.php?visitor=$1 : this line of code applies rewriting rule where ^ start of input $ end of input hello/ REQUEST_URI starts with "hello" ([a-z]+) capture any word or characters and put it in $1 /? this is nothing but an optional trailing slash "/" rewrite: hello.php?visitor=$1 where $1 is the captured literal string.
now make a file named ".hello.php" and copy & paste the below code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Apache mod_rewrite Example: Friendly URL using .htaccess</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="Md Iqbal Hosan">
<meta name="title" content="apache mod rewrite example friendly url using htaccess">
<meta name="keywords" content="php, example, code, array, function, mod_rewrite, string, apache, htaccess">
<meta name="description" content="apache mod rewrite example friendly url using htaccess">
<style>
h2, h4{background:orange; color:#000089;}
h2{ padding:3px; margin:3px; font-size:22px;}
h4{ padding:2px; margin:2px; font-size:19px;}
p{padding:2px; margin:2px;}
body{ background:#FFFFFD;}
span{ font-size:16px; font-weight:bold; color:#3366FF;}
</style>
</head>
<body>
<h1>Apache mod_rewrite Example: Friendly URL using .htaccess</h1>
<h2>you are currently visiting hello.php</h2>
<pre>
<?php
/*
-----------------------------
catch visitor name from url
-----------------------------
*/
$VisitorName = $_REQUEST['visitor'];
?>
<p>Hello <span><?php echo $VisitorName; ?></span></p>
</pre>
</body>
</html>
Explanation of hello.php file
this file receives a name from url and make a greeting message with it.



No comments:
Post a Comment
leave your comments here..