Get last url php

abdullahbutt / gist:10253010

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

get last word from url after a slash in php
preg_match(«/[^\/]+$/», «http://www.mydomainname.com/m/groups/view/test», $matches);
$last_word = $matches[0]; // test
OR
Use basename with parse_url:
echo basename(parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH));
OR
You can use explode but you need to use / as delimiter:
$segments = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
Note that $_SERVER[‘REQUEST_URI’] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:
$_SERVER[‘REQUEST_URI_PATH’] = parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH);
And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:
$_SERVER[‘REQUEST_URI_PATH’] = parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH);
$segments = explode(‘/’, rtrim($_SERVER[‘REQUEST_URI_PATH’], ‘/’));
1 down vote
To do that you will need to use explode on your REQUEST_URI.I’ve made some simple function:
function getLast()
$requestUri = $_SERVER[‘REQUEST_URI’];
# Remove query string
$requestUri = trim(strstr($requestUri, ‘?’, true), ‘/’);
# Note that delimeter is ‘/’
$arr = explode(‘/’, $requestUri);
$count = count($arr);
return $arr[$count — 1];
>
echo getLast();
use preg*
if ( preg_match( «~/(.*?)$~msi», $_SERVER[ «REQUEST_URI» ], $vv ))
echo $vv[1];
else
echo «Nothing here»;
this was just idea of code. It can be rewriten in function.
PS. Generally i use mod_rewrite to handle this. ans process in php the $_GET variables. And this is good practice, IMHO

Источник

Get Last Part of URL PHP

I’m just wondering how I can extract the last part of a URL using PHP.

http://domain.com/artist/song/music-videos/song-title/9393903 

Now how can I extract the final part using PHP?

There is always the same number of variables in the URL, and the id is always at the end.

Php Solutions

Solution 1 — Php

The absolute simplest way to accomplish this, is with basename()

echo basename('http://domain.com/artist/song/music-videos/song-title/9393903'); 

Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.

Solution 2 — Php

Split it apart and get the last element:

$end = end(explode('/', $url)); # or: $end = array_slice(explode('/', $url), -1)[0]; 

Edit: To support apache-style-canonical URLs, rtrim is handy:

$end = end(explode('/', rtrim($url, '/'))); # or: $end = array_slice(explode('/', rtrim($url, '/')), -1)[0]; 

A different example which might me considered more readable is (Demo):

$path = parse_url($url, PHP_URL_PATH); $pathFragments = explode('/', $path); $end = end($pathFragments); 

This example also takes into account to only work on the path of the URL.

Yet another edit (years after), canonicalization and easy UTF-8 alternative use included (via PCRE regular expression in PHP):

 use function call_user_func as f; use UnexpectedValueException as e; $url = 'http://example.com/artist/song/music-videos/song-title/9393903'; $result = preg_match('(([^/]*)/*$)', $url, $m) ? $m[1] : f(function() use ($url) throw new e("pattern on '$url'");>) ; var_dump($result); # string(7) "9393903" 

Which is pretty rough but shows how to wrap this this within a preg_match call for finer-grained control via PCRE regular expression pattern. To add some sense to this bare-metal example, it should be wrapped inside a function of its’ own (which would also make the aliasing superfluous). Just presented this way for brevity.

Solution 3 — Php

You can use preg_match to match the part of the URL that you want.

In this case, since the pattern is easy, we’re looking for a forward slash ( \/ and we have to escape it since the forward slash denotes the beginning and end of the regular expression pattern), along with one or more digits ( \d+ ) at the very end of the string ( $ ). The parentheses around the \d+ are used for capturing the piece that we want: namely the end. We then assign the ending that we want ( $end ) to $matches[1] (not $matches[0] , since that is the same as $url (ie the entire string)).

$url='http://domain.com/artist/song/music-videos/song-title/9393903'; if(preg_match("/\/(\d+)$/",$url,$matches)) < $end=$matches[1]; > else < //Your URL didn't match. This may or may not be a bad thing. > 

Note: You may or may not want to add some more sophistication to this regular expression. For example, if you know that your URL strings will always start with http:// then the regex can become /^http:\/\/.*\/(\d+)$/ (where .* means zero or more characters (that aren’t the newline character)).

Solution 4 — Php

If you are looking for a robust version that can deal with any form of URLs, this should do nicely:

 $url = "http://foobar.com/foo/bar/1?baz=qux#fragment/foo"; $lastSegment = basename(parse_url($url, PHP_URL_PATH)); 

Solution 5 — Php

$id = strrchr($url,"/"); $id = substr($id,1,strlen($id)); 

Источник

How to Get URI Segment in PHP

The URL segments are used for many purposes in the web application. You can parse URL segments easily using the parse_url() function in PHP. Here we’ll provide the example code to get URI segments and the last URL segment using PHP.

Get URI Segments in PHP

Use the following code to get URL segments of the current URL. It returns all the segments of the current URL as an array.

$uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

Usage:
When the current URL is http://www.example.com/codex/foo/bar .

echo $uriSegments[1]; //returns codex
echo $uriSegments[2]; //returns foo
echo $uriSegments[3]; //returns bar

Get Last URL Segment

If you want to get last URI segment, use array_pop() function in PHP.

$lastUriSegment = array_pop($uriSegments);
echo
$lastUriSegment; //returns bar

Источник

Получить последнюю часть URL-адреса PHP

Мне просто интересно, как я могу извлечь последнюю часть URL-адреса с помощью PHP.

http://domain.com/artist/song/music-videos/song-title/9393903 

Теперь, как я могу извлечь финальную часть с помощью PHP?

