Home url in functions php

How do I get the base URL with PHP?

I am using XAMPP on Windows Vista. In my development, I have http://127.0.0.1/test_website/ . How do I get http://127.0.0.1/test_website/ with PHP? I tried something like these, but none of them worked.

echo dirname(__FILE__) or echo basename(__FILE__); etc. 

25 Answers 25

If you plan on using https, you can use this:

function url() < return sprintf( "%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI'] ); >echo url(); #=> http://127.0.0.1/foo 

Per this answer, please make sure to configure your Apache properly so you can safely depend on SERVER_NAME .

 ServerName example.com UseCanonicalName on 

NOTE: If you’re depending on the HTTP_HOST key (which contains user input), you still have to make some cleanup, remove spaces, commas, carriage return, etc. Anything that is not a valid character for a domain. Check the PHP builtin parse_url function for an example.

@admdrew thanks. I double-checked that REQUEST_URI already includes a / ; it does. @swarnendu please be more careful when editing other people’s answers. That should’ve been a comment instead.

Function adjusted to execute without warnings:

function url() < if(isset($_SERVER['HTTPS']))< $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http"; >else < $protocol = 'http'; >return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; > 
if (!function_exists('base_url')) < function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE)< if (isset($_SERVER['HTTP_HOST'])) < $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; $hostname = $_SERVER['HTTP_HOST']; $dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY); $core = $core[0]; $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s"); $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir); $base_url = sprintf( $tmplt, $http, $hostname, $end ); >else $base_url = 'http://localhost/'; if ($parse) < $base_url = parse_url($base_url); if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = ''; >return $base_url; > > 
// url like: http://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php echo base_url(); // will produce something like: http://stackoverflow.com/questions/2820723/ echo base_url(TRUE); // will produce something like: http://stackoverflow.com/ echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); // will produce something like: http://stackoverflow.com/questions/ // and finally echo base_url(NULL, NULL, TRUE); // will produce something like: // array(3) < // ["scheme"]=>// string(4) "http" // ["host"]=> // string(12) "stackoverflow.com" // ["path"]=> // string(35) "/questions/2820723/" // > 
 $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/'; 
$modifyUrl = parse_url($url); print_r($modifyUrl) 

Its just simple to use
Output :

Array ( [scheme] => http [host] => aaa.bbb.com [path] => / ) 

@AnjaniBarnwal can you explain why? I think this is the best way if you have a string with an url and want to get the base url like https://example.com from https://example.com/category2/page2.html?q=2#lorem-ipsum — that has nothing to do with the current page you are at.

Читайте также:  Php new domdocument utf 8

I think the $_SERVER superglobal has the information you’re looking for. It might be something like this:

echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] 

You can see the relevant PHP documentation here.

this keeps redirecting to same page user is at now. how can I fix this to redirect to home page? Im on apache, localhost. php7

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http"); $config['base_url'] .= "://".$_SERVER['HTTP_HOST']; $config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']); echo $config['base_url']; 

The first line is checking if your base url used http or https then the second line is use to get the hostname .Then the third line use to get only base folder of your site ex. /test_website/

The following code will reduce the problem to check the protocol. The $_SERVER[‘APP_URL’] will display the domain name with the protocol

$_SERVER[‘APP_URL’] will return protocol://domain ( eg:-http://localhost)

$_SERVER[‘REQUEST_URI’] for remaining parts of the url such as /directory/subdirectory/something/else

 $url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI']; 

The output would be like this

Rather than just pasting a random bunch of code, explain what you did and why. That way, the OP and any future readers with the same problem can actually learn something from your answer, rather than just copy/pasting it and asking the same question again tomorrow.

$host = $_SERVER['HTTP_HOST']; $host_upper = strtoupper($host); $path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); $baseurl = "http://" . $host . $path . "/"; 

URL looks like this: http://example.com/folder/

You can do it like this, but sorry my english is not good enough.

First, get home base url with this simple code..

