Australian Made and Owned

Extract GET Variables from URL String to Array - PHP Function

While making the YouTube Music in MySpace tool, I coudln’t find a function that reads an input URL then makes an array with the GET variable names and values. I needed this to get the video id from the YouTube video URL - so I made it, and now I’m sharing it.

So in my case, the function is fed a YouTube URL and returns the video id variable (v) - So an example:
Input: http://au.youtube.com/watch?v=le860Jd-FqI&feature=related
Output:
$output['v'] = “le860Jd-FqI”
$output['feature'] = “related”

And so witout further ado, here’s the actual code:

function getVariableFromUrl($url) {		//we need to see if this URL is passing any GET variables

 	$variablesStart = strpos($url, "?") + 1;

if (!$variablesStart) {

 		// no variables!

 		return(false);

 	}

//before we extract the variables, we need to remove any anchors

$variablesEnd = strpos($url,"#",$variablesStart);

if ($variablesEnd) {

 		$getVariables = substr($url, $variablesStart, $variablesEnd - $variablesStart);

 	} else {

 		$getVariables = substr($url, $variablesStart);

 	}

//next, we split the URL into an arrays containing variable name and value pairs (ie. "variable=value")

 	$variableArray = explode("&", $getVariables);

//we will iterate through each of the array pairs (ie. "variable=value")

 	foreach ($variableArray as $arraySet) {

$nameAndValue = explode("=", $arraySet);

//using the above examples, $nameAndValue[0] would be "variable" and $nameAndValue[1] would be "value"

 		$output[$nameAndValue[0]] = $nameAndValue[1];

}

return($output);

}


Did you like this post?
Email Send to a friend Add to Technorati Favorites

AddThis Social Bookmark Button
AddThis Feed Button

Leave a comment

6 Comments

  1. Piero

    could you put your function on a php example, please?? you can email me at piero@chullotv.com

    March 18, 2008 @ 5:07 pm

  2. AngusI

    Could you not simply have used the extract() function?

    April 7, 2008 @ 12:28 am

  3. Craig

    Thank you. Took me ages to find this. Nowhere else has a method like this that I could find.

    May 7, 2009 @ 8:09 am

  4. Leonardo

    Hi…
    Where do you insert the Youtube Video URL.

    June 22, 2009 @ 11:07 pm

  5. Tim

    The function takes one argument, $url. That’s where the URL goes.

    you could use something like this:

    $url = $_GET['url'];
    $url_variables = getVariableFromUrl[$url];

    You will have a 2d array of the get variables from that URL.

    July 5, 2009 @ 1:13 am

  6. pmp

    Excellent script! Thank you for making it, it saved me a lot of time after screwing with the the parse_url function.

    September 16, 2009 @ 1:58 am

RSS feed for comments on this post. TrackBack URL