-3

Possible Duplicate:
Add http:// prefix to URL when missing

I'm using this code like this:

<?php echo $_GET['i']; ?>

myweb.com/sample.php?i=http://sample.com

But I want to make sure it always has http:// just in case this is provide myweb.com/sample.php?i=sample.com

How can I make this code <?php echo $_GET['i']; ?> make sure always adds the http:// in case is missing?

Community
  • 1
  • 1
MrAztek
  • 7
  • 1

4 Answers4

0

You can check, your $_GET['i'] and accept only with http:

For example:

'http://' contains 7 chars + smallest url 'w.xx' contains 4 chars

So, minimal lenght of your $_GET[i] is 11 chars

if(!empty($_GET['i']))
{

    $len = strlen($_GET['i']);
    if($len > 10 and  substr($_GET['i'], 0, 7) === 'http://')
    {     
        [... some of your code ?]
    }
    else if ($len > 3)
    {

        //force add http://
        $_GET['i'] = 'http://'.$_GET['i'];
     }

     unset($len);
}
else
{
    $_GET['i'] = 'No url?';
}

// <-- Place for your echo
Jan Czarny
  • 916
  • 1
  • 11
  • 29
  • You are not properly checking whether the url is valid. You should implement check for one '.' (dot) and valid `top level domain`. But if this echo is meant to be used in some company intranet, then only hostname can be used to link som webpage `host/1` (just like `localhost/index.php`) – Buksy Dec 19 '12 at 09:28
  • yes and this script is not safe vs XSS :) if this $_GET is used for secure connection. But this question is about, how add http. Not how secure z $_GET['i'] before XSS attack, valid domain lenght, accepted chars.. and other – Jan Czarny Dec 19 '12 at 09:35
0

Use this way:

<?php
    if (strpos("http://", $_GET['i']) !== 0)
        $_GET['i'] = "http://" . $_GET['i'];
?>

Or as an echo statement:

echo (strpos("http://", $_GET['i']) !== 0) ? "http://" . $_GET['i'] : $_GET['i'];
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

if you are generating the above mentioned http url dynamically into your query string, use urlencode or rawurlencode functions inside php to concatenate the query string to your url and then accept in request using http get ($_GET['i']).

Hope it works for you.

Saif Mulla
  • 26
  • 2
0

Use stristr() function.

$url = stristr($_GET['i'],'http://');
if($url != '')

Then string contains 'http'.

sjkon
  • 633
  • 2
  • 10
  • 24