Jump to content

Validating a URL in a form


Kemik

Recommended Posts

Hello all,

 

I've been reading a PHP book called "PHP and MySQL for Dynamic Websites (2nd Edit)" and it gives me a way to validate URLs however the method the author give isn't very good as the user is forced to enter the URL in a manner:

 

http://yourdomain.com

 

Obviously someone's personal url can be much different to this, with users adding www. before the domain, different tlds, sub domains, directories, etc.

 

Does anyone have a good example?

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/58554-validating-a-url-in-a-form/
Share on other sites

Thanks. The book was using eregi but as I said, it was pretty restrictive with the rules he was using.

 

Would this sound about right then?

 

<?php 
function validateURL($url) {
    $domain = "([[:alpha:]][-[:alnum:]]*[[:alnum:]])
(\.[[:alpha:]][-[:alnum:]]*[[:alpha:]])+";
    $dir = "(/[[:alpha:]][-[:alnum:]]*[[:alnum:]])*";
    $page = "(/[[:alpha:]][-[:alnum:]]*\.[[:alpha:]]{3,5})?";
    $getstring = "(\?([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+)
(&([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+))*)?";
    $pattern = "^".$domain.$dir.$page.$getstring."$";
    return eregi($pattern, $url);
} ?>

<?php
$url = $_POST['curl'];

// Check for a website URL.

if  validateURL($url) {
$curl = escape_data($url);
} else {
$curl = FALSE;
echo '<p><font color="red">Please enter a valid clan website address!</font></p>';
}

For some reason this isn't working. I get "Please enter a valid clan website address!" when I enter http://www.domain.co.uk

 

	
<?php
function validateURL($url) {
    $domain = "([[:alpha:]][-[:alnum:]]*[[:alnum:]])
(\.[[:alpha:]][-[:alnum:]]*[[:alpha:]])+";
    $dir = "(/[[:alpha:]][-[:alnum:]]*[[:alnum:]])*";
    $page = "(/[[:alpha:]][-[:alnum:]]*\.[[:alpha:]]{3,5})?";
    $getstring = "(\?([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+)
(&([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+))*)?";
    $pattern = "^".$domain.$dir.$page.$getstring."$";
    return eregi($pattern, $url);
}

// Check for a website URL.
if  (validateURL($_POST['curl'])) {
        $curl = escape_data($_POST['curl']);
} else {
        $curl = FALSE;
echo '<p><font color="red">Please enter a valid clan website address!</font></p>';
}?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.