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'; }
Related
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
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 ...
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";
}
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
I have a domain. Let's call it www.example.com for this question. Thanks to the wonders of how I have things setup and/or Wordpress, if I were to type in example.com it would redirect me to www.example.com and Wordpress would do its thing. I also have a subdomain called members.example.com in which I have built a rather elaborate system using CodeIgniter into the folder /members off of public_html.
In a perfect world, what I would like to do is be able to put some php code into Wordpress that would allow someone reading the "www" side of things to be able to determine if they are also currently logged in on the "members" side of things. I know the CodeIgniter session persists so that whenever I jump on to the members side, I'm still logged in. My first thought was to put together a quick page in CI that did this:
public function isLogged()
{
$x = "off";
if ($this->session->userdata('memberKey') != 0) {
$x = "on";
}
echo $x;
}
Then, whenever I would run the link members.example.com/login/isLogged , I would always get either "off" or "on" to determine if I was in or not. The memberKey would be either 0 for not logged in, or a number based on someone's corresponding key in the database. My hope was that I would be able to run something like THIS from the www side (within Wordpress)
$homepage = file_get_contents('http://members.example.com/login/isLogged');
...and I would be able to act on whether the person was logged in or not. Well, obviously the flaw here is that when I call the above function, I'm always going to get "off" as my result because I'm making that call from the server, and not from the client in question that needs this information.
What would be the most elegant solution to being able to read this information? Is there a way to read cookies cross platform?
Well, I realized that I worked through the process, and I don't want to leave anyone hanging, so my solution was this:
First, I know that for my cookies, I went into codeIgniter's /application/config/config.php and put the following in as my cookie domain (line 269 - and I've changed the domain name here to protect my client, obviously)
$config['cookie_domain'] = ".example.com";
I'm being careful here, and using the "." before the domain to cover all subdomains.
I also know that I'm writing my session data to a database. So, on the Wordpress side of things, I put in this code at a certain location:
$memCCinfo = unserialize(stripslashes($_COOKIE['ci_session'])); // Changed for OBVIOUS reasons
$mysqli = mysql_connect('localhost', 'NAME', 'PASSWORD'); // Changed for OBVIOUS reasons
$mysqlDatabase = mysql_select_db('DATABASE',$mysqli); // Changed for OBVIOUS reasons
$isLoggedCC = "off";
$sessInfoQry = mysql_query('SELECT user_data FROM ci_sessions WHERE session_id = "' . $memCCinfo['session_id'] .'"',$mysqli);
while ($sessInfo = mysql_fetch_assoc($sessInfoQry)) {
$breakOutInfo = unserialize(stripslashes($sessInfo['user_data']));
if (is_array($breakOutInfo)) { $isLoggedCC = "on"; }
}
Then, I now have a way to determine if a member is logged on to the "members" side or not. Question is... are there any holes in what I'm doing that I should worry about?