Get in touch:
01524 851 877
07718 896 553

Validating Url Strings In PHP

Posted on Sep 25 2008

I was writing a form a little while ago that requests a url from a user. Obviously it would be nice to validate the string the user input in some way. I am not a fan of writing a regex for something like this when I know that there are bound to be many examples of doing this knocking about already so to save time I once again headed over to google to look around.

I came across this link which has a nice little example of a regex to achieve a good validation.

Below is a copy and paste of building the regex string from that site with brief explanations of what each part achieves.

// SCHEME
$urlregex = "^(https?|ftp)\:\/\/";

// USER AND PASS (optional)
$urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";
// HOSTNAME OR IP
$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*";
// PORT (optional)
$urlregex .= "(\:[0-9]{2,5})?";
// PATH (optional)
$urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";// GET Query (optional)
$urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?";// ANCHOR (optional)
$urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?\$";

This builds a nice regex string which can be used with the eregi() function to validate a url string like so:

if (eregi($urlregex, $url))
{
echo "URL Valid";
}
else
{
echo "URL Invalid";
}

This regex will validate nearly all valid url’s and is handy to have knocking about.

Thanks to the original author, whoever that may be…..

Get Next Auto Increment Value

Posted on Sep 24 2008

Earlier today I had the need to try and discover the next auto increment value in a MySQL table. I haven’t needed to do this before so I headed over to google to have a look for how to accomplish it.

A lot of information I found said to use a ‘SELECT MAX…’. This would work fine as long as nothing gets deleted from the end of the database. I ended up finding a nice blog entry here that explains exactly how to do it. The following code snippet taken from the site above shows how to get the next value.

$tablename = "tablename";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus);

$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];

echo "next increment number: [$next_increment]";
?>

Quite a useful piece of info…