I’ve tested this code on my local server and public and the result is good.

 // now last steps // assign protocol in first value if ($tmpURL !== $_SERVER['HTTP_HOST']) // if protocol its http then like this $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/'; else // else if protocol is https $base_url .= $tmpURL.'/'; // give return value return $base_url; > ?> // and test it echo home_base_url(); 
local machine : http://localhost/my_website/ or https://myhost/my_website public : http://www.my_website.com/ or https://www.my_website.com/ 

use home_base_url function at index.php of your website and define it

and then you can use this function to load scripts, css and content via url like

will create output like this :

and if this script works fine.

Add the following code to a page:

 $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") < $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; >else < $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; >return $pageURL; > ?> 

You can now get the current page URL using the line:

Sometimes it is needed to get the page name only. The following example shows how to do it:

 echo "The current page name is ".curPageName(); ?> 
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://"; $url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI']; 
/*url.php file*/ trait URL < private $url = ''; private $current_url = ''; public $get = ''; function __construct() < $this->url = $_SERVER['SERVER_NAME']; $this->current_url = $_SERVER['REQUEST_URI']; $clean_server = str_replace('', $this->url, $this->current_url); $clean_server = explode('/', $clean_server); $this->get = array('base_url' => "/".$clean_server[1]); > > 

This is the best method i think so.

$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http"); $base_url .= "://".$_SERVER['HTTP_HOST']; $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']); echo $base_url; 

The following solution will work even when the current url has request query string.

 $protocol = $_SERVER['PROTOCOL'] == isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http'; $url = "$protocol://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $url = str_replace($currentFile, '', $url); return $url; > 

The calling file will provide the __FILE__ as param

Here’s one I just put together that works for me. It will return an array with 2 elements. The first element is everything before the ? and the second is an array containing all of the query string variables in an associative array.

function disectURL() < $arr = array(); $a = explode('?',sprintf( "%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI'] )); $arr['base_url'] = $a[0]; $arr['query_string'] = []; if(sizeof($a) == 2) < $b = explode('&', $a[1]); $qs = array(); foreach ($b as $c) < $d = explode('=', $c); $qs[$d[0]] = $d[1]; >$arr['query_string'] = (count($qs)) ? $qs : ''; > return $arr; > 

Note: This is an expansion of the answer provided by maček above. (Credit where credit is due.)

Edited at @user3832931 ‘s answer to include server port..

$base_url="http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER["REQUEST_URI"].'?').'/'; 

Try using: $_SERVER[‘SERVER_NAME’];

I used it to echo the base url of my site to link my css.

/assets/css/your-stylesheet.css" rel="stylesheet" type="text/css"> 
$some_variable = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1); 

and you get something like

There is much code on this Q&A entry that belongs into the danger zone, this one as well especially because of the use of PHP_SELF.

In my case I needed the base URL similar to the RewriteBase contained in the .htaccess file.

Unfortunately simply retrieving the RewriteBase from the .htaccess file is impossible with PHP. But it is possible to set an environment variable in the .htaccess file and then retrieve that variable in PHP. Just check these bits of code out:

Now I use this in the base tag of the template (in the head section of the page):

So if the variable was not empty, we use it. Otherwise fallback to / as default base path.

Based on the environment the base url will always be correct. I use / as the base url on local and production websites. But /foldername/ for on the staging environment.

They all had their own .htaccess in the first place because the RewriteBase was different. So this solution works for me.

Currently this is the proper answer:

$baseUrl = $_SERVER['REQUEST_SCHEME']; $baseUrl .= '://'.$_SERVER['HTTP_HOST']; 

You might want to add a / to the end. Or you might want to add

$baseUrl .= $_SERVER['REQUEST_URI']; 
$baseUrl = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; 
function server_url() < $server =""; if(isset($_SERVER['SERVER_NAME']))< $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], '/'); >else < $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_ADDR'], '/'); >print $server; > 

The redundant/WET style is not attractive. This code-only answer is missing its educational explanation.

I had the same question as the OP, but maybe a different requirement. I created this function.

