Auto-rewrite URL in php - php

I'm wondering if there is a pre-existing PHP function that will rewrite a given URL, adding a pre-defined application context. For example: I have a link like this:
Home
I would want this link to point to "/" under the production environment, but under the development environment it should point to "/app_context/". Is there any PHP function that can do this for me?

You can always change the server config on your production server to match the live server by changing the document root for the production volume (unless you're on a shared host like Bluehost or something like that). There are exceptions to this... example:
BluehostDomain1.com root is /
If you host a second domain with bluehost, then it's a subdirectory (and accessible) of and from the first domain.
BluehostDomain2.com root is / by default and also accessible at /BluehostDomain1.com/BluehostDomain2.com.
In these cases I do something like this:
Make the code look for the domain executing it:
<?php
switch ($_SERVER['SERVER_NAME']){
case "production.server.com":
$dR = '/';
break;
default:
//Dev server dev.server.com
$dR = '/app_context/';
}
$code = 'Home';
$code .= 'About'; // /about/
echo $code;
?>

I usually define a WEBROOT constant that holds this value, and then prepend it to all links:
define('WEBROOT', str_replace('//', '/', dirname($_SERVER['SCRIPT_NAME']) . '/'));
Home
About

Problem solved. I realized that I can just use relative path. For instance:
Home

you can use something like:
<?php
if(/* test for developement environement */) {
echo 'Home';
}
else {
echo 'Home';
}
?>

Related

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

links not working on web server

i have developed a php application which is running perfect on local server. when i deployed the application on web server the links are not working
1) my site is "abc.myapplication.com" (abc is subdomain)
i defined following variable in config file
define('ROOT_PATH', $_SERVER['DOCUMENT_ROOT']);
ROOT_PATH variable shows /home/punjabfo/public_html/abc (which is perfect)
for link i used following code
Add Record
link should go to "abc.myapplication.com/addrecord.php" but link go to
"abc.myapplication.com/home/punjabfo/public_html/abcaddrecord.php"
i tried a lot but could not fin the issue. please help. thanks
What is wrong with Keeping It Simple
Add Record
Let the server do all the work, as it gets it right and you do less messing around.
Try
define('ROOT_PATH', $_SERVER['HTTP_HOST']);
Just use
Add Record
You can try -
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo 'http://'.parse_url($url, PHP_URL_HOST) . '/';
Your issue is "$_SERVER['DOCUMENT_ROOT']". $_SERVER['DOCUMENT_ROOT'] stands for the root directory on the server (dir-path). What you need, is the URL and not the file-system-path.
Take a look on
<?php
echo "<pre>";
var_dump($_SERVER);
echo "</pre>";
?>
Why not to do
Add Record
Of course you do not need ROOT_PATH in the URL. What you do is returning full path of the file, instead of link. And btw, full path is incorrect itself, as you forgot slash before addrecord.php.

How to get the same $_SERVER['REQUEST_URI'] on both localhost and live server

So this is the thing, Im building dispatcher class that needs to dispatch http requesd based on Request URI, so Im interesed only in part of URI that comes behind domain.
Now when im working on live server on URI like this:
www.domain.com/controller/method/params/
REQUEST_URI would return:
/controller/method/params/
But when im working on local machine i have URI like this:
localhost/project/controller/method/params/
and REQUEST_URI would return:
/project/controller/method/params/
So is there an elegant and neat way to tell php to get me only the params I need fromu URI?
It dosent have to be $_SERVER['REQUEST_URI'], but I need that string the same on both live and local server?
Thanks!
Dispatcher compares current request URI with URI defined in config file. And on live server it matches, but on local machine there is one segment more then on live server.
How could I deal with this?
Usually I configure my local webserver to respond on "test.mysite.com" and in hosts file i set test.mysite.com to 127.0.0.1, in that way i better simulate production environments, and i'm not forced to use subpaths in urls
If you use apache webserver, you can simply setup N virtual hosts.
You can simply remove the path from the start of the URL if it exists.
$path = '/project/'; // for localhost/project/controller/method/params/
//$path = '/'; // for domain.tld/controller/method/params/
$url = getenv('REQUEST_URI');
if(strpos($url, $path) === 0)
{
$url = str_replace($path, '', $url, 1);
}
print $url;
I haven't tested the above code so stray "/" might mess it up. You can always trim the URL with something like $url = trim($url, '/') if needed.
$url = $_SERVER['REMOTE_ADDR'].$_SERVER['REQUEST_URI'];
is that what you want?
I use the built in array_shift() function if localhost is detected.
if ($_SERVER['HTTP_HOST'] == 'localhost') {
$array_uri = explode('/', $_SERVER['REQUEST_URI']);
array_shift($array_uri);
$uri = $array_uri;
} else {
$uri = explode('/', $_SERVER['REQUEST_URI']);
}

