how to show the content of a wildcard subdomain? - php

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

Related

How to automatically assign sudomain to users during registration

I'm currently creating a custom application which involves letting each users have its own subdomain but I'm finding it hard to make that work.
I want user to do this on the fly during registration.
How do I make this work using PHP, .htaccess and MySQL?
This is what I've done so far.
<?php
$host = $_SERVER ['HTTP_HOST'] ;
$subdomain = "myshop" ;
$domain = "$subdomain.$host" ;
echo $domain ;
?>
First point all sub domains to your server with a wildcard DNS-entry
*.example.com
when a user navigates to user1.example.com, have your php script look up the sub domain
$user = array_shift((explode(".",$_SERVER['HTTP_HOST'])));
check if the user exists in the database, or show an error.
You now have the username available and can use that parameter for querying the database.
When a user registers on your site, just create the user in the database and then redirect them to newuser.example.com

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

Redirect included files

I have this file which stores my db info
<?php
$DBServer = 'this';
$DBUser = 'is';
$DBPass = 'my';
$DBName = 'secret';
?>
And it is included where I need it to connect to the db. My question is, how can I prevent users from going to mywebsite/db_info.php ? I know it displays a blank to them and they don't have access to the info, but I'd like to redirect them to the index page. The problem comes when this file being included in another one, it will always redirect to the index page when used(when I will connect to the db).
With apache, You can put your file in a separate folder within a .htaccess file with this content:
Order deny,allow
Deny from all
So you will have:
/yourPrivateFolder/.htacces
/yourPrivateFolder/db_info.php
This will prevent external access to your file
First, what is the point to redirect a file with important information like database access? No users should have access to this file, or even his name and path.
There are some approaches you can choose, one security option it is to allocate your db_info.php file outside the public root of your domain. Exemple:
yourdomain.com = /home/user/www/
your file should be: /home/user/db_info.php (or outsite /www/ folder!)

.htaccess and php includ on same server using subdomain

