How to mask subdomain as domain - php

Is it possible to to access web with url example.com but variables inside php (like SERVER_NAME) would act like sub.example.com?
We made wrong decision during development and now we are actually stuck with two separate versions of software. One for example.com and other for automatically generated subdomains. We could reserver one subdomain to act as our main domain, but we don't want that sub. example.com part.

You should add some checks, for example:
function hasSubdomain($url) {
$parsed = parse_url($url);
$exploded = explode('.', $parsed["host"]);
if(count($exploded) > 2){
return true;
}else{
return false;
}
}
if(!hasSubdomain($_SERVER['SERVER_NAME'])){
$_SERVER['SERVER_NAME']="sub.example.com";
}

Related

how to show the content of a wildcard subdomain?

How can I do that when a user enters to a subdomain (I'll have wildcard subdomains), he will see what in the subfolder with the same name in the main domain? For example, if user will enter to works.domain.com, I want him to see what's in www.domain.com/works.
Here is my approach:
I have created a wildcard subdomain like *.domain.com
Created some subdomain into the wildcard directory with a index.php file as I can check preferences other information about this store -> see:
Now my intention is to provide the user what they ask for in the url
This code is written in wildcard/index.php file
<?php
//Get the store name from url
$host = $_SERVER['HTTP_HOST'];
$url = explode('.', $host)[0];
//Find the store name is it available in the database
$db = new database;
$qri = $db->query("SELECT * FROM store_info WHERE store_name='$url'");
$count = mysqli_num_rows($qri);
//If it returns true then show the reuquested store data
if($count != 0){
*I want to show here the folder data that requested in the url*
}else{
echo 'Store Not found';
}
Now my question is:
Is it the right approach to do it,so how can I show the requested folder data?
You can configure NGINX in front of your PHP server to route to particular directories with the following configuration (not tested). Configuring this in NGINX would be efficient than configuring this in PHP.
server {
server_name ~^(?<sub>[a-zA-Z0-9-]+)\.domain\.com$; # will cause the sub-domain to be placed in $sub
return 301 "http://testsite.net/${sub}${uri}";
}
Source: https://serverfault.com/questions/426673/nginx-redirect-subdomain-to-sub-directory

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'; }

How to serve Mobile / Desktop on same URL wthout m.version nor Media queries?

I want the same URL website.com serving totally different content based on whether mobile or not.
This means, no CSS media queries, and no specific URL m.website.com.
I don't even know if this is possible. But I think I have seen this on this website (not sure).
In other words, imagine a "mobile" folder and a "desktop" folder on the server.
Would it be possible to serve the content of "mobile" folder to the root website.com/ if mobile, and serve desktop if not.
You can do it with PHP and the HTTP User Agent:
function find_mobile_browser()
{
if(preg_match('/(alcatel|android|blackberry|benq|cell|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mobi|motorola|nokia|palm|panasonic|philips|phone|sagem|sharp|smartphone|sony|symbian|t-mobile|up\.browser|up\.link|vodafone|wap|wireless|xda|zte)/i', $_SERVER['HTTP_USER_AGENT']))
{
return true;
}
return false;
}
Call this Function in the beginning of a code and it returns True if your user uses a Mobile User Agent. Ant then you can include the actual site. The if-Block could look like this: (Im not sure about the Include/Requested URI at the Moment)
if($_SERVER['REQUESTED_URI'] == ''){
$request = index.html;
}
else{
$request = $_SERVER['REQUESTED_URI'];
}
if(find_mobile_browsers()){
include('mobile/'.$request);
}
else{
include('desktop/'.$request;
}
Be Aware that the User Agent can be changed or doesn't get send to you but in this Case it would just return the Desktop Version.
For the .htaccess see this site: http://jrgns.net/redirect_request_to_index/

Best way to detect if request came from a different domain or a sub domain

I'm building an application that uses sub domains and custom domain names that sit in the database for users, so if a request comes from another domain I'll check from the database if that custom url is indeed there or when the request comes from a subdomain, I'll check if that's there. If it is I do my stuff.
Consider this a simple example of I'm looking for:
if(is_user_request())
{
$url = get_url();
// assuming that get_url() magically decides whether to output ..
// a custom domain (http://domain.tld)
// or a subdomain's first part (eg. "this".domain.tld)
}
else
{
// otherwise it's not a sub domain nor a custom domain,
// so we're dealing with our own main site.
}
Now before you go ahead assuming that because I have 0 rep, I'm here asking for "teh codes". I have a completely working way of doing this, which is the following:
// hosts
$hosts = explode('.', $_SERVER['HTTP_HOST']);
// if there is a subdomain and that's under our $sitename
if(!empty($hosts[1]) AND $hosts[1] === Config::get('domain_mid_name'))
{
$url = $hosts[0];
$url_custom = false;
}
// if there is no subdomain, but the domain is our $sitename
elseif(!empty($hosts[0]) AND $hosts[0] === Config::get('domain_mid_name') AND !empty($hosts[1]) AND $hosts[1] !== Config::get('domain_mid_name'))
{
$url = false;
$url_custom = false;
}
// otherwise it's most likely that the request
// came from a entirely different domain name.
// which means it's probably $custom_site
else
{
$url = false;
$url_custom = implode('.', $hosts);
}
if($url)
{
return $url;
}
if($url_custom)
{
return $url_custom;
}
However, I'm sure there are better way of doing this. Because first of all, HTTP_HOST does not include 'http://', so I need to add that manually and I'm pretty sure this entire if, else thing is just an overkill. So, people smarter than me, enlighten me, please.
Oh and, no .. I do not have pre-defined sub-domains. I have a simple wildcard *.domain.tld set up, so all sub-domains go to the main script. I'm just saying this because from my search for a solution I found numerous answers that suggested to manually create a sub-domain, which is not even remotely related to what I'm asking, so let's skip that subject.
$_SERVER['HTTP_HOST'] is the correct way to do it unless you want to pass different parameters from your web server into PHP.
As for the protocol, be aware the request protocol should be determined by $_SERVER['HTTPS'] rather than assuming it's http.
For extracting the subdomain you could look at using array_shift and then running
$subdomain = array_shift(explode('.', $_SERVER['HTTP_HOST']));
But generally what you have is how it should be done.
As already said, $_SERVER['HTTP_HOST'] is the way to go.
But there are errors in your code. You're assuming that host names sent consist of 2 or 3 components but you can't be sure of that. You should at least check count($hosts) too.
If by example you use domain.tld for your own site then you're better off with first checking if domain.tld is sent (you return your page, fast); then see if substr($_SERVER['HTTP_HOST']...,-11)==='.domain.tld' and if so, return the subsite (works with any level of subdomain, still fast); else error-recovery, since a completely foreign domain has been routed to you. The key thing to note is that domain matching from the hierarchy's top means matching the hostname strings right-aligned:
.domain.tld | subsite-pattern
sub12.domain.tld | MATCH
sub12.dumain.tld | NO MATCH
sub12domain.tld | NO MATCH

How to detect "abc" in abc.domain.com or abc.sub.domain.com using PHP?

I need to detect if a user is accessing my site from a certain sub-domain. How can I detect the following example and flag it using PHP? I only want to detect if "abc" is the sub-domain and nothing more, but it has to work with various other domains after "abc".
http://abc.domain.com/
http://abc.domain/
http://abc.sub.domain.com/
Yes, they're on the "abc" sub-domain.
http://domain.com/
http://xyz.domain.com/
http://www.domain/
http://sub.domain.com/
http://xyz.sub.domain.com/
No, they're not.
This will return the subdomain:
array_shift(explode(".",$_SERVER['HTTP_HOST']));
You can check the HTTP_HOST or SERVER_NAME in your $_SERVER variable.
<?php
if(strpos($_SERVER['SERVER_NAME'], 'abc.domain.com') !== false) {
//do something
}
?>
You can access the host name from within the $_SERVER superglobal like this:
$domain = $_SERVER['HTTP_HOST']
There are then any number of ways to determine if this value begins with abc. The easiest might simply be stripos
if(stripos('abc', $domain) === 0) {
// you found it
}
Note that the use of === instead of == is VERY important here. If you used == and the substring was not found in $domain, stripos would return false, which with == 0 would evaluate as true in your conditional.
<?php
if( explode( '.', $_SERVER['SERVER_NAME'] )[0] === 'abc' ) {
//do something
}
?>
That will explode server name in parts divided by ., so it will compare the first part of the domain name with the string abc.
The explode(x,x)[N] thing is only possible in PHP 5.4+ (or 5.3+, I don't remember correctly).
You can configure your web server to redirect all your subdomains to a single PHP file where you can make up an error or redirect the user via the header() function with something like...
header('Location: http://domain.com');
Also, because you're sure that the particular PHP file is being accessed because of a subdomain, then you can do something like...
$url = $_SERVER['SERVER_NAME'];
list($subdomain) = explode('.', $url, 2);
$subdomain = trim(strtolower($subdomain));
And then use the $subdomain variable the way you like (eg. print it)...
echo $subdomain;
Just in case. For the Apache configuration, you need to modify the VirtualHost for redirecting your subdomains to a PHP file for processing.
<VirtualHost *:80>
ServerAlias *.domain.com
DocumentRoot /website/directory/page.php
</VirtualHost>
NOTE
1.) To restart Apache.
2.) Apache will give you warning that the directory does NOT exist. It's true, because you are providing a file path instead of a directory path. But this will work.

Categories