Php получить хост url

$_SERVER

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server, therefore there is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. However, most of these variables are accounted for in the » CGI/1.1 specification, and are likely to be defined.

Note: When running PHP on the command line most of these entries will not be available or have any meaning.

In addition to the elements listed below, PHP will create additional elements with values from request headers. These entries will be named HTTP_ followed by the header name, capitalized and with underscores instead of hyphens. For example, the Accept-Language header would be available as $_SERVER[‘HTTP_ACCEPT_LANGUAGE’] .

Indices

‘ PHP_SELF ‘ The filename of the currently executing script, relative to the document root. For instance, $_SERVER[‘PHP_SELF’] in a script at the address http://example.com/foo/bar.php would be /foo/bar.php . The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name. ‘argv’ Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. ‘argc’ Contains the number of command line parameters passed to the script (if run on the command line). ‘ GATEWAY_INTERFACE ‘ What revision of the CGI specification the server is using; e.g. ‘CGI/1.1’ . ‘ SERVER_ADDR ‘ The IP address of the server under which the current script is executing. ‘ SERVER_NAME ‘ The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

Note: Under Apache 2, UseCanonicalName = On and ServerName must be set. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts.

‘ SERVER_SOFTWARE ‘ Server identification string, given in the headers when responding to requests. ‘ SERVER_PROTOCOL ‘ Name and revision of the information protocol via which the page was requested; e.g. ‘HTTP/1.0’ ; ‘ REQUEST_METHOD ‘ Which request method was used to access the page; e.g. ‘GET’ , ‘HEAD’ , ‘POST’ , ‘PUT’ .

Note:

PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD .

‘ REQUEST_TIME ‘ The timestamp of the start of the request. ‘ REQUEST_TIME_FLOAT ‘ The timestamp of the start of the request, with microsecond precision. ‘ QUERY_STRING ‘ The query string, if any, via which the page was accessed. ‘ DOCUMENT_ROOT ‘ The document root directory under which the current script is executing, as defined in the server’s configuration file. ‘ HTTPS ‘ Set to a non-empty value if the script was queried through the HTTPS protocol. ‘ REMOTE_ADDR ‘ The IP address from which the user is viewing the current page. ‘ REMOTE_HOST ‘ The Host name from which the user is viewing the current page. The reverse dns lookup is based on the REMOTE_ADDR of the user.

Note: The web server must be configured to create this variable. For example in Apache HostnameLookups On must be set inside httpd.conf for it to exist. See also gethostbyaddr() .

‘ REMOTE_PORT ‘ The port being used on the user’s machine to communicate with the web server. ‘ REMOTE_USER ‘ The authenticated user. ‘ REDIRECT_REMOTE_USER ‘ The authenticated user if the request is internally redirected. ‘ SCRIPT_FILENAME ‘

Читайте также:  Java browser is javascript

The absolute pathname of the currently executing script.

Note:

If a script is executed with the CLI, as a relative path, such as file.php or ../file.php , $_SERVER[‘SCRIPT_FILENAME’] will contain the relative path specified by the user.

‘ SERVER_ADMIN ‘ The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host. ‘ SERVER_PORT ‘ The port on the server machine being used by the web server for communication. For default setups, this will be ’80’ ; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

Note: Under Apache 2, UseCanonicalName = On , as well as UseCanonicalPhysicalPort = On must be set in order to get the physical (real) port, otherwise, this value can be spoofed, and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts.

‘ SERVER_SIGNATURE ‘ String containing the server version and virtual host name which are added to server-generated pages, if enabled. ‘ PATH_TRANSLATED ‘ Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Note: Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO .

‘ SCRIPT_NAME ‘ Contains the current script’s path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. ‘ REQUEST_URI ‘ The URI which was given in order to access this page; for instance, ‘ /index.html ‘. ‘ PHP_AUTH_DIGEST ‘ When doing Digest HTTP authentication this variable is set to the ‘Authorization’ header sent by the client (which you should then use to make the appropriate validation). ‘ PHP_AUTH_USER ‘ When doing HTTP authentication this variable is set to the username provided by the user. ‘ PHP_AUTH_PW ‘ When doing HTTP authentication this variable is set to the password provided by the user. ‘ AUTH_TYPE ‘ When doing HTTP authentication this variable is set to the authentication type. ‘ PATH_INFO ‘ Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URI http://www.example.com/php/path_info.php/some/stuff?foo=bar , then $_SERVER[‘PATH_INFO’] would contain /some/stuff . ‘ ORIG_PATH_INFO ‘ Original version of ‘ PATH_INFO ‘ before processed by PHP.

Читайте также:  Vim редактор для python

Examples

Example #1 $_SERVER example

Источник

Get Full URL & URL Parts In PHP (Simple Examples)