Redirect to another directory

My site is almost up and running, but in the original code there are, for example img src="/design/pic1.png" and so one. On the real server, there is a must dir, web, so the new paths should be img src="web/design/pic1.png" but I don't want to rewrite all paths.
Is there another option?
Depending on your set up, one approach would be to have a constant that dictates your base path which is dependant on your environment.
For example, suppose in your development environment you're happy to put all images in $WEB_ROOT . "/design/", but on your production environment it's $WEB_ROOT . "/web/design/", then you might end up with something like this:
<?php
// initialise stuff for development
if(ENVIRONMENT == ENV_DEV) {
define("BASE_PATH", "/");
// initialise stuff for production
} elseif(ENVIRONMENT == ENV_PROD) {
define("BASE_PATH", "/web");
}
?>
Then, in your HTML, you could use this BASE_PATH constant like so:
<img src="<?=BASE_PATH;?>/design/pic1.png" />
How you decide what is ENV_DEV and ENV_PROD in this example, is entirely up to you.
One approach would be to detect it based on the domain (using $_SERVER['HTTP_HOST'], which has some caveats).
Another approach would be to initialise this in your web configuration. Suppose you're using Apache2, you might use the SetEnv directive.
In your httpd.conf:
SetEnv MY_ENVIRONMENT DEV
Which you can access in PHP using:
<?php
$_SERVER['MY_ENVIRONMENT'];
// or...
getenv("MY_ENVIRONMENT");
?>

how to differentiate whether the environment is a virtual host or not?

I have this code here:
$config['SUBFOLDER'] = '/';
$config['APP_URL'] = 'http://'.$_SERVER['HTTP_HOST'].$config['SUBFOLDER'];
And APP_URL is used throughout the HTML templates. The problem is - the config needs to be as universal as possible, so there's less to do when switching environments.
Now, it works like this when I have configured a virtual host for my project, but when it isn't a virtual host, but sort of a localhost/myproject/ - the $config['SUBFOLDER'] has to be set manually to /myproject/
How do I do this programmatically?
You could set a variable in, for example, your htaccess file.
#.htccess
SetEnv APPLICATION_ENV development
then in your website do a check for this:
<?php
//live
$config['SUBFOLDER'] = '/';
//on localhost - override live settings
if(APPLICATION_ENV === 'development')
{
$config['SUBFOLDER'] = '/myproject';
}
With this approach you only need to change one variable in the htaccess file.
If you just want to check if you are running on localhost, doing a check on $_SERVER['HTTP_HOST'] will also work:
<?php
if($_SERVER['HTTP_HOST'] === 'localhost')
{
$config['SUBFOLDER'] = '/myproject';
}
Check the URL whether it contains LOCALHOST or a normal domain name and wrap your config up in a conditional dependent on what the URL is.
I take a slightly different approach..
if ($_SERVER['HTTP_HOST'] == 'testingserver') // local environment here
{
// local settings
}
else if ( // remote environment here
$_SERVER['HTTP_HOST'] == 'www.something.com' ||
$_SERVER['HTTP_HOST'] == 'something.com'
)
{
// remote settings
}
else // error.. this shouldn't happen
{
echo $_SERVER['HTTP_HOST'];
}

Categories