Get real base URL - php

You can get a base URL with $_SERVER["SERVER_NAME"], but sometimes if you have different projects in the same website, you need to save them in different directories. For example, if you have /var/www/myproject/, the real base URL is http://yourhost.com/myproject/.
If you try with $_SERVER["SERVER_NAME"] + $_SERVER["REQUEST_URI"], it gives the full request URL, and the problem becomes worse when you use friendly URLs. For example, if you use it in something like http://yourhost.com/myproject/controller/action/ you can't get the real base URL (yourhost.com/myproject).
How can I get the real base URL in these situations?

If I understood you right, you may need this..
$uri = isset($_SERVER['REQUEST_URI']) ? strip_tags($_SERVER['REQUEST_URI']) : '';
$urlvariables = (substr($uri, 0, 1) == '/') ? substr($uri, 1) : $uri;
$variables = explode('/', $uri);
echo $whatyouneed = $_SERVER['HTTP_HOST'] . '/' . $variables['1'];
You may give it a try.

Define it. If you have any sort of global project configuration at all (you should), you can set it up there. That’s more or less how CodeIgniter (for example) does it.
define('BASE_URL', '/myproject/'); # Include the host name if you truly must

To calculate it, put this code in your project root:
define('BASE_PATH', str_replace('\\', '/', __DIR__));
define('BASE_URL', preg_replace('|/+|', '/', strtolower(preg_replace('|^'.str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT'])).'|i', '', BASE_PATH))));

Related

PHP: Get current directory index file name

I must not be phrasing this question right because I couldn't find an answer to this but surely it's been asked before. How do I get the current filename from a URL if it's the directory's index file?
I.e. This will get index.html if I'm on www.example.com/index.html
$url = basename($_SERVER['REQUEST_URI']);
But that won't work if i'm on www.example.com. The only thing I've come up with so far is something like this:
$url = basename($_SERVER['REQUEST_URI']);
if($url == "") {
$filename = "index.html";
}
But that's obviously a bad solution because I may actually be on index.htm or index.php. Is there a way to determine this accurately?
$_SERVER['SCRIPT_FILENAME'] will determine the full path of the currently executing PHP file. And $_SERVER['SCRIPT_NAME'] returns just the file name.
This is one of the other methods.
$url = basename($_SERVER['REQUEST_URI']);
$urlArray = explode("/",$url));
$urlArray = array_reverse($urlArray);
echo $urlArray[0];
Unfortunately, the $_SERVER array entries may not always be available by your server. Some may be omitted, some not. With a little testing though, you can easily find out what your server will output for these entries. On my servers (usually Apache) I find that $_SERVER['DOCUMENT_ROOT'] usually gets me the base of the URI I'm after. This also works well for me in the production environment I work on (XAMPP). As my URI will have a localhost root. I have seen people encourage DOCUMENT_ROOT before in this situation. You can read all about the $_SERVER array here.
In this example, I get the following results:
echo $_SERVER['DOCUMENT_ROOT'] ; // outputs http://example.com
If you are working in a production environment this is very helpful because you won't have to modify your URL's when you go live:
echo $_SERVER['DOCUMENT_ROOT'] ; // outputs C:/xampp/htdocs/example
'DOCUMENT_ROOT' The document root directory under which the current
script is executing, as defined in the server's configuration file.
You could find the last occurrence of the slash / using strrchr() and simply extract the rest using substr(). The optional parameter in substr() tells where to begin. With one we skip the slash /. If you want to keep it, just set the parameter to 0.
echo substr( strrchr( "http://example.com/index.html" , "/" ) , 1 ) ; // outputs index.html
EDIT: Considering that not every server will provide $_SERVER with entities, my approach might be more reliable. That is, if the URL you pass to strrchr() is reliable. In either case, make sure you test the different outputs from $_SERVER, or your paths you provide.

About HTML and attribute href

Good evening guys, I have a problem with the attribute href because I don't know how to access folders, I give an example:
I stay in root/store/products/details.php
I want to go root/index.php
My answer is : How do I arrive to root/index.php ? I has been trying with ../../index but that didn't worked
If root is the base path on your domain, e.g. example.com/root, then if you're at example.com/root/store/products/details.php, you would have a link like below to get to your root. This href will actually work on any page. If you use ../../index.php it will only work on some pages.
Root
This is how I make all of my template links portable.
For files processed Server-Side you would link by using the SERVER_ROOT and for links in an -a href=...' you would use the SITE_ROOT.
define('SERVER_ROOT', dirname( __FILE__ ) . DS);
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ?
'https://' : 'http://') . $_SERVER['SERVER_NAME'];
if (strlen( $url ) <= 10) $url = null; // For IDE Support
define( 'SITE_ROOT', $url . DS); // The base URL
So to implement the above
Post Score</li>
Use <a href="../../index.php">
Demo Snippet:
var base = 'https://example.com/store/products/details.php'
var relative = '../../index.php'
var target = new URL(relative, base).toString()
console.log(target)
PHP defaults to index.php so you can link to
Link text
By prefixing a URL with /, like "/root/" instead of "root/", you are forcing it to read from the root of your webhost or with a VPS the directory of the website.
If you customised the DirectoryIndex you can do Link

Getting current domain + directory in php

So, I've found a way to get the current directory using dirname(__FILE__) and getting the domain with $_SERVER['HTTP_HOST']. While both of these are well and good, they aren't quite what I need them to be.
For instance, if I have a script on http://mydomain.com/scripts/myscript.php, I'd like to get http://mydomain.com/scripts/. I feel like there should be an easy way to do this and that I've somehow overlooked something.
As an aside, I am currently using the script in a cloud shared hosting environment, so the directory structure is somewhat odd.
Try:
<?php
echo $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
The only problem with that is that dirname returns the parent directory, so if you access http://domain.com/scripts/ directly you'll just get http://domain.com/ withouth the scripts. http://domain.com/scripts/script.php resolves correctly to http://domain.com/scripts/ though.
Try:
<?php
echo $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>
function url_part(){
$http=isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$part=rtrim($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME']));
$domain=$_SERVER['SERVER_NAME'];
return "$http"."$domain"."$part";
}
echo url_part;//htts://www.example.net/test

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

url of the current page without page name and query string

As mentioned in the question, I want to get the url of the page without the page name and query string.
For example my url is:
http://sub.domain.com/app/page.php?var=abc
what I want from this is:
http://sub.domain.com/app/
without the query string and page name.
I found this tutorials:
http://www.phpf1.com/tutorial/get-current-page-url.html
it was helpful but not exactly what I want.
Thanks for your answers.
The dirname(__FILE__) is not the same as happyhardik's goal.
substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'))
returns: /wwwroot/activetest2
dirname(__FILE__)
returns: /home/content/94/3671394/html/wwwroot/activetest2
To get the full URL:
$_SERVER['SERVER_NAME'].substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'))
returns: www.domainname.com/wwwroot/activetest2
I suggest the following trick:
$location = dirname(__FILE__);
If you need an absolute URL, add the following in front of it:
$protocol = 'http'.(!empty($_SERVER['HTTPS']) ? 's' : '');
$root = $protocol.'://'.$_SERVER['SERVER_NAME'];
The server vars don't hold only the path without the page name.
So you need to strip the page name from PHP_SELF (everything after the last / should do the trick)
you can use HTACCESS for this problem. so by using htaccess your URL can be changed.
Thanks.
Exactly answer that you are looking for is
$protocol = 'http'.(!empty($_SERVER['HTTPS']) ? 's' : '');
$currURL = $protocol.'://'.$_SERVER['SERVER_NAME'].substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
=======================================Explanation
For Example your current url is
http://sub.domain.com/app/page.php?var=abc
it will return
http://sub.domain.com/app

Categories