I have been searching all day for a solution to this and searched here.
I have a central file for including functions for all sites on the server, this looks up to the database and if valid includes the file as a .inc as the sites could be on any server so has to process over a url. So I set up a subdomain to test this and everything works fine, however if someone where to look up the link in the site they can go direct and browse the .inc file.
I've tried looking up on here how to deny someone from browsing the file if they are viewing through the browser. This works, however if the website requesting/including the functions.inc are hosted on the same server then the requesting HTTP_HOST/REFFERER becomes the subdomain and the functions.inc file is exluded.
So far I had this:-
RewriteEngine on
RewriteCond %{SERVER_NAME} !^http://(www.)?subdomainchecker.mysite.co.uk/.*$ [NC]
RewriteRule .(inc)$ - [F]
See the subdomain acts like a service. And the reason I want to do this is that I want all the php functions in one place for everyone. that way I'm only maintaining one file. One bug fix etc.
Now I thought there has to be a way to check that there is a difference when using a subdomain.
However if there is a better way???
If this doesn't work maybe I could get htaccess to include (a virtual folder) to my subdomain folder so that I don't have to go over a url... but that wont work if the site gets hosted on another server?
Or... could I do a look up straight to the DB, as the user credentials only has SELECT privileges only. Could the DB contain all the functions and output them from a text field? Or have functions listings in a DB and retrieve the function when I do a database call?
Or... could I do a php XML request and return the php functions within an XML node?
I'd rather keep the functions and classes in a file than on a DB, but I am not sure how the best way to go about it is. All I want to do is keep my php functions in one place.
If anyone has any ideas?
Thanks
Andi
Ok So I answered my own question eventually like so.
Step 1) I password protected my .inc files using .htaccess in the directory that stores my include files on my webservice (subdomain). Protecting both .inc and .php
Options -Indexes
<FilesMatch "\.(inc|php|anyext)$">
AuthType Basic
AuthName "authenticate this puppy"
AuthUserFile /[servername]/[accountusernameOnServer]/.unseenfolder/public_html/[website_authentication_folder]/.htpasswd
Require valid-user
</FilesMatch>
This folder is now password protected by the encrypted .htpassword file outside my web root.
Step 2) Back in my now protected webserivce folder contains three files (one .php / two .inc files containing my functions and application file (session variables for the site)
authenticate_some_websitesite_against_my_own_DB.php
This contains the account verification process (lookup to a database on my own server), note the host is always Localhost and I am using PHP PDO for convenience (just in case you have a Postgre database or MSSQL etc)
application_for_site.inc
This contains/sets all the site session variables (user ID etc)
a file without a name called .anyext containing my global functions for all sites
Now here is the cool thing. THE PROCESS or how I got it to work.
I put my new website in a subfolder and include a file called authentication.php in my local folder in the site. I call this in the head of index.php in the site.
This file contains my webkey, usernames and passwords to my clients table in my DB which is used to verify in the file I call from my subdomain... authenticate_some_websitesite_against_my_own_DB.php
I put all these variables in a url variable which also include my username and password to my protected subdomain.
So now it looks something like this: Of course I set the variables above
$link = "authenticate_anewsite.php";
// Create Website check link criteria.
$link .= "?website=" . $_SERVER['HTTP_HOST'];
$link .= "&website_folder=$website_folder";
$link .= "&webkey=$webkey";
$link .= "&username=$username";
$link .= "&password=$password";
$link .= "&base_url=$base_url";
$link .= "&DBLangtype=$DBLangtype";
$link .= "&localDBtype=$localDBtype";
$link .= "&content_folder=$content_folder";
$link .= "&google_api=$google_api";
$link .= "&menu_folder=$menu_folder";
$link .= "&news_folder=$news_folder";
$link .= "&events_folder=$events_folder";
$link .= "&documents_folder=$documents_folder";
$link .= "&uploaded_images_folder=$uploaded_images_folder";
$link .= "&gallery_folder=$gallery_folder";
//// Do not delete required to access the link below
$PHP_AUTH_USER = "website_user"; /// Do NOT AMEND THIS
$PHP_AUTH_PW = "passw0rd"; /// Do NOT AMEND THIS
$path = "http://$PHP_AUTH_USER:$PHP_AUTH_PW#www.websitecheck.mydomain.com/"; /// Do NOT AMEND THIS LINK
$authCHK = $path . $link;
/// going to check that we connect
$handle = curl_init($authCHK);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
/// If server can't connect
if($httpCode == 401) {
//set error handler
set_error_handler("customError", E_ALL);
/* Handle 404 here. */
trigger_error("<strong style='color:red;'>Error: SERVER - $httpCode</strong> $website failed to connect to authenticate site.<br />Connection string..:\n $authCHK");
// error_function(error_level,error_message,error_file,error_line,error_context)
} else {
require_once($authCHK);
} // end if
curl_close($handle);
Now the file successfully includes the .php file from the server because the username and password to it are parsed in the url.
in the authenticate_anewsite.php I just included (actually I did a require_once) this is the bit that authenticates my website against my clients table which runs these checks:
The MySQL database username and password are stored in this file. This account has only the priveliges of select.
checks clients for existence of a webkey which I give them
check the username against the clients table
checks the password
paid = true
active = true
So the SQL looks like this:
SELECT * FROM clients where paid=1 and active=1 and webkey = '$webkey' and username = '$username' and password = '$password'
If the required checks are verified then the num of records is 1, if this is >0 then my authenticate_anewsite.php includes the other two .inc files like this (the folder username and password have already been verified in the call.
if ($count_check > 0) {
$appliation = $path . 'application_for_my_site.inc';
$appliation = file_get_contents($appliation);
echo $appliation;
$functions = $path . '.anyext';
$functions = file_get_contents($functions);
echo $functions;
} else {
// redirect to the holding page
//header('Location: $base_url/500.shtml');
}
At this point its probably ok to set a session variable to not keep checking the database every time the index.php page is called from the actual site.
OK so this actually works although a little Archaic.
The advantages of all this:
Functions and application are served from one file in a central location (one bug fix can fix all sites)
Doesn't matter if the website is hosted on my server or on another
A user cannot browse the files directly, because htaccess has password protected them
Even if a user were to browse the subdomain/webservice in the browser by putting the link together with the folder username and password the browser, it doesn't server the PHP as is server sided script. It wont be able to see my username and database password, sql, or the name of the files I'm calling in by viewing source
I have my functions in a file with no file name and an extension that I have made up this is the purpose of the .anyext (htaccess treats this the same and protects it, but because its an extension that I made up it makes it harder to guess, and generally invisible)
indexes have been switched off so general browsing is not allowed on my webservice
OK so it took me two days to come up with this solution. I hope that my idea will help save someone a lot of time!
Bless You :o)
Andi Lee Davis

dynamic sub-domain creation with PHP in a linux based server

I want to create sub-domains using PHP on the fly. Suppose a user registers himself as a name "ABC". Then I want to create a sub-domain named 'ABC.mydomain.com' automatically by PHP. I'm using a linux based server.
Would anyone point me to the right direction?
You should be aware that this is easily done using wildcard DNS records. This way:
you do not have to register each user to your DNS server.
your DNS A-record may contain as few as 1 record: e.g *.mydomain.com -> 12.34.56.78
your web server at 12.34.56.78 have to be configured to accept wildcard
In your server-side scripts, you dynamically resolve "abc.mydomain.com" on your controller/routing code by checking if abc is an existing active username, sample code below:
<?php
// Note that I am using SERVER_NAME vs HTTP_HOST,
// but for additional safety also check your httpd.conf
list($user, $domain) = split("\.", $_SERVER['SERVER_NAME'], 2);
// check if domain is correct,
// or you can leave this part if the web server checks this already
if ($domain === "mydomain.com") {
// here, you verify $user if existent/active
// and reroute or render the page depending on request params
// ...
}
?>

Categories