adiian
adiian

Reputation: 1392

How do you create subdomains using PHP? Is is possible on shared hosting?

I'm interested to create subdomains on the fly directly from php. For example when an user create a new page I want that page to be newpage.mydomain.com. Is that possible without changing the php or apache configuration files (supposing I'm using a shared hosting account).

Later Edit: I'm talking about my domain, and I have full access to the domain administration area.

Upvotes: 1

Views: 2038

Answers (3)

Mathieu
Mathieu

Reputation: 5695

it's not possible through php alone. and I don't think shared hosting allow that. anyway, for that you have to own a domain (or have permission to edit DNS record) then you can add wildcard record to allow any subdomain to point to a single machine (identified by its IP adress)

edit (from Powerlord comment)

apache have to redirect each subdomain to the same vhost usually with ServerAlias *.example.com in a vhost configuration

/edit

then in php you can check which from subdomain the page is request by parsing(spliting) $_SERVER['HOST_NAME']

eg:

$host = explode ('.', $_SERVER['HOST_NAME']);
array_pop ($host);
array_pop ($host);
$subdomain = join ('.', $host);

Upvotes: 0

Layke
Layke

Reputation: 53156

Yes you can do this. You need to make sure that first you set up a wildcard * A record against your domain in your domain register DN panel.

Once you have set up the wildcard, you can just look at the >

 $_SERVER["SERVER_NAME"]

Upvotes: 0

Urda
Urda

Reputation: 5411

  1. Set up an error document in your .htaccess file that redirects every single 404 to a file called maybe redirection.php. This .php file is what will handle the "on the fly" redirects.

  2. Add a wildcard DNS record in your zone files, so that [whateverhere].yourdomain.com points to the IP of your webserver

  3. Add a wildcard serveralias in your apache configs by using: ServerAlias *.yourdomain.com

  4. Write the following code in your redirection.php file.

.

<?php

$url = $_SERVER["REQUEST_URL"];
$newurl=str_replace(".yourdomain.com","",$url);
$newcomplete="http://yourdomain.com/".$newurl;
Header("Location: ".$newcomplete);

?>

Does this help a bit?

Upvotes: 1

Related Questions