Parsing url and routing issues - php

www.foo.com/Base/index.php/controller/method/
This is my url, I need to get only "controller/method" part out of it - is there any elegant way to achieve this?
parse_url($url, PHP_URL_PATH)
This would be great, but it returns the whole "Base/index.php/controller/method" part.

$url = "http://www.foo.com/Base/index.php/controller/method/";
$path = parse_url($url, PHP_URL_PATH);
$parts = explode("/", $path);
$index = array_search("index.php", $parts);
$controller = $parts[$index+1];
$method = $parts[$index+2];
You did not provide any additional information about url format. But as example, you may use regular expressions with preg_match():
$url = "http://www.foo.com/Base/index.php/controller/method/";
preg_match ("/^.*Base\/index.php\/([a-zA-Z0-9_]*)\/([a-zA-Z0-9_]*)\/?/", $url, $data);
$controller = $data[1];
$method = $data[2];

Related

Get values from url with PHP

I'm trying to get values from a url using php. With basename I only get the last part but i need the part before that as well.
This is the domain: http://mydomain.nl/first/second/third/
$url = parse_url($entry['source_url']);
$urlFragments = explode('/', $url);
$second = $urlFragments[0];
$third = $urlFragments[1];
I need to use part second and part third.
#idka-80 try this,
$url_components = parse_url($url);
echo "<pre>";
print_r(array_filter(explode("/",$url_components['path'])));
This script can help you
First of all, to make it simple I remove http:// part and then explode it with / and get a different part of the data which is separated by /
<?php
$url = "http://mydomain.nl/first/second/third/";
$url = str_replace("http://", "", $url);
$urlFragments = explode('/', $url);
$yourDomain = $urlFragments[0];
$first = $urlFragments[1];
$second = $urlFragments[2];
$third = $urlFragments[3];
echo $first . ", " . $second . ", " . $third;
As you can tell from the fatal error, you're making a wrong assumption about how parse_url() works:
Fatal error: Uncaught TypeError: explode(): Argument #2 ($string) must be of type string, array given
If you only want a specific fragment, you need to tell which one:
$url = parse_url($entry['source_url'], PHP_URL_PATH);
// ^ Also give it a better name, such as `$path`
You also possibly want to discard leading and trailing slashes:
$urlFragments = explode('/', trim($url, '/'));
Hopefully this will help
$url = 'http://mydomain.nl/first/second/third/';
$urlFragments = explode('/', $url);
echo $second = $urlFragments[4];
echo $third = $urlFragments[5];

Extract particular point of URL in PHP

I'm trying to get a very specific part of a URL using PHP so that I can use it as a variable later on.
The URL I have is:
https://forums.mydomain.com/index.php?/clubs/11-Default-Club
The particular part I am trying to extract is the 11 part between the /clubs/ and -Default-Club bits.
I was wondering what the best way to do this was. I've seen examples on here that use a regex-esque parser but I can't wrap my head around it for this particular instance.
Thanks
Edit; this is what I've tried so far using an explode query, but it seems to give me all sorts of elements which are not present in the URL above:
$url = $_SERVER['REQUEST_URI'];
$url = explode('/', $url);
$url = array_filter($url);
$url = array_merge($url, array());
Which returns:
Array ( [0] => index.php?app=core&module=system&controller=widgets&do=getBlock&blockID=plugin_9_bimBlankWidget_dqtr03ssz&pageApp=core&pageModule=clubs&pageController=view&pageArea=header&orientation=horizontal&csrfKey=8e19769b95c733b05439755827a98ac8 )
If you expect that the string with dashes (11-Default-Club) will be always at the end you can try this:
$url = $_SERVER['REQUEST_URI'];
$urlParts = explode('/', $url);
$string = end($urlParts);
$stringParts = explode('-', $string);
$theNumber = $stringParts[0]; // this will be 11
I'd rather be explicit:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$query = parse_url($url, PHP_URL_QUERY);
$pattern = '#^/clubs/(\d+)[a-zA-Z-]+$#';
$digits = preg_match($pattern, $query, $matches)
? $matches[1]
: null;
var_dump($digits);
Output:
string(2) "11"
If this URL structure is fix for all URLs in your site and you only want to get the integer/number/digit part of the URL:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$int = (int) filter_var($url, FILTER_SANITIZE_NUMBER_INT);
echo $int;
If this url structure is fix for all URLs in your site then below is best way to get your value.
<?php
$url = "https://forums.mydomain.com/index.php?/clubs/11-Default-Club";
$url = explode('/', $url);
$url = array_filter($url);
$end = end($url);
$end_parts = explode('-',$end);
echo $end_parts[0];
Output:
11

$_SERVER['QUERY_STRING'] become empty if the url change