В URL всегда есть такое же количество переменных, и идентификатор всегда находится в конце.

Вы можете использовать preg_match , чтобы соответствовать той части URL, которую вы хотите.

В этом случае, поскольку шаблон прост, мы ищем косую черту ( \/ , и нам нужно избегать его, поскольку передняя косая черта обозначает начало и конец шаблона регулярного выражения), а также один или больше цифр ( \d+ ) в самом конце строки ( $ ). Скобки вокруг \d+ используются для захвата фрагмента, который мы хотим: а именно, конца. Затем мы назначаем окончание, которое мы хотим ( $end ), на $matches[1] (не $matches[0] , так как это то же самое, что $url (т.е. Вся строка)).

$url='http://domain.com/artist/song/music-videos/song-title/9393903'; if(preg_match("/\/(\d+)$/",$url,$matches)) < $end=$matches[1]; >else < //Your URL didn't match. This may or may not be a bad thing. >

Примечание.. Вы можете или не захотите добавить некоторую сложность в это регулярное выражение. Например, если вы знаете, что строки вашего URL будут всегда начинаться с http:// , тогда регулярное выражение может стать /^http:\/\/.*\/(\d+)$/ (где .* означает ноль или более символов (это не символ новой строки )).

Разделите его и получите последний элемент:

$end = end(explode('/', $url)); # or: $end = array_slice(explode('/', $url), -1)[0]; 

Изменить: для поддержки URL-адресов, rtrim стиле apache, rtrim удобен:

$end = end(explode('/', rtrim($url, '/'))); # or: $end = array_slice(explode('/', rtrim($url, '/')), -1)[0]; 

Другой пример, который может считаться более читаемым, – это (Демо):

$path = parse_url($url, PHP_URL_PATH); $pathFragments = explode('/', $path); $end = end($pathFragments); 

Этот пример также учитывает только работу по пути URL.

Еще одно редактирование(), канонизация включало:

) ; var_dump($result); # string(7) "9393903" 

Это довольно грубо, но показывает, как это сделать при вызове preg_match для более тонкого управления с помощью шаблона регулярного выражения PCRE. Чтобы добавить некоторый смысл в этот простой пример, он должен быть обернут внутри функции его собственной (что также сделает излишним псевдоним). Просто представил этот путь для краткости.

Абсолютным простейшим способом добиться этого является basename()

echo basename('http://domain.com/artist/song/music-videos/song-title/9393903'); 

Конечно, если в конце есть строка запроса, она будет включена в возвращаемое значение, и в этом случае принятый ответ является лучшим решением.

Если вы ищете надежную версию, которая может иметь дело с любой формой URL-адресов, это должно сделать красиво:

$id = strrchr($url,"/"); $id = substr($id,1,strlen($id)); 
$urlarray=explode("/",$url); $end=$urlarray[count($urlarray)-1]; 

Одно из самых элегантных решений было здесь Получить символы после последнего/в URL

$id = substr($url, strrpos($url, '/') + 1); 

strrpos получает позицию последнего вхождения косой черты; зиЬзЬг возвращает все после этой позиции.

Один вкладыш: $page_path = end(explode(‘/’, trim($_SERVER[‘REQUEST_URI’], ‘/’)));

Получить URI, обрезать косые черты, преобразовать в массив, захватить последнюю часть

это облегчит работу, чтобы получить последнюю часть требуемого URL

$url="http://domain.com/artist/song/music-videos/song-title/9393903"; $requred_string= substr(strrchr($url, "/"), 1); 

вы получите строку после первого “/” справа.

$end = preg_replace( '%^(.+)/%', '', $url ); // if( ! $end ) no match. 

Это просто удаляет все до последней косой черты, включая его.

$url = "http://www.yoursite/one/two/three/drink"; echo $end = end((explode('/', $url))); 

Выход: напиток

$mylink = $_SERVER['PHP_SELF']; $link_array = explode('/',$mylink); echo $lastpart = end($link_array); 

Источник

How to get the previous page URL in PHP?

There are many times when you need to know the previous page URL after a redirect. Maybe you’re wondering where your traffic is coming from, or if a particular campaign is driving users to your site. In any case, knowing the previous page URL is essential for understanding how users are interacting with your site.

Fortunately, it’s easy to get this information using some simple code. Keep reading to learn how!

How to get the previous page URL using PHP?

$_SERVER[‘HTTP_REFERER’] always contains the referrer or referring page URL. When you want to get the previous page’s URL, use this code:

However, you should know that someone can change the $_SERVER[‘HTTP_REFERER’] header at any time. This will not tell you if they have been to a website before.

Sometimes you may notice a warning like

Notice: Undefined index: HTTP_REFERER

Some user agents don’t set HTTP_REFERER, and others let you change HTTP_REFERER. So it’s not a reliable piece of information. So, always check if it is set or not by using isset() .

How to spoof HTTP_REFERER?

It’s very easy to spoof as well as there are many ways to grab the header from the user. This is a very common problem that I have come across in almost every single web application which requires the referer check to be enabled.

Referer spoofing is a simple process and can often be done by any individual who has little knowledge of the HTTP protocol. Let’s look at how it works:

How to get the previous page URL after redirect in PHP?

The best way to get the previous URL is with the PHP session. The value for $_SESSION[‘previous_location’] will be set as the previous page URL after a redirect.

Now set the session on your homepage like this:

You can access this session variable from any page like this:

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment Cancel reply

Enjoying the articles? I would appreciate a coffee to help me keep writing and coding!

Источник

Читайте также:  Xml and xpath in java
Оцените статью