/** * Get the base URL of the current page. For example, if the current page URL is * "https://example.com/dir/example.php?whatever" this function will return * "https://example.com/dir/" . * * @return string The base URL of the current page. */ function get_base_url() < $protocol = filter_input(INPUT_SERVER, 'HTTPS'); if (empty($protocol)) < $protocol = "http"; >$host = filter_input(INPUT_SERVER, 'HTTP_HOST'); $request_uri_full = filter_input(INPUT_SERVER, 'REQUEST_URI'); $last_slash_pos = strrpos($request_uri_full, "/"); if ($last_slash_pos === FALSE) < $request_uri_sub = $request_uri_full; >else < $request_uri_sub = substr($request_uri_full, 0, $last_slash_pos + 1); >return $protocol . "://" . $host . $request_uri_sub; > 

. which, incidentally, I use to help create absolute URLs that should be used for redirecting.

Источник

home_url() │ WP 3.0.0

Используйте эту функцию, когда нужно получить URL сайта (фронта), а не URL WordPress (админки) (см. Общие настройки). Используйте site_url(), когда нужно получить URL WordPress (админка, где лежат файлы).

Константа WP_HOME — в wp-config.php можно указать константу WP_HOME, тогда её значение будет браться для этой опции, а не значение из БД.

Используйте get_home_url( $blog_id ), когда нужно получить ссылку на другой сайт в сети сайтов, а не URL адрес текущего сайта.

Возвращает

Использование

$path(строка) Путь, который будет вставлен в конец ссылки.
По умолчанию: » $scheme(строка) Протокол передачи данных. По умолчанию вычисляется через is_ssl(). Может быть: http или https .
По умолчанию: null

Примеры

#1 Примеры получения адреса сайта:

echo home_url(); // http://example.com echo home_url( '/' ); // http://example.com/ echo home_url( 'blog', 'relative' ); // /blog echo home_url( 'blog' ); // https://example.com/blog echo home_url( '/blog', 'https' ); // https://example.com/blog echo home_url( '#hash', 'https' ); // https://example.com/#hash echo home_url( '//foo.bar/foo' ); // http://example.com/foo.bar/foo echo home_url( 'http://foo.bar/foo' ); // http://example.com/http://foo.bar/foo echo home_url( '/mypage?id=123' ); // https://example.com/mypage?id=123

Список изменений

Код home_url() home url WP 6.2.2

function home_url( $path = », $scheme = null )

Cвязанные функции

URL (УРЛ Ссылка)

  • admin_url()
  • attachment_url_to_postid()
  • build_query()
  • comment_link()
  • content_url()
  • get_comments_link()
  • get_comments_pagenum_link()
  • get_edit_post_link()
  • get_edit_term_link()
  • get_home_url()
  • get_next_comments_link()
  • get_next_posts_page_link()
  • get_page_link()
  • get_post_embed_url()
  • get_post_permalink()
  • get_post_type_archive_link()
  • get_previous_posts_page_link()
  • get_privacy_policy_url()
  • get_rest_url()
  • get_search_link()
  • get_stylesheet_directory_uri()
  • get_stylesheet_uri()
  • get_theme_root_uri()
  • get_year_link()
  • includes_url()
  • network_admin_url()
  • network_home_url()
  • plugin_dir_url()
  • plugins_url()
  • site_url()
  • strip_fragment_from_url()
  • the_post_thumbnail_url()
  • url_to_postid()
  • wc_get_cart_url()
  • wp_extract_urls()
  • wp_get_attachment_image_url()
  • wp_get_upload_dir()
  • wp_make_link_relative()
  • wp_parse_url()
  • wp_registration_url()
  • wp_upload_dir()
  • wp_validate_redirect()

Опции сайта (настройки)

Ссылки (УРЛы)

  • edit_bookmark_link()
  • edit_comment_link()
  • edit_post_link()
  • edit_tag_link()
  • get_admin_url()
  • get_delete_post_link()
  • get_permalink()
  • get_search_query()
  • get_theme_file_uri()
  • the_permalink()
  • the_privacy_policy_link()

а что если на поддомен ссылка?
как тогда реализовать через home_url?
например на mega.example.com
когда основной example.com

Источник

Оцените статью