Reputation: 699
Well, I am working on core php, I am unable to define a constant base URL for my application.
I am working using xampp on mac os, I have the main file initilize.php in htdocs/myproject/private directory, which contain the code to define a base URL
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$validURL = str_replace("&", "&", $url);
Now when I include the initialize.php file in myproject/index.php as,
<?php
require_once 'private/initialize.php';
header('Location: site/');
I got BASE_URL as http://localhost/myproject/site , but when I include the initilize.php file in the site/create.php I got the BASE_URL as http://localhost/myproject/site/create.php, I am unable to define a base URL for myproject, which in xampp case is localhost/myproject and after deployment it must be http://subdomain.myproject.com any suggestion in this regard. Thanks in advance.
Upvotes: 1
Views: 2622
Reputation: 699
Finally, I solve my problem by using the following piece of code
/*
* Assign the root URL to a PHP constant
* Do not need to include the domain
* Use same document root as web server
* Can dynamically find everything in URL up to "/site"
*/
$site_end = strpos($_SERVER['SCRIPT_NAME'], '/site') + 5;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $site_end);
define("WWW_ROOT", $doc_root);
$url = "http://" . $_SERVER['HTTP_HOST'] . WWW_ROOT;
$validURL = str_replace("&", "&", $url);
define("BASE_URL", $validURL);
It always return BASE_URL = http://localhost/myproject/site
Upvotes: 0
Reputation: 4719
You could define a static base_url for your myproject
directory like this :
$protocol = if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$servername = filter_input(INPUT_SERVER, 'SERVER_NAME');
$url = $protocol . $servername;
if (strstr($servername, 'localhost')) {
$url .= '/myproject/'; // add project directory on localhost setup
}
$validURL = str_replace("&", "&", $url);
Upvotes: 2
Reputation: 329
You can do it by using environmental variables (.env files or apache/nginx configuration) or you can set it manually as shown below, there is no magic which can find a base url on your localhost if you the /myproject part to it.
$protocol = if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$baseUrl = $protocol . $_SERVER['HTTP_HOST'];
if (strstr($baseUrl, 'localhost')) {
$baseUrl = 'http://localhost/myproject/site';
}
Upvotes: 1