-4

I've working on a project and in this project i need to check the user input is a valid URL.

I've made a preg_match for all possible characters used on a URL. However, I'm trying to make it show an error if HTTP:// / HTTPS:// is not in front of the URL.

Here is what I've done.

if(preg_match('/[^0-9a-zA-Z.\-\/:?&=#%_]/', $url) || substr($url, 0, 7) != "http://" || substr($url, 0, 8) != "https://") {

But that doesn't work. It keeps giving me the an OK message. I'm not sure what I'm doing wrong here, I hope I can get some help!

The if statement will return true or false. So

    if(preg_match('/[^0-9a-zA-Z.\-\/:?&=#%_]/', $url) || substr($url, 0, 7) != "http://" || substr($url, 0, 8) != "https://") {
echo "true";
} else {
echo "false";
}

I just need to check if the url has entered a valid url. I don't need to verify it. Just need to check if it has HTTP:// or HTTPS:// and contains valid URL characters.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Dhamesh Makwana
  • 109
  • 1
  • 2
  • 14

4 Answers4

14

Instead of a regex, you could make things easy on yourself and use the URL filtering in filter_var:

if (filter_var($url, FILTER_VALIDATE_URL)) { ...
Peter Geer
  • 1,132
  • 1
  • 6
  • 11
  • 1
    On it own this does not answer the OP question, `filter_var('hxxpabc://example.com', FILTER_VALIDATE_URL)` is valid? – Lawrence Cherone Jun 21 '13 at 17:06
  • 2
    If `filter_var` produces a positive result you can inspect it with `parse_url`. This allows you to extract parts of the URL, like the scheme (http, https, hxxpabc). – Halcyon Jun 21 '13 at 17:09
7

Alternately you can do this without regex. Though you do also need to validate the url imagine http://">bla</a><script>alert('XSS');</script> as the value passed as there url

<?php
$url = 'http://example.com';

if(in_array(parse_url($url, PHP_URL_SCHEME),array('http','https'))){
    if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
        //valid url
    }else{
        //not valid url
    }
}else{
    //no http or https
}
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

You've not shown your complete relevant code. So, not sure, why it is not working for you but for url validation, you can check for a detailed discussion on the thread link below:

PHP validation/regex for URL

Community
  • 1
  • 1
Manish Jain
  • 829
  • 1
  • 8
  • 20
0

To validate user input with website url it is good to allow with or without scheme and with or without www, then in view add scheme to set as external url.

    $withWww = 'www.' . str_replace(array('www.'), '', $value);
    $withScheme = 'http://' . str_replace(array('http://', 'htttps://'), '', $withWww);
    $headers = @get_headers($withScheme);
    if (strpos($headers[0], '200') === false) {
        return false;
    }
Marcin Żurek
  • 145
  • 1
  • 3