How to automatically assign sudomain to users during registration - php

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

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

Need to pass subdomain codeIgniter info to domain with wordpress

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?

Can a Directory alone load specific query on a page?

On websites such as facebook and many others you see URLs such as www.facebook.com/username. How does a URL such as this actually load the users information from a MySQL database? and what is the actual file it is displaying on? I would assume there's not really a folder for each user that it is referring to. If my question doesn't make sense can you at least point me in the right direction to set something like this up through PHP?
Again, I want example.com/username to load my users profile. How does this work?
By using apache's .htaccess file to manage a RewriteEngine, all of your pages can be funneled through an index.php file. After confirming that the requested page is not actually a page that you've intended to be a default part of your web page, you can fall back on the code below, to discover a user account. If a user account is not discovered, then the likelihood is that the page being accessed is simply a 404, which you could then redirect to as a catch-all scenario
.htaccess file
RewriteEngine on
RewriteBase /
RewriteRule !\.(xml|js|ico|gif|jpg|png|css|swf|php|txt|html|otf)$ index.php
php logic to run after confirming the requested page, isn't something like a contact-us page, or any typical web page an end user would be attempting to access.
if(preg_match("/^\/(?P<username>[^\/]*)/", $_SERVER['REDIRECT_URL'], $matches)) {
$result = mysql_query("SELECT * FROM users WHERE username = '" . mysql_real_escape_string($matches['username']) . "'");
if($user_record = mysql_fetch_row($result)) {
echo "DO WHATEVER YOUR HEART CONTENTS HERE :)";
} else {
header("Location: error-404.php");
}
}
It is all loaded dynamically via the database. For example, my Facebook name is "benroux". In facebook's user table, there is going to be a unique column called, lets say, nickname. When I visit Facebook, they are parsing the path info and essentially calling a query in the form:
select * from user where nickname = "{$nickName}"
Now, this is an over simplified example, but I hope it gives you an idea of what is going on here. The key is that there are 2 types of url vars, the facebook.com/pagename.php?id=blah and the restful style path info vars facebook.com/pagename/var1/var2/
If you are looking to have example.com/benroux load my user page, you need to make your index.php (I'll use PHP) load the path info ( http://php.net/manual/en/function.pathinfo.php ) and then query the database as I have described above.
try to
print_r($_SERVER);
you will get that parameters. Then you just need to split them.
Something like
$directory = $_SERVER['REQUEST_URI'].split('/')[1];
So, put $directory into query

create subdomain programmatically in PHP

I am on shared hosting and on a add on domain.
I need to create subdomain for each user of my website like if the username is jeff then he should have a url jeff.mydomain.com.
How can I create it programmatically using PHP?
There's two parts to this. Firstly you'll need to setup a wildcard dns entry.
Once you've got that setup you should have all your requests pointed back to a single domain. From there you can then use php to figure out which domain you're currently on:
$domain = $_SERVER['HTTP_HOST'];
$base = 'mydomain.com';
$user = substr($domain, 0, -(strlen($base)+1));// the user part of the domain
if(!empty($user)) {
$user = sanatiseUser($user);
require_once $user.'.php';
}
You need to set apache to listen for all domains coming into a specific IP.
You then need to setup a wildcard DNS entry to point *.domain.com to that IP.
Then inside your app, use $_SERVER['HTTP_HOST'] to determine which user to load.

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