I am just wondering what the best way of extracting "parameters" from an URL would be, using PHP.
If I got the URL:
http://example.com/user/100
How can I get the user id (100) using PHP?
To be thorough, you'll want to start with parse_url().
$parts=parse_url("http://example.com/user/100");
That will give you an array with a handful of keys. The one you are looking for is path.
Split the path on / and take the last one.
$path_parts=explode('/', $parts['path']);
Your ID is now in $path_parts[count($path_parts)-1].
You can use parse_url(), i.e.:
$parts = parse_url("http://x.com/user/100");
$path_parts= explode('/', $parts[path]);
$user = $path_parts[2];
echo $user;
# 100
parse_url()
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 notmeant to validate the given URL, it only breaks it
up into the above listed parts. Partial URLs are also
accepted, parse_url() tries its best to parse them correctly.
$url = "http://example.com/user/100";
$parts = Explode('/', $url);
$id = $parts[count($parts) - 1];
I know this is an old thread but I think the following is a better answer:
basename(dirname(__FILE__))
Related
I have an array of URLs. The URLs look similar to:
https://maps.googleapis.com/maps/api/place/details/json?placeid=$place_id&key=myAPIkey
The $place_id is a variable that changes in every single url.
I want to be able to select just this part of the url.
So when I loop through the URLs, I want it to extract that part, of the URL I am using, and assign it to a variable ($place) that I can use in my code. I have looked at strpos() and / or substr(), but I don't know how I would use them since the $place_id changes every time. I think the length of $place_id is always the same, but I am not 100% certain so a solution that worked for different lengths would be preferable.
Alternatively, I am already have the multiple $place_ids in an array. I am generating the array of URLs by using
foreach ($place_ids as $place_id) {
array_push(
$urls,
"https://maps.googleapis.com/maps/api/place/details/json?placeid=$place_id&key=myAPIkey"
);
}
I am then using
foreach ($urls as $url){}
to loop through this array. If there was a way I could check to make sure the value of $place_id coincided with the value of the URL either through some sort of check or by using their position in the array that would work too.
I'm sorry if any of this is incorrect and if there are any questions I can answer or ways for me to improve my question I'd be happy to.
Since you're dealing with URLs here, you'll probably want to use PHP's built-in helpers, parse_url() and parse_str().
For example, you can separate the GET parameters with parse_url and then extract each argument into an array with parse_str:
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=<arg1>&key=<arg2>';
$args = [];
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $args);
// args => ["placeid" => "<arg1>", "key" => "<arg2>"]
A regular expression will do
$match = array();
$url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=346758236546&key=myAPIkey";
preg_match('/[?&]placeid=([^&]+)(?:$|.*)/', $url, $match);
var_dump($match[1]); // string(12) "346758236546"
I have got a large array of lets say 500 urls, now using array_unique I can remove any duplicate values. However I am wanting to remove any duplicate values where the domain is the same while keeping the original domain (so only removing duplicates so this value is now unique).
I have been using the following however this only removes duplicate values:
$directurls = array_unique($directurls);
I have been playing around with the following to get the domain but am wondering how I can check the entire array for other parse_url domains in the array:
foreach($directurls as $url) {
$parse = parse_url($url);
print $parse['host']; //the domain name I just need to find a way to check this and remove it
}
I imagine I will need to use some form of loop perhaps where I can get the current host and check all other hosts in the array. If duplicates remove all duplicates and keep the current value. Maybe something like this could work am just testing it now:
foreach($directurls as $url) {
$parse = parse_url($url);
if (in_array($parse['host'], $directurls)) {
//just looking for a way to remove while keeping unique
}
}
If anyone has any suggestions or recommendations on other ways to go about this I would be very thankful.
Let me know if I need to explain a bit more.
You could avoid having to loop through the URLs by using array_map() with a callback function.Grab the domain using parse_url(), and create a new array with just the domains. Now, you can simply create a new array with the URLs as keys and domains as values and just call array_unique() to get the unique items. Now, to get just the URLs into a new array, you can use array_keys():
$domains = array_map(function($d) {
$parts = parse_url($d); // or: parse_url($d)['host'] if PHP > 5.4
return $parts['host'];
}, $directurls);
$result = array_keys(array_unique(array_combine($directurls, $domains)));
Demo!
I can't find a solution for this problem. I have this URL http://examplesite.com/?skill-type=new and I want to get the very last word after the = sign, using PHP only. "skill-type" stays the same all the time Thanks in advance :)
This snippet should do:
$url = 'http://examplesite.com/?skill-type=new';
$skillType = explode('&', parse_url($url, PHP_URL_QUERY))['skill-type'];
Check parse_url for more details.
If you meant that the request comes in to that particular url, just use $_REQUEST['skill-type'] to retrieve the value.
Considering you already have the URL in a variable, let's say
$url = 'http://examplesite.com/?skill-type=new;
One possible way (certainly there are others) would be:
$urlArray = explode('=',$url);
$last = $urlArray[sizeof($urlArray)-1];
Note:
only applicable if you don't know how the URL comes, if you do, consider on using $_GET
Use the PHP $_GET Global Variable
$skill_type = $_GET['skill-type'];
PHP will automatically parse GET variables for you. To access the value of the skill-type variable, you need only use $_GET['skill-type']. For instance:
echo $_GET['skill-type'];
Will display
new
Generate your url by $_SERVER variable and then split it like this
$url = "http://examplesite.com/?skill-type=new";
$array = explode("=", $url);
$last_word = $array[1];
Use substr (url, posstr (url,'=')+1) or if this is the page being loaded $_GET ['skill-type']
I was wondering how I could remove a certain part of a url using PHP.
This is the exact url in questions:
http://www.mysite.com/link/go/370768/
I'm looking to remove the number ID into a variable.
Any help would be great, Thanks!
There are many (many!) ways of extracting a number from a string. Here's an example which assumes the URL starts with the format like http://www.mysite.com/link/go/<ID> and extracts the ID.
$url = 'http://www.mysite.com/link/go/370768/';
sscanf($url, 'http://www.mysite.com/link/go/%d', $id);
var_dump($id); // int(370768)
Use explode()
print_r(explode("/", $url));
You could use mod_rewrite inside of your .htaccess to internally rewrite this URL to something more friendly for PHP (convert /link/go/370768/ into ?link=370768, for example).
I suspect that you are using some kind of framework. There are two ways to check the $_GET variables:
print_r($_GET);
or check the manual of the manual of the framework and see how the GET/POST is passed internally, for example in CakePHP you have all parameters save internally in your controller you can access them like that:
$this->params['product_id'] or $this->params['pass']
There is another solution which is not very reliable and professional but might work:
$path = parse_url($url, PHP_URL_PATH);
$vars = explode('/', $path);
echo $vars[2];
$vars should contain array like this:
array (
0 => link
1 => go
2 => 370768
)
I have back_url given to me from the outside. I need to generate a hash and to make redirect to this back_url with this param: header("Location: $back_url?hash=123sdf"). But the problem is that I don't know the format of back_url.
It may be www.example.com and I do header("Location: $back_url/?hash=123sdf") sj that's fine.
It maybe www.example.com/?param=value and if I do header("Location: $back_url/?hash=123sdf") it's wrong, because it would be www.example.com/?param=value/?hash=123asd.
And so on. The question is: what's the universal way to pass params to back_url ignoring its format?
A complex but very clean way is
Use parse_url() to extract the query string (if any) from the URL into an array
Add hash to the resulting array: $params["hash"] = "1234";
Use http_build_query() to glue the parameters back into a query string
Take all the components returned by parse_url() and glue them back into a full URL
one thing to note is that this dissects the URL into it components and glues it back together, so it's likely it won't work with URLs that are broken in the first place.
Have you tried using http://php.net/manual/en/function.parse-url.php ?
If you have the PECL HTTP extension, use http_build_url:
$url = '...';
$hash = '...';
$new_url = http_build_url($url, array('hash' => $hash), HTTP_URL_JOIN_QUERY);
If you don't have http_build_url, you can use parse_url to find the different parts if a URL. Then it's just a matter of pasting them together. Here's a solution in the manual which can be tailored for your needs.
Well, you would need to detect if $back_url has other query parameters (or GET variables) and append your hash using ?hash=123asd if it hadn't, or using &hash=123asd if indeed it had query parameters.
If you know that $back_url is a full url like http://whatever.com/blah/blah (the important part being http://whatever.com, you can use parse_url to get all components, and then continue with Pekka's answer. If your $back_url doesn't begin with http://..., then prepend the right value (I assume http://$_SERVER['host'] and, again, continue with Pekka's answer.
Wrote this function:
private function addUrlParam(array $params, $url){
$parsed = parse_url($url);
if(!isset($parsed['query']))
{
$slash = '';
if(substr($url, -1) !== '/')
$slash = '/';
$start_with = $slash.'?';
}
else
$start_with = '&';
$scheme = '';
if(!isset($parsed['scheme']))
$scheme = 'http://';
$query = http_build_query($params);
return $scheme.$url.$start_with.$query;
}
Looks like it's perfect for me. Thanks everyone.