...

View Full Version : Checking for http:// in urls ?



jeddi
01-27-2012, 01:26 PM
Hi

I have used the this code to ensure that I get a vaild
url ( or I use "none" value )


if(!filter_var($Db_return, FILTER_VALIDATE_URL)) {
$Db_return = "none";
} // end if


Now I just want to make sure that there is an http://
in place so that the re-direct will work.



if( $return == "none"){
$return_path="thankyou.php";
} // endif
else {
if( substr($return, 0, 7) != "http://" || substr($return, 0, 8) != "https://") {
$return = "http://".$return;
} // endif
else {
$return_path = $return;
} // end else
} // end else

header("Location: $return_path");


Is this a good way to deal with checking for the re-direct ?
Or is there another built-in function I should use ?


Thanks


.

Fou-Lu
01-27-2012, 01:48 PM
You can use parse_url. If http[s] is omitted there will be no value for the returned array's 'scheme' index. So then you can just check


$sURL = $return;
if (false !== ($aURL = parse_url($return))
{
if (!isset($aURL['scheme']))
{
$sURL = 'http://' . $sURL;
}
}

If you have pecl installed, there is also an http_build_url, so you can just append the 'scheme' to the $aURL and then build it.

kbluhm
01-27-2012, 03:03 PM
Some more solutions:


// recommended
if ( 0 !== stripos( $return, 'http://' ) )
{
$return = 'http://' . $return;
}

// will also work
if ( 'http://' != substr( $return, 0, 7 ) )
{
$return = 'http://' . $return;
}

The use of stripos() ensures case-insensitivity... should the URL begin with HTTP://, etc.

jeddi
01-27-2012, 03:06 PM
That certainly looks neater than my effort :cool:


Just thinking ...

Because of the "not equal" should ...


if( substr($return, 0, 7) != "http://" || substr($return, 0, 8) != "https://") {

really be ...


if( substr($return, 0, 7) != "http://" && substr($return, 0, 8) != "https://") {

I get confused with negatives :o


.

kbluhm
01-27-2012, 03:16 PM
You could use a regular expression to match both http:// and https:// without having to use multiple conditions:


if ( ! preg_match( '~^https?\://~i', $return ) )
{
$return = 'http://' . $return;
}

~ are delimiters
^ binds the match to the beginning of the string
? makes he previous character optional (matchs both http and https)
\ escapes the colon because it is a special character in PCRE
i makes the match case-insensitive

jmj001
01-27-2012, 04:01 PM
That certainly looks neater than my effort :cool:


Just thinking ...

Because of the "not equal" should ...


if( substr($return, 0, 7) != "http://" || substr($return, 0, 8) != "https://") {

really be ...


if( substr($return, 0, 7) != "http://" && substr($return, 0, 8) != "https://") {

I get confused with negatives :o


.

it should && because || will always be true



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum