Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php parse_url reverse -- parsed url

Tags:

php

parse-url

Is there a way to reverse the url from a parsed url?

$url = 'http://www.domain.com/dir/index.php?query=blabla#more_bla'; $parse = parse_url($url); print_r($parse); /* array(  'scheme'=>'http://',  etc.... ) */ $revere = reverse_url($parse); // probably does not exist but u get the point  echo $reverse; //outputs:// "http://www.domain.com/dir/index.php?query=blabla#more_bla" 

Or if there is a way validate a url that is missing part of its recommended urls e.g

www.mydomain.com

mydomain.com

should all return http://www.mydomain.com or with correct sub domain

like image 784
Val Avatar asked Dec 04 '10 17:12

Val


2 Answers

These are the two functions I use for decomposing and rebuilding URLs:

function http_parse_query($query) {     $parameters = array();     $queryParts = explode('&', $query);     foreach ($queryParts as $queryPart) {         $keyValue = explode('=', $queryPart, 2);         $parameters[$keyValue[0]] = $keyValue[1];     }     return $parameters; }  function build_url(array $parts) {     return (isset($parts['scheme']) ? "{$parts['scheme']}:" : '') .          ((isset($parts['user']) || isset($parts['host'])) ? '//' : '') .          (isset($parts['user']) ? "{$parts['user']}" : '') .          (isset($parts['pass']) ? ":{$parts['pass']}" : '') .          (isset($parts['user']) ? '@' : '') .          (isset($parts['host']) ? "{$parts['host']}" : '') .          (isset($parts['port']) ? ":{$parts['port']}" : '') .          (isset($parts['path']) ? "{$parts['path']}" : '') .          (isset($parts['query']) ? "?{$parts['query']}" : '') .          (isset($parts['fragment']) ? "#{$parts['fragment']}" : ''); }  // Example $parts = parse_url($url);  if (isset($parts['query'])) {     $parameters = http_parse_query($parts['query']);     foreach ($parameters as $key => $value) {         $parameters[$key] = $value; // do stuff with $value     }     $parts['query'] = http_build_query($parameters); }  $url = build_url($parts); 
like image 187
NobleUplift Avatar answered Sep 29 '22 08:09

NobleUplift


You should be able to do

http_build_url($parse) 

NOTE: http_build_url is only available by installing pecl_http.

According to the docs it's designed specifically to handle the output from parse_url. Both functions handle anchors, query params, etc so there are no "other properties not mentioned on the $url".

To add http:// when it's missing, use a basic check before parsing it:

if (strpos($url, "http://") != 0)     $url = "http://$url"; 
like image 28
Brad Mace Avatar answered Sep 29 '22 08:09

Brad Mace