I have a problem to resolve. The first url allow me to display information or not on the website. It work fine.
I identify Account&Edit for example and make action.
http://localhost/boutique/index.php?Account&Edit
$_SERVER['QUERY_STRING'] = Account&Edit
If I rewrite the url, the system does not work and Account&Edit become Account/Edit
http://localhost/boutique/index.php/Account/Edit
$_SERVER['QUERY_STRING'] = '';
How to resolve this element when this element Account&Edit change ?
$_SERVER['QUERY_STRING'] is empty is this case.
Thank you.
I make that to solve the problem.
public function getUrlwithoutSEFU() {
if (empty($_SERVER['QUERY_STRING'])) {
$url = $_SERVER['REQUEST_URI'];
$replace = str_replace('index.php', '', $url);
$replace = str_replace(CLICSHOPPING::getConfig('http_path'), '', $replace);
$replace = substr($replace, 1);
$replace = str_replace('/', '&', $replace);
$url_string = $replace;
} else {
$url_string = $_SERVER['QUERY_STRING'];
}
return $url_string;
}
Take a look at RFC3875: The Common Gateway Interface (CGI) Version 1.1
When you have no ? i nthe request URL, then there's no query string.
Looking at REQUEST_URI would make sense.
This is how request urls are split into environment vars:
# QUERY_STRING
# ↓↓↓↓↓↓↓↓↓↓↓↓
http://localhost/boutique/index.php?Account&Edit
Or the part after the (directly invoked) php script. (This may vary depending on SAPI or be impacted by rewrite rules).
# PATH_INFO
# ↓↓↓↓↓↓↓↓↓↓↓↓↓
http://localhost/boutique/index.php/Account/Edit
Or the full path:
# REQUEST_URI
# ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
http://localhost/boutique/index.php/Account/Edit
Notably you would have to split it up yourself then. Also may show up as REDIRECT_REQUEST_URI for example in the $_SERVER array with some setups.
Solution
public function getUrlwithoutSEFU() {
if (empty($_SERVER['QUERY_STRING'])) {
$url = $_SERVER['REQUEST_URI'];
$replace = str_replace('index.php', '', $url);
$replace = str_replace(CLICSHOPPING::getConfig('http_path'), '', $replace);
$replace = substr($replace, 1);
$replace = str_replace('/', '&', $replace);
$url_string = $replace;
} else {
$url_string = $_SERVER['QUERY_STRING'];
}
return $url_string;
}

PHP Get end string on url between / and /

I need to get the last string content of the url between / and /
For example:
http://mydomain.com/get_this/
or
http://mydomain.com/lists/get_this/
I need to get where get_this is in the url.
trim() removes the trailing slash, strrpos() finds the last occurrence of / (after it's trimmed), and substr() gets all content after the last occurrence of /.
$url = trim($url, '/');
echo substr($url, strrpos($url, '/')+1);
View output
Even better, you can just use basename(), like hakre suggested:
echo basename($url);
View output
Assuming there always is a trailing slash:
$parts = explode('/', $url);
$get_this = $parts[count($parts)-2]; // -2 since there will be an empty array element due to the trailing slash
If not:
$url = trim($url, '/'); // If there is a trailing slash in this URL instance get rid of it so we're always sure the last part is where we expect it
$parts = explode('/', $url);
$get_this = $parts[count($parts)-1];
Something like this should work.
<?php
$subject = "http://mydomain.com/lists/get_this/";
$pattern = '/\/([^\/]*)\/$/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
Just use parse_url() and explode():
<?php
$url = "http://mydomain.com/lists/get_this/";
$path = parse_url($url, PHP_URL_PATH);
$path_array = array_filter(explode('/', $path));
$last_path = $path_array[count($path_array) - 1];
echo $last_path;
?>
You can try this:
preg_match("/http:\/\/([a-z0-9\.]+)\/(.+)\/(.*)\/?/", $url, $matches);
print_r($matches);

How to trim down a URL using regex in PHP?

I am struggling to finish this regex code in PHP. I want to trim down the following url which is held in variable $text so that it goes from:
http://www.site.net/showthread.php?tid=324&pid=...
to:
showthread.php?tid=324
Thank you kindly!
Why use a regex? The parse_url method should give you all you want: http://php.net/manual/en/function.parse-url.php
Edit: working example
$someurl = 'http://www.site.net/showthread.php?tid=324&pid=...';
$urlParts = parse_url($someurl, PHP_URL_PATH | PHP_URL_QUERY);
$params = parse_str($urlParts['query']);
unset($params['pid']);
$queryString = http_build_query($params);
$newUrl = $urlParts['path'] . '?' . $queryString;
Since $urlParts['path'] start with a / and you didn't want that, you could even use
$newUrl = substr($newUrl, 1);
and be done :) Does that help at all?
This should do it:
$url = 'http://www.site.net/showthread.php?tid=324&pid=...';
$pattern = "/showthread.php\?tid=[0-9]+/";
if (preg_match($pattern, $url, $match))
print_r($match);

Categories