parse_url

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

parse_url

Post by SidewinderX »

I have a form where a user is suppose to enter his site URL. Just out of habit I always type the http:// in front of all URL's. However it has come to my attention that not all users are as habitual as I am. :roll:

So I created a little code that checks to see if the http is on the URL, if it is'nt, it will concatenate the http:// with the URL the user entered. I figured parse_url() would be a function to use and this is the code I came up with:

Code: Select all

<?php
$site = "www.google.com";
$site_array = parse_url($site);

if($site_array['scheme'] == "") {
	$site = "http://".$site_array['path'];
}

echo $site;
?>
Now if the http:// is present on the $site string, http://www.google.com is $site_array['host'] - if the http:// is not present [ie. the code above] http://www.google.com is defined as $site_array['path']. Why?
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

A lot of the parsing functions in PHP are expecting a certain format, and when they don't get that format, they may end up giving unexpected results.

Code: Select all

if(!preg_match('&^[A-Za-z]{3,}://&', $url)) $url = 'http://' . $url;
You could limit this to '*tp://' transfer protocols if you want.
Post Reply