I'm trying to achieve clean URLs on my localhost (so when I write localhost/contact, it redirects me to localhost/contact.php), but it's not working. I did it according to the older tutorial I found on YouTube, but I probably didn't understand well some parts. Many thanks for every answer. Here is my code:
.htaccess // I am sure I have mod_rewrite allowed.
<IfModule mod_rewrite.so>
RewriteEngine On
RewriteBase /www/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
</IfModule>
Script in index.php
include_once('classes/simpleUrl.php');
$url = new simpleUrl('localhost');
$test = $url->segment(1);
if (!$url->segment(1)) {
$page = 'home';
}
else {
$page = $url->segment(1);
}
switch ($page) {
case 'home' :
echo 'Home page';
break;
case 'contact':
echo 'Contacts page';
break;
default:
echo '404';
break;
}
classes/simpleUrl.php
class simpleUrl {
var $site_path;
function __toString() {
return $this->site_path;
}
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
return $string;
}
}
function __construct($site_path) {
$this->site_path = $this->removeSlash($site_path);
}
function segment($segment) {
$url = str_replace($this->site_path, '', $_SERVER['REQUEST_URI']);
$url = explode('/', $url);
if(isset($url[$segment])) {return $url[$segment];} else {return false;}
return $url;
}
$url = new simpleUrl('localhost');
localhost is not shown in $_SERVER['REQUEST_URI'] so in this case you may simply use $url = new simpleUrl('index.php');
OR
Use this code for .htaccess :
RewriteEngine On
RewriteBase /www/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.php [L]
because when you do this:
RewriteRule ^(.*)$ index.php/$1
Your actual URL may become something like this:
localhost/index.php/contact
So it's better requested URL to stay same.
but in this case use:
$url = new simpleUrl('');
Oho, look at this mistery:
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
return $string;
}
}
when passed $string does not ends with slash it returns nothing, so have to change it in such:
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
}
return $string;
}
Now I'll explain when and why to use $site_path for simpleUrl constructor:
if you have running your script in subdirectory, for ex: if you are working under /www/test/ then you should you test as param to pass to simpleUrl constructor, otherwise leave it blank
Update 3
You should change simpleUrls segment method to this:
function segment($segment) {
$url = trim(str_replace($this->site_path, '', $_SERVER['REQUEST_URI']),'/');
$url = explode('/', $url);
if(isset($url[$segment])) {return $url[$segment];} else {return false;}
return $url;
}
and next use 0 as index instead of 1 - $url->segment(0)
I'm not sure if you wish to use more variables like: www.domain.com/folder-with-website/products/product-name or if you could live with: www.domain.com/folder-with-website/products?id=123
But try this:
index.php
<?php
$page = $_GET["page"];
if(file_exists("pages/{$page}.php")) {
include("pages/{$page}.php");
} else if(empty($page)) {
include("pages/home.php");
} else {
echo "This page does not exists";
}
?>
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1
Options -Indexes
Link setup
<ul>
<li>
Home <!-- Just a page without any variables -->
</li><li>
Products <!-- same as Home -->
</li><li>
Details about product <!-- Page with a variable / extra information -->
</li><li>
Details about product <!-- Page with more variables -->
</li>
</ul>
Related
I want to write a project with regular files. The index file has a php code where all the files opened in the URL are switches. Like for example:
index.php
<?php
if(isset($_GET['page'])){
$current_page = isset($_GET['page']) ? $_GET['page'] : '';
}else{
$current_page = 'index';
}
$result = str_replace(".php","", $current_page);
switch($result){
case 'welcome':
include('sources/welcome.php');
break;
case 'index':
include('sources/index.php');
break;
case 'profile':
// Here is the problem. I want to make Facebook style user profile system
// But the switch can not see profile username because it is working just for page names not usernames
break;
}
?>
Like the code in the index.php file, I call the pages with the switch. But everything changes when the user opens the profile page. Because I want to make the profile pages of the members just like Facebook. Like http://www.mywebproject.com/username
My created htaccess is here:
.htaccess
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
RewriteRule (?:^|/)([\w-]+)/?$ profile.php?username=$1 [L,QSA]
My question is this. How can I call members' profiles with their username in switch.
How can I call members' profiles with their username in switch because there is no every username in $thePage array.
Just pass everything to the index.php
.htaccess:
# Activate rewrite engine
RewriteEngine on
RewriteBase /root/
# If the request is not for a valid directory, file or symlink
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
# Redirect all requests to index.php
RewriteRule ^(.*)$ index\.php?/$1 [QSA]
You just pass the $_REQUEST['username'] to the profile.php and then you render your page.
Something like:
index.php
// you can do this better, this is just an example:
$request_uri = $_SERVER['REQUEST_URI'];
$params_offset = strpos($request_uri, '?');
$request_path = '';
$request_params = [];
echo 'request_uri = ', $request_uri, '<br>', PHP_EOL;
if ($params_offset > -1) {
$request_path = substr($request_uri, 0, $params_offset);
$params = explode('&', substr($request_uri, $params_offset + 1));
foreach ($params as $value) {
$key_value = explode('=', $value);
$request_params[$key_value[0]] = $key_value[1];
}
} else {
$request_path = $request_uri;
}
echo 'request_path = ', $request_path, '<br>', PHP_EOL;
echo 'request_params = ', PHP_EOL; print_r($request_params);
if (preg_match('~/root/(photos|videos|albums)/([\w-]+)~', $request_uri, $match)) {
print_r($match);
unset($match);
require_once('photos_videos_albums.php');
} else if (preg_match('~/root/([\w-]+)~', $request_uri, $match)) {
$username = $match[1];
unset($match);
require_once('profile.php');
} else if ($request_path == '/root/') {
echo 'HOME';
exit();
} else {
header('HTTP/1.0 404 Not Found');
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
}
My website has 2 languages. When I change language, I want the URL to change as well, similar to this:
www.domain.com
changing to this:
www.domain.com/th
and this:
www.domain.com/en
My php:
config.php
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);
if(empty($_SESSION['language'])){
$_SESSION['language'] = "th";
}
if ($_SESSION['language'] == "th") {
include $_SERVER['DOCUMENT_ROOT'] . "/language/th.php";
} else {
include $_SERVER['DOCUMENT_ROOT'] . "/language/en.php";
}
$base_url = "/";
function lang($th, $en) {
if ($_SESSION['language'] == "th") {
return $th;
} else {
return $en;
}
}
lang.php
<?php
session_start();
switch ($_POST["lang"]) {
case "th":
$_SESSION['language'] = "th";
echo json_encode("complete");
break;
case "en":
$_SESSION['language'] = "en";
echo json_encode("complete");
break;
default :
break;
}
?>
links to change language
<li><a href="javascript:lang('th');" <?= $_SESSION['language'] == "th" ? 'class="active"' : ''; ?> >TH</a></li>
<li><a href="javascript:lang('en');" <?= $_SESSION['language'] == "en" ? 'class="active"' : ''; ?> >EN</a></li>
Can I use .htaccess to do this?
No, you can't acceess the PHP session from .htaccess. But you could use mod_rewrite to rewrite every request to your config.php.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# Only for non-existing directories, files or symlinks
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* config.php [L]
</IfModule>
I have redirect loop in when I select a category of posts below is my htaccess file:-
<IfModule mod_rewrite.c>
# Enable mod_rewrite
RewriteEngine On
# Specify the folder in which the application resides.
# Use / if the application is in the root.
RewriteBase /
# Rewrite to correct domain to avoid canonicalization problems
RewriteCond %{HTTP_HOST} !^www\.rswebtek\.in
RewriteRule ^(.*)$ http://www.rswebtek.in/$1 [R=301,L]
# Rewrite URLs ending in /index.php or /index.html to /
RewriteCond %{THE_REQUEST} ^GET\ .*/index\.(php|html?)\ HTTP
RewriteRule ^(.*)index\.(php|html?)$ $1 [R=301,L]
# Rewrite category pages
RewriteRule ^.*-c([0-9]+)/page-([0-9]+)/?$ index.php?CategoryId=$1&Page=$2 [L]
RewriteRule ^.*-c([0-9]+)/?$ index.php?CategoryId=$1 [L]
#Redirect search results
RewriteRule ^search-results/find-(.*)/page-([0-9]+)/?$ index.php?SearchResults&SearchString=$1&Page=$2[L]
RewriteRule ^search-results/find-?(.*)//?$ index.php?SearchResults&SearchString=$1&Page=1 [L]
#Redirect tag search results
RewriteRule ^tagged/([^/]+)/page-(\d+)/?$ index.php?TagSearchResults&TagName=$1&Page=$2 [L,QSA]
RewriteRule ^tagged/([^/]+)/?$ index.php?TagSearchResults&TagName=$1&Page=1 [L,QSA]
#Redirect static pages based on page name
RewriteRule ^pages/([^/]+)/?$ index.php?StaticPage&PageName=$1 [L,QSA]
# Rewrite subpages of the home page
RewriteRule ^page-([0-9]+)/?$ index.php?Page=$1 [L]
# Rewrite Post details pages
RewriteRule ^.*-p([0-9]+)/?$ index.php?PostId=$1 [L]
</IfModule>
# Set the default 500 page for Apache errors
ErrorDocument 500 /rswebtek_blog/500.php
#Set the defualt 404 error page
ErrorDocument 404 /rswebtek_blog/404.php
here is my link.php file:-
<?php
class Link{
public static function Build($link, $type='http'){
$base = (($type == 'http' || USE_SSL == 'no') ? 'http://' :'https://').getenv('SERVER_NAME');
//if HTTP_SERVER_PORT is defined and different than default
if(defined('HTTP_SERVER_PORT') && HTTP_SERVER_PORT !='80' && strpos($base, 'https') === false){
//append server port
$base .=':' . HTTP_SERVER_PORT;
}
$link = $base . VIRTUAL_LOCATION . $link;
//escape html
return htmlspecialchars($link, ENT_QUOTES);
}
public static function ToCategory($categoryId, $page =1){
$link = self::CleanUrlText(Blog::GetPostCategoryName($categoryId)).
'-c'.$categoryId.'/';
//$link ='index.php?CategoryId='.$categoryId;
if($page > 1)
$link .='page-'.$page.'/';
//$link .= '&Page='.$page;
return self::Build($link);
}
public static function ToPost($postId){
$link = self::CleanUrlText(Blog::GetPostTitle($postId)).
'-p'.$postId.'/';
// return self::Build('index.php?PostId='.$postId);
return self::Build($link);
}
public static function ToIndex($page = 1){
$link ='';
if($page > 1)
$link .='page-'.$page.'/';
//$link .='index.php?Page='.$page;
return self::Build($link);
}
public static function QueryStringToArray($queryString){
$result = array();
if($queryString !=''){
$elements =explode('&',$queryString);
foreach($elements as $key => $value){
$element = explode('=',$value);
$result[urldecode($element[0])] = isset($element[1]) ? urldecode($element[1]) : '' ;
}
}
return $result;
}
// Prepares a string to be included in an URL
public static function CleanUrlText($string)
{
// Remove all characters that aren't a-z, 0-9, dash, underscore or space
$not_acceptable_characters_regex = '#[^-a-zA-Z0-9_ ]#';
$string = preg_replace($not_acceptable_characters_regex, '', $string);
// Remove all leading and trailing spaces
$string = trim($string);
// Change all dashes, underscores and spaces to dashes
$string = preg_replace('#[-_ ]+#', '-', $string);
// Return the modified string
return strtolower($string);
}
//redirects to proper url if not already there
public static function CheckRequest(){
$proper_url = '';
if (isset ($_GET['Search']) || isset($_GET['SearchResults']) || isset($_GET['TagSearchResults']) || isset($_GET['StaticPage'])){
return;
}
// Obtain proper URL for category pages
elseif (isset ($_GET['CategoryId'])){
if (isset ($_GET['Page']))
$proper_url = self::ToCategory($_GET['CategoryId'], $_GET['Page']);
else
$proper_url = self::ToCategory($_GET['CategoryId']);
}
// Obtain proper URL for post pages
elseif (isset ($_GET['PostId'])){
$proper_url = self::ToPost($_GET['PostId']);
}
// Obtain proper URL for the home page
else{
if (isset($_GET['Page']))
$proper_url = self::ToIndex($_GET['Page']);
else
$proper_url = self::ToIndex();
}
/* Remove the virtual location from the requested URL
so we can compare paths */
$requested_url = self::Build(str_replace(VIRTUAL_LOCATION, '',$_SERVER['REQUEST_URI']));
//404 redirect if the requested product, category or department
//donnot exist
if(strstr($proper_url, '/-')){
//clean output buffer
ob_clean();
//load the 404 page
include('404.php');
//clear the output buffer an stop executon
flush();
ob_flush();
ob_end_clean();
exit();
}
// 301 redirect to the proper URL if necessary
if ($requested_url != $proper_url){
// Clean output buffer
ob_clean();
// Redirect 301
header('HTTP/1.1 301 Moved Permanently');
header('Location:'.$proper_url);
// Clear the output buffer and stop execution
flush();
ob_flush();
ob_end_clean();
exit();
}
}
//create link to the search page
public static function ToSearch(){
return self::Build('index.php?Search');
}
public static function ToSearchResults($searchString, $page = 1){
$link = 'search-results/find';
if(empty($searchString))
$link .='/';
else
$link .= '-' . self::CleanUrlText($searchString) . '/';
// $link .='all-words-'.$allWords.'/';
if($page > 1)
$link .= 'page-'.$page.'/';
return self::Build($link);
}
//build tag links
public static function ToTagLinks($tags, $page = 1){
$tags = explode(',', $tags);
foreach ($tags as &$tag) {
$link ='tagged/'.self::CleanUrlText($tag) ;
if($page > 1)
$link .='/page-'.$page.'/';
$tag = '<a class="taglist" href="'.self::Build($link).'" title="">'.$tag.'</a>';
}
return implode(', ', $tags);
}
public static function ToStaticPage($pageName){
//$link ='index.php?StaticPage&PageName='.$pageName;
$link ='pages/'.self::CleanUrlText($pageName) ;
return self::Build($link);
}
public static function ToTagNexPreLink($tag, $page = 1){
$link ='tagged/'.self::CleanUrlText($tag) ;
if($page > 1)
$link .='/page-'.$page.'/';
return self::Build($link);
}
?>
and index.php
<?php
//active session
session_start();
//start output buffer
ob_start();
//include utility files
require_once('include/config.php');
require_once(BUSINESS_DIR.'error_handler.php');
//set error handler
ErrorHandler::SetHandler();
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'blog.php';
//Link::CheckRequest();
// Load presentation Tier
require_once(PRESENTATION_DIR.'application.php');
require_once(PRESENTATION_DIR.'link.php');
Link::CheckRequest();
$application = new Application();
//this is used to mute errors
$application->muteExpectedErrors();
//display page
$application->display('blog_front.tpl');
// close the connection
DatabaseHandler::Close();
//output content from the buffer
flush();
ob_flush();
ob_end_clean();
?>
problem arised when I select a category or post :- my static link as follow
http://www.rswebtek.in/database-c3/
any help must be appreciated
I am trying/attempting to create my own MVC. I am really trying to manipulate the url. I am trying to get several parameters to form a full URL.
I want to turn
http://example.com/?action=account&user=JohnDoe
to
http://example.com/account/JohnDoe
But I cant seem to get the .htaccess file to work right :/
This is what I have
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([a-zA-Z0-9-=_?]+)/?$ index.php?action=$1&user=$2 [NC,L]
When I go to http://example.com/account/JohnDoe I get a 404 error.
Your missing one parameter, try this
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php?action=$1&user=$2 [NC,L]
Rather than set up a mod_rewrite rule for that specific URL, why not put an entire framework in place?
mod_rewrite as follows:
#URI PATH CONSTRUCTION
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)$ /index.php?string=$1 [L,QSA]
</IfModule>
Then have your index.php file break up $_REQUEST['string'] into an array that you can test to direct the request to where it needs to go
if (isset($_GET['string'])) {
//DEALS WITH GET PARAMETERS
if (strstr($_GET['string'],"?") !== false) {
$pos = 0;
$tailstr = substr($_GET['string'],$pos);
$endpos = strpos($tailstr, "?");
$endpos = $endpos + strlen("?");
$string = substr($_GET['string'],$pos,$endpos);
} else {
$string = $_GET['string'];
}
$path = explode("/",$_GET['string']);
}
//Depth to 5 levels
for ($i=0;$i<5;$i++) {
if (!isset($path[$i])) $path[$i] = null;
}
global $path;
You now have a global array containing the individual elements in the URI
eg
http://example.com/account/JohnDoe
would give you:
$path[0] = 'account'
$path[1] = 'JohnDoe'
$path[2] = ''
$path[3] = ''
$path[4] = ''
I have actually tried the tutorial stated in here: http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls
I have tried to use the PHP version of the Tutorial. However it doesn't seems to work. In fact it looks a little bit illogical for me.
This is the code which I'd need to place to the .htaccess file:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^.*$ ./index.php
As I have tested this actually redirects everything to the index.php file. So I have inserted this code to my index.php file:
$request = $_SERVER['REQUEST_URI'];
$params = split("/", $request);
$safe_pages = array("login");
if(in_array($params[0], $safe_pages)) {
echo 'ok'; //insert a file here
} else {
echo 'not ok'; //header to 403.php
}
This code is quite starightforward. If the URI is /login it should echo: "ok" (insert the file there).
However whenever I type: mywebsite.com/login it just always gives me the index.php, with the message: "not ok" so something should be wrong with the php code I guess.
Your are missing one more method on the .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
This should suport url like 'page/item'
<?php
$request = $_SERVER['QUERY_STRING'];
$params = explode("/", $request);
$safe_pages = array("login");
if(in_array($params[0], $safe_pages)) {
echo 'ok'; //insert a file here
} else {
echo 'not ok'; //header to 403.php
}
?>
This dont work with url like 'page/item'
This should work:
<?php
$request = $_SERVER['REQUEST_URI'];
$params = explode("/", $request);
$safe_pages = array("login");
$last_item = count($params)-1;
if(in_array($params[$last_item], $safe_pages)) {
echo 'ok'; //insert a file here
} else {
echo 'not ok'; //header to 403.php
}
You are testing the wrong item. You should check for the string 'login' in the end of the array. And the function split is depreciated, use explode()