Use PHP to rewrite URLS? - php

I want to make my own url rewriting rules using couple of PHP-MySQL. The concept is to have a rule in my .htaccess that send all request to my index.php file like :
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php
RewriteCond %{REQUEST_URI} !\.(.+)$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301].
And php will take all params via a super global var like $_SERVER['REQUEST_URI'] and explode("/", $_SERVER['REQUEST_URI']).
function rewrite(){
$paramKeys = array("", "locale", "page", "par1", "par2", "par3", "par4", "par5");
$paramValues = explode("/", $_SERVER['REQUEST_URI']);
foreach($paramValues as $key => $value){
if (!is_array($key)) {
$paramValues[$key] = htmlspecialchars(stripslashes(trim($value)));
if($key == 0){ //but the 1st slash is in the end of URL
continue;
}
elseif($key == sizeof($paramKeys)){
break;
}
else $params[$paramKeys[$key]] = $value;
}
else continue;
}
return $params;
}
And compare the requested URL with URL's in my database to send http statut in order of the requested file is found 200, moved 301, or not found 404.
Have I a bad idea ? if not, how can I perfectionize it. Thank you !

Related

I am confused while configuring the url using htaccess and php switch

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.";
}

htaccess rewrite with subdomain as variable

I have a sitename.net and in a root directory i have .htaccess and index.php
.htaccess is:
FallbackResource /index.php
so basically as it's empty site (no sub directories, no files etc...) I will get a fallback to index.php which contains this:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
echo "Domain is: $domain <br>";
if(empty($elements[0])) { // No path elements means home
echo "ShowHomepage()";
}
else switch(array_shift($elements)) { // Pop off first item and switch
case 'tests':
echo "First is test";
case 'sample':
echo "First is sample";
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
my problem is that when visitor enters: https://username.sitename.net/tests/test1
I get error as subdomain doesn't exist...
When I go to "https://sitename.net/tests/test1" i get what I want but I need username as a variable as well.
Should I first do rewrite in .htaccess so it translate https://username.sitename.net/tests/test1 as https://sitename.net/username/tests/test1 and than redo index.php so it pickup a first array element as username or there is another option ?
Can somebody help me out ?
------------- EDIT ----------------
I've ended up pointing A record *.sitename.net to server IP
I've changed .htaccess so it's:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^(.*)\.sitename\.net
RewriteRule ^(.*)$ subdomains/%1/$1 [L,NC,QSA]
FallbackResource /index.php
...and still getting 404 error... still can't get:
https://username.sitename.net/tests/test1 to act like https://sitename.net/username/tests/test1 so index.php will do it stuff...
I think wildcard DNS records is what you're looking for.
https://en.wikipedia.org/wiki/Wildcard_DNS_record
All subdomains will then redirect to your DNS, which you can redirect to your server.
EDIT:
Once the subdomains are up and running, you can use
.htaccess rewrite subdomain to directory
to fix the htaccess.
This work with php redirect too:
$url = "https://gbr8295.sitename.net"; //$_SERVER['HTTP_HOST']
if (substr($_SERVER['HTTP_HOST'], 0, 16) != 'https://sitename') { // You need edit 16 to a correct number for your domain
$username = substr($url, 8, ((strpos($url, '.') - 8)));
$new_url = "https://sitename.net/".$username."/";
echo $url."<br>"; // Output: https://gbr8295.sitename.net
echo $new_url; // Output: https://sitename.net/gbr8295/
header("Location: $new_url");
exit;
} else {
echo 'ok';
}

Clean URL on localhost

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>

htaccess rewrite or php url exploding

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] = ''

url rewriting and passing variable

Hi i'm trying to send data over from a url rewrite page but unfortunately, its not working its just throwing me back to the main page or error page. The template & urlrewrite for rmbitter is what i'm trying to do. Currently domain.com/rmbitter.php loads perfectly file. I have a link on domain/boothwall.html and that link looks like this domain.com/rmbitter.php?ulnk=$usr&slnk=$lnk the rmbitter.tpl has the $_GET code. My problem I believe is with the rewrite its not allowing the variable to be passed over.
The reason for using the .tpl is because the page has a design layout that is needed. If i build a started rmbitter.php file with a test.html page and a link to rmbitter.php with the variable it works fine.
$inc = array(
'pictures' => 'icons.php',
'view_images' => 'templates/view_images.tpl',
'boothw' => 'templates/boothw.tpl',
'rmbitter' => 'templates/rmbitter.tpl'
);
//URL rewriting rules...
$rew = array(
'/view_images_public\/(.*)$/' => 'req=view_images&user=$1',
'/boothwall\.html$/' => 'req=boothw',
'/rmbitter\.php$/' => 'req=rmbitter'
);
url_rewrite.php
<?php
//get request
$url = $_SERVER['REQUEST_URI'];
if (strpos($url,'?PHPSESSID=')) $url = substr($url,0,strpos($url,'?PHPSESSID='));
while (strpos($url,'//') !== false) $url = str_replace('//','/',$url);
$url = substr($url,strlen(constant('dir')));
$url_array = explode('/', $url);
//make request string
$reqstr = '';
foreach ($url_array as $key => $value)
$reqstr .= '/'.$value;
$reqstr = substr($reqstr,1);
//other stuff
if (substr($reqstr,0,9) != 'index.php') {
$rewrite['/pages\/(.*)\.html$/'] = 'req=pages&id=$1';
$rewrite['/static\/(.*)\.html$/'] = 'req=static&id=$1';
$rewrite['/(.*)\.html$/'] = 'req=$1';
?>
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*) index.php [L]
</IfModule>
I don't 100% understand what your problem is, but the general cure to all GET related mod_rewrite ailments is Query String Append (QSA).
RewriteRule ^(.*) index.php [L, QSA]
as the name says, it appends any incoming GET data to the new URL and passes it on to index.php.

Categories