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';
}
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.";
}
So I just started making a new website, or rather modifying an old one. All the code is the same, the only difference is I changed some text here and there. The old website worked perfectly, so this one should as well, so I'm not sure why this is happening, but only the main page can be found using the URLs that I wish to be used. Try going to, for example, the projects page, and not only is the file not found, but my custom not found page won't even be shown. First I'll show some examples then I will show some code.
Main page that works: teivodov.com
Projects page that worked on old site, but not on this one: teivodov.com/projects
Projects page that works, but ugly url form https://teivodov.com?page=projects
Not found page working only if ?page= used: https://teivodov.com?page=blahblah
Here is my htaccess file:
//deny access to this file
<Files ~ ".htaccess">
deny from all
</Files>
//start RewriteEngine
RewriteEngine On
//if the called file is NOT a directory, file or link, we call index.php?page=
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
//disable file listing
Options -Indexes
//set error page 403 (no permission) and 404 (page not found) to our notfound page
ErrorDocument 403 /notfound
ErrorDocument 404 /notfound
order deny,allow
(# replaced with //)
My index.php:
<?php
function dump_error_to_file($errno, $errstr) {
file_put_contents('/errors.log', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler('dump_error_to_file');
//load needed settings, constants, page array and functions
include 'variables.php';
include 'constants.php';
include 'functions.php';
//setting timezone to America/Chicago, needed by some functions
date_default_timezone_set('America/Chicago');
//gets changed to the return of the include file
$ret = 1;
/*
* The include file has to contain the following values:
* Array('filename' => string, -- Filename for template
* 'data' => Array()) -- Array with data for the template
* - At an exception
* string -- Errormessage.
*/
//if no page was called, include the main page
if (!isset($_GET['page'])) {
$ret = include 'includes/' . $files['main'];
} else {
if (isset($_GET['page'])) {
$page = trim($_GET['page']);
} else {
$page = 'main';
}
if (isset($files[$page])) {
//if the file exists include it, else print error message
if (file_exists('includes/' . $files[$page])) {
$ret = include 'includes/' . $files[$page];
} else {
$ret = "Include-File was not found: 'includes/" . $files[$page] . "'";
}
} else {
$ret = include 'includes/' . $files['notfound'];
}
}
//include header template
include 'templates/header.html';
//if the include returns an array, it contains the templatestring and the data array, try to include the template
if (is_array($ret) && isset($ret['filename'], $ret['data']) && is_string($ret['filename']) && is_array($ret['data'])) {
//if the template exists include it, else print error message
if (file_exists($file = 'templates/' . $ret['filename'])) {
$data = $ret['data'];
include $file;
} else {
$data['msg'] = 'Template "' . $file . '" was NOT found.';
include 'templates/error.html';
}
//if the include file returns a string, it returned an exception. So we print it
} else if (is_string($ret)) {
// Exception
$data['msg'] = $ret;
include 'templates/error.html';
//the defualt value of $ret didnt change, so the include didnt return anything. Print error message
} else if (1 === $ret) {
//No return array
$data['msg'] = 'No return in the template!';
include 'templates/error.html';
} else {
//include file has a complete other return like a boolean or something, print error
//everything left
$data['msg'] = 'Include file has an invalid return.';
include 'templates/error.html';
}
//include footer template
include 'templates/footer.html';
Variables.php:
<?php
$files = array();
$files['main'] = 'main.php';
$files['projects'] = 'projects.php';
$files['projects/jda-extended'] = 'projects/jda-extended.php';
$files['contact'] = 'contact.php';
$files['about'] = 'about.php';
$files['notfound'] = 'notfound.php';
An example include file, projects.php:
<?php
$a = array();
$a['filename'] = 'projects.html';
$a['data'] = array();
return $a;
Example template file, projects.html:
<div class="fluid">
<p>
This website is still under construction.
<br><br>
<strong>JDA Extended</strong> - Extension to the JDA API. Allows for quick and easy discord bot development.
</p>
</div>
I believe that should be all the code someone might ask for, but feel free to ask for more if need be. The only difference between my last site and this one, is that the last site was hosted on shared web hosting. This one is hosted on my vps using apache2. It really confuses me as the site is able to find for example includes/main.php and templates/main.html, but not any other files in those folders. The only thing I can think of is something went wrong in the htaccess file as ?page=projects works but /projects does not, but I can't see anything wrong with it?
After playing around, I realized it was an issue with Apache2. By default in /etc/apache2/apache2.conf AllowOverrides is set to None when I needed it to be All. I had done all my testing of the website in windows, which I did not need to bother changing that.
How can i do the below probably .htaccess ?
/sp/sitea => /check.php?page=sitea #no trailing forward slash
/sp/sitea/ => /check.php?page=sitea #trailing forward slash
/sp/sitea/index.php => /check.php?page=sitea/index.php #includes a file
/sp/siteb => /check.php?page=siteb
/sp/index.php , /sp/login.php => no redirect
I then want to check the DB using PHP for sitea to see if the user is logged in and then redirect to /sp/sitea If they are not logged in for that site redirect to /login.php
I tried .htaccess below , in sp folder, but doesnt redirect, im not really .htaccess master
RewriteEngine On
RewriteCond %{REQUEST_URI} /
RewriteRule ^\/(.*)$ sp/check.php?path=$1 [L]
I solved this with a modified .htaccess file
RewriteEngine on
RewriteOptions MaxRedirects=2
RewriteBase /
#dont check non pages
RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$
RewriteRule ^(.*)/(.*)$ /sp/check.php?path=$1&path2=$2 [L,P] #P keeps address in bar after redirect
check.php
<?php
//htaccess redirects here for sitepreview subdomains, then do authentication check and output the html
//cant redirect to page or get redirect loop
session_start();
$dir = $_GET["path"];
$dir2 = $_GET["path2"];
//echo $dir;
if(!isset($_SESSION['login_user'])){
header("Location: /sp/index.php",true,301);
exit();
}else {
$name = $_SESSION['login_user']["name"];
if($name == $dir) {
$homepage = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/sp/$dir/" . (isset($dir2) && strpos($dir2, ".htm") ? $dir2 : "index.html") );
echo $homepage;
}
else {
header("Location: /sp/index.php",true,301);
exit();
}
exit();
}
First of all, I apologize. I looked up a lot of questions but so far nothing has worked. I don't know why.
I have a site www.mysite.it
and one URL is
www.mysite.it/home.php?pagina=home
I want to see
www.mysite.it/home or www.mysite.it/home.php is the same
I added this in .htaccess:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)/$ home.php?pagina=$1
and I have this expression in my php:
<?php
$get= #$_GET ['pagina'];
$pagina = (isset($_GET['pagina']) ? $_GET['pagina'] : 'home') . '.php';
if(file_exists($get)){
include($pagina);
} else {
include("404.php");
}
switch ($get){
default :
include ('contenuto/home.php');
break;
case "tournament":
include ('torneo/torneo.php');
break;
case "arena":
include ('contenuto/modalita/arena.php');
break;
etc
Your RewriteRule only matches URLs that end with "/". You'll need to change your rewrite rules. Consider using an R directive as well as L.
RewriteRule ^(.*)/$ home.php?pagina=$1 [L]
RewriteRule ^(.*)$ home.php?pagina=$1 [L]
Then change your logic. The 404 if block should go below case. It seems like you're figuring out what page you're going to at multiple places. I tried to sort that out below. Also, use the debug statements to determine if the variables are getting set how you want them. Also remember that pagina must match an actual file on the disk, including directory. For example, if you ask for torneo, it won't be found. tournament only works because it has a special listing in the switch block.
$get = #$_GET['pagina'];
if (!isset($_GET['pagina'])) {
$get = 'home';
$pagina = 'contenuto/home.php';
} else {
$pagina = $get . '.php';
}
// debug
echo $get . '//' . $pagina
switch ($get) {
default :
$pagina = 'contenuto/home.php';
break;
case "tournament":
$pagina = 'torneo/torneo.php';
break;
}
if (file_exists($pagina)) {
include($pagina);
} else {
include("404.php");
}
Here you check for the existence of one file and you include another :
if(file_exists($get)){
include($pagina);
This cannot work. It must be :
if(file_exists($pagina)){
include($pagina);
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 !