Wildcard Subdomain with .htaccess and php - php

Spent the better part of a day trying to get my head around this and finally need to ask for some help.
I have a bunch of folders which i want to make into subdomains. I have followed the tutorial below and have set up a wildcard redirect in my DNS in step 1 and edited my virualhost in step2. This seems to have gone to plan.
However i am unsure of the logic behind step 3. How does the code below allow me to display content from a folder in a subdomain? i cant figure out what logic i am supposed to try and code - i think i am clearly missing something obvious here.
$serverhost = explode('.',$_SERVER["HTTP_HOST"]);
$sub = $serverhost[0];
if ($sub = "www") {
$sub = "";
}
(text from tutorial)
OK, here's what's taking place. You insert this code in your main php
file and what it does is check to see if the subdomain portion of the
domain (ie: thishere.yourdomain.com) is www. If so, it just nulls
$sub, otherwise, $sub will contain your subdomain keyword. Now, you
can check if ($sub > "") and take appropriate action with your code if
a subdomain exists, to display a page based on that value.
(tutorial link)
http://www.wiredstudios.com/php-programming/setting-up-wildcard-dns-for-subdomains-on-cpanel.html
Thanks in advance.

mmhh well, in fact, this code only permit you to get what subdomain is called.
So if you want to display the content of the folder corresponding to your subdomain, you have to scan your directory, then check if the folder called by subdomain exists, and then include script from this folder.
A simple way to do it is :
$scan = scandir('.'); // scan the current directory
if( in_array($sub, $scan) && is_dir($sub) ){
require( $sub.'/yourscript.php');
}
But this mean that your whole appication is designed in function of the $sub value, each include, each file prefixing etc ...

Related

Regional subdomains

