php get url path
parse_url
(PHP 4, PHP 5, PHP 7, PHP 8)
parse_url — Parse a URL and return its components
Description
This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial and invalid URLs are also accepted, parse_url() tries its best to parse them correctly.
Parameters
Return Values
Examples
Example #1 A parse_url() example
The above example will output:
Example #2 A parse_url() example with missing scheme
The above example will output:
Notes
This function may not give correct results for relative URLs.
This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP’s backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///. ) are allowed. For any other scheme this is invalid.
See Also
User Contributed Notes 33 notes
[If you haven’t yet] been able to find a simple conversion back to string from a parsed url, here’s an example:
Here is utf-8 compatible parse_url() replacement function based on «laszlo dot janszky at gmail dot com» work. Original incorrectly handled URLs with user:pass. Also made PHP 5.5 compatible (got rid of now deprecated regex /e modifier).
Here’s a good way to using parse_url () gets the youtube link.
This function I used in many works:
I was writing unit tests and needed to cause this function to kick out an error and return FALSE in order to test a specific execution path. If anyone else needs to force a failure, the following inputs will work:
There’s a quirk where this function will return the host as the «path» if there is a leading space.
I have coded a function which converts relative URL to absolute URL for a project of mine. Considering I could not find it elsewhere, I figured I would post it here.
The following function takes in 2 parameters, the first parameter is the URL you want to convert from relative to absolute, and the second parameter is a sample of the absolute URL.
Currently it does not resolve ‘../’ in the URL, only because I do not need it. Most webservers will resolve this for you. If you want it to resolve the ‘../’ in the path, it just takes minor modifications.
?>
OUTPUTS:
http :// user:pass@example.com:8080/path/to/index.html
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/img.gif
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/path/to/../img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/images/img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/path/to/../images/img.gif
Sorry if the above code is not your style, or if you see it as «messy» or you think there is a better way to do it. I removed as much of the white space as possible.
php get URL of current file directory
Might be an easy question for you, but I’m breaking my head over this one.
I have a php file that needs to know it’s current directory url to be able to link to something relative to itself.
For example, currently I know to get the current directory path instead of the url. When I use this I get the path:
But this would be my desired result:
Note that this is not the location of the current page. The page calls a file from «http://localhost:8888/dir1/dir2/dir3/myfile.php» And «myfile.php» has the script from above.
4 Answers 4
For example if the URL is http://localhost/
The output would be:
That’s enough to generate a relative URL.
In the case above that will give you /
Please note that echo getcwd(); is not what you want, based on your question. That gives you the location on the filesystem/server (not the URL) that your script is running from. The directory the script is located in on the servers filesystem, and the URL, are 2 completely different things.
There is also a function to parse URL’s built in to PHP: http://php.net/manual/en/function.parse-url.php
This is the code I’ll now be useing:
If your URL is like this: https://localhost.com/this/is/a/url
If you would like to get the full url, you can do something like:
В этой статье будет рассказано о том, как в языке программирования PHP получить адрес текущей страницы. Также вы узнаете о работе переменной $_SERVER.
Первое, о чём следует сказать, — зачем вообще получать ссылки (urls) в PHP? На практике варианты могут различаться. Представьте, что у нас для разных разделов применяется один и тот же шаблон. И возникает потребность в том, чтобы вывести (либо не вывести — зависит от ситуации) какой-нибудь специальный блок, причём в других разделах вывод этого блока не нужен.
В большинстве случаев мы пожелаем выполнить поставленную задачу по условию. То есть сделаем условие, в котором будем выполнять проверку того либо иного раздела. Можно сказать, что с точки зрения архитектуры данное решение не является оптимальным. Но на практике нам нередко достаются уже реализованные проекты, с которыми необходимо что-то решать с учётом уже имеющейся архитектуры.
Но давайте не будем много говорить, а лучше приступим к решению поставленной задачи — получению ссылки в PHP.
Получение ссылки текущей страницы в PHP
Идём дальше. Представьте, что у вас есть web-страница, имеющая следующий вид: http://localhost/php-lessons/url/?name=anna&city=Valencia. Тестирование в данном примере осуществляется на локальном сервере. Если надо тестировать код на реальном веб-сайте, доступном в интернете, достаточно вместо localhost прописать имя сайта (домен) — тот же otus.ru.
Что же мы увидим в подопытном url? Нас могут интересовать следующие данные: — адрес веб-страницы без GET-параметров; — URL с GET-параметрами; — непосредственно GET-параметры без текущей ссылки (адреса веб-страницы).
Лучше всего разобраться с каждым из случаев по отдельности — так будет гораздо понятнее.
Получение полного URL в PHP
Для получения полного URL вместе с имеющимися GET-параметрами, пригодится следующий код:
На втором этапе выполняется присоединение двоеточия и двух слэшев, имени домена и остальной части URL.
Итог выполнения кода будет следующим:
Если протокол получать не требуется, код на PHP можно немного сократить:
Смотрим на результат и видим, что протокол отсутствует:
Получение URL в PHP без GET-параметров
Иногда эти параметры, передаваемые в качестве части ссылки, нас не интересуют, то есть требуется получить адрес без них. Мы говорим о следующих параметрах: name=anna&city=Valencia.
В действительности их можно отсечь, используя функцию explode в PHP, разбивающую строку по разделителю. Не стоит объяснять, что ссылка представляет собой строку, а параметры GET начинают прописываться после «?». В результате вопросительный знак и станет разделителем, а функция explode сделает из строки массив с 2-мя элементами. Первый элемент станет содержать искомую ссылку без GET-параметров, так как эти самые параметры останутся во втором элементе.
Получение только параметров GET
С помощью этого кода получим:
PHP: building a URL path
I have a few strings to combine to build a full path. e.g.
String concatenation won’t do, that would omit the necessary forward slashes.
In Win32 I’d use PathCombine() or PathAppend(), which would handle adding any necessary slashes between strings, without doubling them up. In PHP, what should I use?
8 Answers 8
when it comes down to something like this I like to use a special function with unlimited parameters.
So that when I use the function I can do
hope this helps you, works really well for me especially within an Framework Environment.
to use with params you can append the url like so for simplicity.
Would produce: http://mysite.com/home?hello=world
not sure why you say string concat won’t do, because something like this is basically similar to a string concat. (untested semi-pseudo)
with string concat, we’d have to write a slightly longer block like so:
I usually go simple:
Either that or use a framework, and then use whatever route system it has.
There are a few considerations first.
This should work on all versions of PHP too.
Not my code, but a handy function which takes an absolute URL and a relative URL and combines the two to make a new absolute path.
The function has been modified to ignore an absolute URL passed as relative ( basically anything that includes a schema ).
I wrote this function for all cases to combine url parts with no duplicate slashes. It accepts many arguments or an array of parts. Some parts may be empty strings, that does not produce double slashes. It keeps starting and ending slashes if they are present.
Here is a check list from unit test. Left array is input and right part is result string.
It can be used as implodePath(‘aaa’, ‘bbb’) or implodePath([‘aaa’, ‘bbb’])
Not the answer you’re looking for? Browse other questions tagged php or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to generate absolute URL path to a script file?
This is almost same question as this
I need to get ABSOLUTE url to my script. For example, I have this structure
My application root would be in freegame_222/
but, how can I «build» absolute, not relative path to ajax.php? Result will be
These examples will return after url(«ajax.php»); is called
Is there a native function in PHP for it? If no, does anybody know about any custom one?
I want to call that page from another page, for example index.php
7 Answers 7
Similar to George Cummins’ answer, simply do something like such:
The parse_url() function might do what you are looking for:
Here’s a more complete example from the manual page:
The above example will output:
Not pertinent to the question, however it is worth mentioning that HTTP/HTTPS can be omitted as a result of port forwarding or reverse proxy. You can do something like this to overcome this:
Note: This is particularly useful on Amazon EC2 deployed under ELB with HTTPS.
There has been some incivility here which prevented @genesis to get what he needs.
Because I pretty much «need» the same, here is my (reformulated) question (and a potential answer).
Assumptions: Application can be installed pretty much anywhere, since it will be downloaded by someone from an open-source repository. So there is the need to automatically determine:
I have taken a look at how WordPress does this. Basically, WordPress requires that the URL pointing to the directory structure is hard-coded by the user (other applications do not). Then it extracts the directory path (for file inclusion) with
This looks rather neat, but, in reality, the problem is that if you’re «deep» in the directory hierarchy, it might be impossible to include the file that defines ABSPATH. What WordPress is constantly doing is to call those two lines and include the required configuration file after it made sure that it got a valid ABSPATH.
But other software seem to be much better organized. They automagically extract the correct URL to the directory where the webserver is pointing to; and they even-more-magically are able to find where all the include files are, no matter how deep in the subdirectory structure they’re located.
The best I could do is to emulate WordPress: ‘force’ the user to write the URL in the configuration file, and, on all levels and sublevels, start pretty much every file with
and attempt to include the global configuration file by guesswork (e.g. test if it’s at the same level, one level up, two levels up, and so forth. ).
This is extremely messy, but it seems that’s what some gold-class applications (like WordPress) are doing. Others seems so much more organized. How do they do it? I have no idea.