4

I have a comment system that allows auto linking of url. I am using cakephp but the solution is more just PHP. here is what is happening.

if the user enters fully qualified url with http:// or https:// everything is fine. but if they enter www.scoobydoobydoo.com it turns into http://cool-domain.com/www.scoobydoobydoo.com. basically cakephp understands that http|https is an external url so it works with http|https not otherwise.

My idea was to do some kind of str stuff on the url and get it to insert the http if not present. unfortunately whatever i try only makes it worse. I am noob :) any help / pointer is appreciated.

thanks

EDIT: posting solution snippet. may not be the best but thanks to answer at least I have something.

<?php
        $proto_scheme = parse_url($webAddress,PHP_URL_SCHEME);
    if((!stristr($proto_scheme,'http')) || (!stristr($proto_scheme,'http'))){
        $webAddress = 'http://'.$webAddress;
    }
?>
Tobias
  • 7,238
  • 10
  • 46
  • 77
Abhishek Dujari
  • 2,343
  • 33
  • 43

4 Answers4

10
$url = "blahblah.com";
// to clarify, this shouldn't be === false, but rather !== 0
if (0 !== strpos($url, 'http://') && 0 !== strpos($url, 'https://')) {
   $url = "http://{$url}";
}
Michael McTiernan
  • 5,153
  • 2
  • 25
  • 16
5

Try the parse_url function: http://php.net/manual/en/function.parse-url.php

I think this will help you.

Tom Marthenal
  • 3,066
  • 3
  • 32
  • 47
Tobias
  • 7,238
  • 10
  • 46
  • 77
  • ah i am using that in the same page to get domain name.. let me try it.. like i said -> noob edit: yes this might work with PHP_URLSCHEME. thanks for the quick reply – Abhishek Dujari Mar 22 '11 at 07:44
  • 1
    Just benchmarked this against manually checking for presence with `strpos()` in my example. I was surprised to find out that they're essentially the same speed, but `parse_url` is waaaay more useful. I'll have to remember this. – Michael McTiernan Mar 22 '11 at 07:51
1

I've had a similar issue, so I created the following php function:

    function format_url($url)
{
    if(!$url) return null;
    $parsed_url = parse_url($url);
    $schema     = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : 'http://';
    $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
    $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
    return "$schema$host$path";
}

if you format the following: format_url('abcde.com'), the result will be http://abcde.com.

Rich R
  • 367
  • 4
  • 15
0

Here is the regex: https://stackoverflow.com/a/2762083/4374834

p.s. @Vangel, Michael McTiernan's answer is correct, so please, learn your PHP before you say, that something might fail :)

Community
  • 1
  • 1
Lucifer
  • 480
  • 3
  • 12