I want to make some regional subdomains of my current site.com - something like city1.site.com and city2.site.com, but I don't want to copy all the files from original domain to subdomain.
Is it possible to show on subdomain city1.site.com the same info as on site.com but just set one variable, something like $city = 123? With this variable on city1.site.com I can show more specific contacts and products for this city.
I'm new to subdomain so please help, my site is on PHP & MySQL. Thank you!
If you have few regions, you can manually create subdomains for each region and point the domains to the same folder as your main site. Then in your script you grab the host and match it to regions and assign desired value to a variable.
<?php
if($_SERVER['HTTP_HOST'] === 'city1.site.com') {
$city = 123;
} else if($_SERVER['HTTP_HOST'] === 'city2.site.com') {
$city = 223;
}
If you have many regions and want a dynamic match, you can match any subdomain to your main site path and inside the script you can use a method to get the subdomain and search in your database. Example:
<?php
$subdomain = strstr($_SERVER["HTTP_HOST"], '.', true);
$city = getRegion($subdomain);
if(!$city) {
// throw 404 error
header('HTTP/1.0 404 Not Found');
exit;
}
// getRegion($subdomain) is a method that should search your database to match the subdomain to a region
To match all subdomains to a path you need to use wildcard in CPanel. See tutorial: https://www.namecheap.com/support/knowledgebase/article.aspx/9191/29/how-to-create-a-wildcard-subdomain-in-cpanel
You can probably use the $_SERVER superglobals in php (read the docs: http://php.net/manual/en/reserved.variables.server.php especially the $_SERVER['HTTP_HOST']) to find out, which subdomain is the current one (if any)
The rest is probably easy, for example a switch statement depending on the current subdomain like
switch($_SERVER['HTTP_HOST']) {
case 'city1.site.com': $abc=1; break;
case 'city2.site.com': $abc=2; break;
default: $abc=0; break;
}
update: the idea is, to use the same code for all subdomains (you don't want to maintain an arbitrary amount of copies) and force different behaviour through code. perhaps you can even setup a "catchall" domain somehow.
So, if you setup your domain site.com to live in your server's htdocs/site.com directory, use the same directory for all the other domains as well.
To achieve different outputs for your sites, you then check the $abc variable or some other var (perhaps even $_SERVER['HTTP_HOST']) to do
if(strpos($_SERVER['HTTP_HOST'],'.site.com') !== FALSE) {
$subdomain = str_replace('.site.com','',$_SERVER['HTTP_HOST']);
}
else {
$subdomain = null;
}
// now 'city1' is in $subdomain
After you have extracted the subdomain, you can run sql queries or the like with that value (if your database is setup appropriately).
First step is to make sure your DNS records are ready. Add an A record for the following if it doesn't already exist.
EDIT - If you are using a shared host, this might not work properly END
Set the name part to '*' and then the next to value to the server IP address you currently use. Once this rule is in place, people can go to {anything}.site.com and will all be sent to the same server.
At this point, I would do something similar to Jakumi's answer but keep it simpler
/* Cut up the URL */
$hostDetails = explode('.', $_SERVER['HTTP_HOST']);
/* Get the first part (city) of the URL */
$city = current($hostDetails);
/* Default check */
if($city == 'site') { $city = 'YOUR_DEFAULT'; }

Determine if site resides in a sub folder in php

I have a strange issue to solve. Lets say I have a vps, and in it i set up my site rum from example.com/site - you can clearly see that site is a sub folder and visiting it causes the url to look like http://example.com/site. Now lets say that I configure apache such that the url looks like: http://example.com but in fact the true url is still http://example.com/site.
I want to write a php function that states:
if site is a sub folder do this, else do that that
That would need to check if I am looking at example.com/site (regardless of apache configurations) or if I am truly looking at example.com
thoughts?
Maybe you could try this..
$urie = isset($_SERVER['REQUEST_URI']) ? strip_tags($_SERVER['REQUEST_URI']) : '';
//experimental echo to see with what we are dealing with
echo $urie;
if($urie == '/site')
{
//do this, or..
// $urie = str_replace('/site', '', $urie);
}
else
{
//do that
}
If you want to search for a "/site" from a complex url (like "example.com/site/image/3333.jpg"), I think you could use preg_match I suppose, or even replace if you need to maneuver to different folder, or you have maybe "base ref" problem.
Depending on your need for this tweak, answer/solution may be different.

PHP : IF Domain equals EXACTLY [x] then [actions] but not subdirectories/files

I am trying to execute code with PHP but only IF the URL is EXACTLY at the entry point of the website: http://mywebsite.com. So specifically ONLY on that URL, nothing after.
I am stumped after trying multiple PHP IF ELSE statements to try gaining it, very close I feel.
<?php $host = $_SERVER['HTTP_HOST']; if($host == "www.mywebsite.com" or $host == "mywebsite.com") { ?> MYHTML1SHOWS <?php } else { ?> MYHTML2SHOWS <?php } ?>
This has given me success in appearing on the domain when most visitors will come to mywebsite.com, but continues to work on all subsequent sub files/pages/directories. Which is 100% not wanted.
So I thought of a work around like ELSEIF's to show MYHTML2 to target all my pages, as they are handily all within country allocated directories: /au/ , /asia/ , /nz/ , /uk/ etc.
<?php } elseif (stripos($_SERVER['REQUEST_URI'],'/au/') !== false) { ?> HTML3 <?php } ?>
This didn’t work, but it was worth a try (works on its own IF statement in previous websites I’ve done, but I figure its clashing with the first IF statement which is more prioritized in the PHP). Appreciate any help guys, this has me stumped but would be ever useful. There were no similar questions on the net for only showing code this way.
(Background: I am implementing a 'Country Selector' that shows only on the entry point of mywebsite.com. I have already set up each country within their own sub-directories, thus no purpose of showing the country selector for them if a customer goes directly to one of those addresses).
You're probably doing some magic with Apache's mod_rewrite ... if not, that might be a good place to start looking. It sounds like the problem you're trying to solve is best done via Apache, either in your httpd.conf or (if enabled) via .htaccess.
http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Otherwise, the $_SERVER variables $_SERVER['PHP_SELF'] and $_SERVER['REQUEST_URI'] are probably of use to you.
http://www.php.net/manual/en/reserved.variables.server.php
$_SERVER['HTTP_HOST'] will only check the domain name, not the requested path. This is as you describe, but doesn't seem to be what you want.

Get Page URL In Order To Use It To Include

So I made a script so that I can just use includes to get my header, pages, and then footer. And if a file doesnt exist a 404. That all works. Now my issue is how I'm supposed to get the end of the url being the page. For example,
I want to make it so that when someone goes to example.com/home/test, it will automatically just include test.php for example.
Moral of the story. How to some how get the page name. And then use it to "mask" the end of the page so that I don't need to have every URL being something.com/home/?p=home
Heres my code so far.
<?php
include($_SERVER['DOCUMENT_ROOT'].'/home/lib/php/_dc.php');
include($_SERVER['DOCUMENT_ROOT'].'/home/lib/php/_home_fns.php');
$script = $_SERVER['SCRIPT_NAME']; //This returns /home/index.php for example =/
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/home/default/header.php');
if($_GET["p"] == 'home' || !isset($_GET["p"])) {
include($_SERVER['DOCUMENT_ROOT'].'/home/pages/home.php');
} else if(file_exists($_SERVER['DOCUMENT_ROOT'].'/home/pages/'.$_GET["p"].'.php')) {
include($_SERVER['DOCUMENT_ROOT'].'/home/pages/'.$_GET["p"].'.php');
} else {
include($_SERVER['DOCUMENT_ROOT'].'/home/default/404.php');
}
include($_SERVER['DOCUMENT_ROOT'].'/home/default/footer.php');
?>
PHP by itself wouldn't be the best choice here unless you want your website littered with empty "redirect" PHP files. I would recommend looking into the Apache server's mod_rewrite module. Here are a couple of guides to get you started. Hope this helps!
The simplest way would be to have an index.php file inside the /home/whatever folder. Then use something like $_SERVER['PHP_SELF'] and extract the name if you want to automate it, or since you are already writing the file yourself, hardcode it into it.
That however looks plain wrong, you should probably look into mod-rewrite if you are up to creating a more complex/serious app.
I would also recommend cakePHP framework that has the whole path-to-controller thing worked out.

If URL contains something include .php file else do nothing?

I wish to include Smart PHP Cache layer on top of main script on site. It works great, but Smart Cache also caches some pages which should not be cached (search results, admin area...).
I looked into Smart PHP Cache source code, and I am not sure if there is some way to configure which pages should be excluded from cache, or how to configure it.
So, what I need is some php code which will be inserted at top of main script of site, before Smart PHP Cache code which will first check if page contains for example:
"/search/"
"/admin/"
"/latest/"
"/other-live-pages/live-page.php"
and then, if something from above example is in URL to do nothing, (not to include smart_cache.php and to continue with other normal code, so user could see live results) and otherwise if there is nothing from above to include smart_cache.php.
Or.
If you have better knowledge to make modification inside Smart PHP Cache to be able to exclude some URLs from caching mechanism (or to tell me how to do that, because it looks like there is something in configuration of Smart PHP Cache that can bypass the cache layer but I am not sure how to use it.
Best regards.
Question update:
Thanks for answer. It works nice, I just wish to ask can you please little change code to make this:
If "pos1" (if URL contains "/search"), than nothing, false, like it is now
if "pos2" (if URL contains "/admin"), than nothing, false, like it is now
if "pos3" (if URL contains "/latest") include file "smart_cache_latest.php"
and after that like it is now, include "smart_cache.php" for any other URLs.
So practically only change is for URLs with "/latest", which should be cached too by including "smart_cache_latest.php".
Best regards.
$currenturl = $_SERVER['REQUEST_URI'];
$pos1 = strpos($currenturl, "/search");
$pos2 = strpos($currenturl, "/admin");
$pos3 = strpos($currenturl, "/latest");
if ($pos1 === false && $pos2 === false){
require '/path/to/smart_cache.php';
} elseif($pos3 == true) {
require '/path/to/smart_cache_latest.php';
}

Categories