Welcome to a quick tutorial on how to get the full URL and URL parts in PHP. Need to get the path, base, domain, or query string from the URL? In Javascript, we can pretty much get all this information with just one line of code. But sadly in PHP, things are a little… backward.

  • To get the full URL in PHP – $full = (isset($_SERVER[«HTTPS»]) ? «https://» : «http://») . $_SERVER[«HTTP_HOST»] . $_SERVER[«REQUEST_URI»];
  • To remove the query string from the full URL – $full = strtok($full, «?»);

That should cover the basics, but if you need more specific “URL parts” – Read on for more examples!

TLDR – QUICK SLIDES

How To Get Full URL & URL Parts In PHP

TABLE OF CONTENTS

URL BASICS

All right, let us start with some “boring” basic URL parts. Yep, this stuff is important if you are new.

THE VARIOUS URL PARTS

  • Protocol – HTTP, HTTPS, FTP, WS, WSS, and whatever else.
  • Host – Better known as the “website address” to the non-technical folks.
  • Port – Usually left out. Commonly understood to be 80 for HTTP, 443 for HTTPS, and 21 for FTP.
  • Path – Beginners usually mistake this to be the “folder”, but it’s really not. I.E. The path can be virtual, not an actual physical folder.
  • File – Yes, the physical file name.
  • Query String – Extra information and parameters.

I know, it’s kind of ironic. The URL is supposed to be “easily understood” by humans, but there are so many parts to it.

GET FULL URL & URL PARTS

Now that you know the individual parts of a URL, let us now walk through how to obtain the full URL and the “common parts” using PHP.

1) URL PARTS IN PHP

2) GETTING THE FULL URL

 // (A4) THE PATH, FILE NAME, AND QUERY $url .= $_SERVER["REQUEST_URI"]; // (A5) INCLUDE QUERY STRING? if ($query===false) < $url = strtok($url, "?"); >// (A6) THE FULL URL return $url; > // (B) GET CURRENT URL echo getFullURL(true); // WITH QUERY echo getFullURL(); // WITHOUT QUERY

This is pretty much the “expanded version” of the introduction snippet, packaged into a function for your convenience.

3) COMMON URL PARTS

As for the “rest of the parts” that are not included in $_SERVER , we will need to do some mix-and-match on our own. Here are a few of the common ones.

PROTOCOL & HOST

// (A) PROTOCOL + DOMAIN $host = isset($_SERVER["HTTPS"]) ? "https://" : "http://" . $_SERVER["HTTP_HOST"] ; echo $host;

PATH ONLY

// (B) PATH ONLY $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); echo $path;

https://site.com/ path /file.php?p=123

FILENAME ONLY

// (C) FILENAME ONLY // USE BASENAME() TO GET THE FILE + STRIP QUERY STRING $file = basename($_SERVER["REQUEST_URI"], "?". $_SERVER["QUERY_STRING"]); echo $file;

https://site.com/path/ file.php ?p=123

PATH WITH FILENAME

// (D) PATH + FILENAME $filepath = strtok($_SERVER["REQUEST_URI"], "?"); echo $filepath;

https://site.com /path/file.php ?p=123

EXTRA) PARSE URL

For you guys who have a URL string from somewhere – You can use the parse_url() function to quickly get all the parts.

Читайте также:  Курсив с помощью CSS - "Нубекс"

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

HOW ABOUT THE HASH?

Want to get the hash section of the URL? For example, http://site.com/path/file.php #section . Sadly, it is nowhere to be found in $_SERVER . Your best bet is to use Javascript instead.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

PHP parse_url и её обратная функция

parse_url($url, $component) – разбирает URL-адрес на компоненты, возвращая их в виде массива. При разборе некорректных URL, функция может вернуть false .

Разбор URL

Структура URL адреса

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); print_r($parse);

Результат:

Array ( [scheme] => https [host] => snipp.ru [path] => /php/parse-url [query] => page=1&sort=1 [fragment] => sample )
$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; echo parse_url($url, PHP_URL_SCHEME); // https echo parse_url($url, PHP_URL_HOST); // snipp.ru echo parse_url($url, PHP_URL_PORT); // NULL echo parse_url($url, PHP_URL_USER); // NULL echo parse_url($url, PHP_URL_PASS); // NULL echo parse_url($url, PHP_URL_PATH); // /php/parse-url echo parse_url($url, PHP_URL_QUERY); // page=1&sort=1 echo parse_url($url, PHP_URL_FRAGMENT); // sample

Кстати, GET-параметры будут представлены строкой вида page=1&sort=1 , преобразовать ее в массив можно с помощью функции parse_str() :

parse_str('page=1&sort=1', $query); print_r($query);

Результат:

echo http_build_query($query); // page=1&sort=1

Обратный parse_url

function reverse_parse_url(array $parts) < $url = ''; if (!empty($parts['scheme'])) < $url .= $parts['scheme'] . ':'; >if (!empty($parts['user']) || !empty($parts['host'])) < $url .= '//'; >if (!empty($parts['user'])) < $url .= $parts['user']; >if (!empty($parts['pass'])) < $url .= ':' . $parts['pass']; >if (!empty($parts['user'])) < $url .= '@'; >if (!empty($parts['host'])) < $url .= $parts['host']; >if (!empty($parts['port'])) < $url .= ':' . $parts['port']; >if (!empty($parts['path'])) < $url .= $parts['path']; >if (!empty($parts['query'])) < if (is_array($parts['query'])) < $url .= '?' . http_build_query($parts['query']); >else < $url .= '?' . $parts['query']; >> if (!empty($parts['fragment'])) < $url .= '#' . $parts['fragment']; >return $url; >

Удаление из URL GET-параметров:

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); unset($parse['query']); echo reverse_parse_url($parse); // https://snipp.ru/php/parse-url#sample

Замена домена:

$url = 'https://snipp.ru/php/parse-url?page=1&sort=1#sample'; $parse = parse_url($url); $parse['host'] = 'example.com'; echo reverse_parse_url($parse); // https://example.com/php/parse-url?page=1&sort=1#sample

Источник

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