Php http base url

Как получить базовый URL с PHP?

Я использую XAMPP в Windows Vista. В моем развитии у меня есть http://127.0.0.1/test_website/ .

Как получить http://127.0.0.1/test_website/ с PHP?

Я пробовал что-то подобное, но никто из них не работал.

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

Solutions Collecting From Web of «Как получить базовый URL с PHP?»

Подробнее о предопределенной переменной $_SERVER

Если вы планируете использовать https, вы можете использовать это:

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 

В этом ответе убедитесь, что вы правильно настроили Apache, чтобы вы могли безопасно зависеть от SERVER_NAME .

 ServerName example.com UseCanonicalName on  

ПРИМЕЧАНИЕ . Если вы HTTP_HOST ключа HTTP_HOST (который содержит пользовательский ввод), вам все равно придется выполнить некоторую очистку, удалить пробелы, запятые, возврат каретки, что-либо, что не является допустимым символом для домена. Например, проверьте функции php builtin parse_url .

Функция, настроенная для выполнения без предупреждений:

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"].'?').'/'; 

Я думаю, что $_SERVER имеет информацию, которую вы ищете. Это может быть что-то вроде этого:

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

Здесь вы можете увидеть соответствующую документацию PHP.

$modifyUrl = parse_url($url); print_r($modifyUrl) 

Его простое в использовании
Вывод :

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

но извините, мой английский не достаточно хорош,

сначала получите исходный код сайта с помощью этого простого кода.

Я тестировал этот код локальным сервером и публичным, и результат хороший.

 // 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/ 

используйте функцию home_base_url на index.php вашего сайта и определите его

и затем вы можете использовать эту функцию для загрузки скрипта, css и контента с помощью URL-адреса, например

и если этот скрипт работает нормально,!

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

URL-адрес выглядит следующим образом: http://domain.com/folder/

Следующий код уменьшит проблему, чтобы проверить протокол. $ _SERVER [‘APP_URL’] отобразит доменное имя с протоколом

$ _SERVER [‘APP_URL’] вернет протокол: // domain (например: – http: // localhost )

$ _SERVER [‘REQUEST_URI’] для оставшихся частей URL-адреса, например / directory / subdirectory / something / else

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

HTTP: // локальный / каталог / подкаталог / чтото / другое

Попробуй это. Меня устраивает.

/*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]); > > 

Добавьте следующий код на страницу:

 $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; > ?> 

Теперь вы можете получить текущий URL страницы с помощью строки:

Иногда требуется получить только имя страницы. В следующем примере показано, как это сделать:

 echo "The current page name is ".curPageName(); ?> 

Отредактировано в ответе @ user3832931, чтобы включить порт сервера.

для создания URL-адресов, таких как « https: // localhost: 8000 / folder / »

$base_url="http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER["REQUEST_URI"].'?').'/'; 
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://"; $url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI']; 
$some_variable = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1); 

и вы получаете что-то вроде

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

Вот один, который я только что собрал, который работает для меня. Он вернет массив с 2 элементами. Первый элемент – это все до? а второй – массив, содержащий все переменные строки запроса в ассоциативном массиве.

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

Примечание. Это расширение ответа, представленного maček выше. (Кредит, в котором должен быть предоставлен кредит).

Попробуйте использовать: $_SERVER[‘SERVER_NAME’];

Я использовал его, чтобы повторить базовый url моего сайта, чтобы связать мой css.

/assets/css/your-stylesheet.css" rel="stylesheet" type="text/css"> 

У меня был тот же вопрос, что и у ОП, но, возможно, другое требование. Я создал эту функцию …

/** * 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; > 

… которые, кстати, я использую, чтобы помочь создать абсолютные URL-адреса, которые должны использоваться для перенаправления.

  • Symfony2 – как я могу настроить пользовательские заголовки?
  • Почему считается, что плохая практика использует «глобальную» ссылку внутри функций?
  • Черты против интерфейсов
  • Как отправить несколько как массив в PHP?
  • Снимок экрана с текущей страницы с помощью PHP
  • Гео-поиск (расстояние) в PHP / MySQL (производительность)
  • В PHP что означает | = mean, that is pipe равно (не восклицание)
  • Использование Md5 для хэша паролей в компоненте Auth Cakephp 2.x
  • PHPMailer, AddStringAttachment и схема URI данных
  • Автоматическое получение широты и долготы с помощью php, API
  • Шифрование паролей
  • Как считать и группировать в yii2
  • Эффективность php array_intersect ()
  • PHP Опубликовать данные с помощью Fsockopen
  • Что означает = и означает в PHP?

Источник

Find Base URL in PHP

Find Base URL in PHP

This article will introduce a few methods to find the base URL of an application in PHP.

Use the $_SERVER Superglobal Variable to Find the Base URL in PHP

The $_SERVER superglobal variable in PHP contains the information about the server and the execution environment.

The term superglobal variable signifies that the variable can be accessed in every scope in the program. The variable is a predefined array and contains a wide range of indices.

We can use the various indices to find paths, headers, and script locations. A few examples of the available indices used in the $_SERVER array are SERVER_NAME , SERVER_ADDR , HTTP_HOST , REMOTE_HOST , etc.

The web servers provide these indices. So, the availability of the indices varies according to the webserver. An example of using the $_SERVER array is shown below.

php echo $_SERVER['SERVER_NAME']; ?> 

In the example above, the server used is localhost. The $_SERVER[‘SERVER_NAME] array returns the server hostname under which the current script is executing.

We can use the $_SERVER array to find the base URL of the application in PHP. The SERVER_NAME and REQUEST_URI indices are useful for finding the base URL.

The REQUEST_URI index returns the Unifrom Resource Identifier (URI) of the current web page.

For example, create a variable $server and store $_SERVER[‘SERVER_NAME’] in it. Likewise, store $_SERVER[‘REQUEST_URI’] in the $uri variable.

Next, concatenate the string http:// with the variables $server and $uri and print them using the print function.

As a result, we can see the base URL of the current application. The example below shows the path of the current application as it is run in the localhost .

$server = $_SERVER['SERVER_NAME']; $uri = $_SERVER['REQUEST_URI']; print "http://" .$server. $uri; 

We can also get the hostname using the HTTP_HOST index in the $_SERVER array. The index HTTP_HOST returns the host header of the current request in the application.

The difference between it and the SERVER_NAME index is that HTTP_HOST retrieves the header from the client request while SERVER_NAME retrieves the information defined at the server configuration.

The SERVER_NAME index is more reliable than the HTTP_HOST as the value is returned from the server and cannot be modified. The example of the HTTP_HOST index to get the base URL of the application is shown below.

$host = $_SERVER['HTTP_HOST']; $uri = $_SERVER['REQUEST_URI']; print "http://" .$host. $uri; 

Above is how we can find the base URL of an application in PHP.

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

Источник

How to Get Base URL from Full URL String in PHP

Base URL is used to create internal web page links dynamically in the website. You can get the base URL from the full URL string using PHP. The parse_url() function helps to parse components from URL in PHP. The base URL can be retrieved from a string using PHP parse_url() function.

The following code snippet shows how to get base URL from URL string with PHP.

  • PHP_URL_SCHEME – This component returns URL scheme (http/https).
  • PHP_URL_HOST – This componenet returns host name (example.com/www.example.com).
$url = 'https://www.codexworld.com/how-to/get-current-url-php/'; 
$url = parse_url($url, PHP_URL_SCHEME).'://'.parse_url($url, PHP_URL_HOST);
$base_url = trim($url, '/');

Источник

Читайте также:  Kotlin gradle utf 8
Оцените статью