Zend - The PHP Company




HTTP

Add Code


URL sanity checker and rebuilder  

Type: code fragment
Added by: julian7
Entered: 05/01/2001
Last modified: 01/12/2000
Rating: - (fewer than 3 votes)
Views: 5324
Gets an URL and converts it to standard format (eg. ftp.somewhere.org - ftp://ftp.somewhere.org/). It can distinguish ftp scheme, when the hostname starts with 'ftp'.


<?php
function urlcheck($url) {
    
$charset "abcdefghijklmnopqrstuvwxyz"
        
."ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        
."0123456789"
        
."./%_-~:@?#&=";
    if (!isset(
$url) || !is_string($url)
     || !(
$len strlen($url)) || strspn($url$charset)!=$len)
        return 
false;
    
$URL parse_url($url);
    if (
strlen($URL["port"]))
        
$port ":".$URL["port"];
    else
        
$port "";
    if (!
strlen($URL["user"]))
        
$user "";
    elseif (
strlen($URL["pass"]))
        
$user $URL["user"].":".$URL["pass"]."@";
    else
        
$user $URL["user"]."@";
    if (
strlen($URL["host"]))
        
$host $URL["host"];
    else {
        
$host $URL["path"];
        
$URL["path"] = "";
    }
    if (
strlen($URL["path"]))
        
$path $URL["path"];
    else
        
$path "/";
    if (
strlen($URL["scheme"]))
        
$scheme $URL["scheme"];
    elseif (
substr($host03) == "ftp")
        
$scheme "ftp";
    else
        
$scheme "http";
    
$query $URL["query"].$URL["fragment"];
    return 
"$scheme://$user$host$port$path$query";
}
?>


Usage Example


$url1 = "www.example.com";
$url2 = "ftp.nonexistent.dom/bad path";
if (!($url = urlcheck($url1))) echo "Bad url $url1<br>n";
else echo "$url1 -> $url<br>n";
if (!($url = urlcheck($url2))) echo "Bad url $url2<br>n";
else echo "$url2 -> $url<br>n";


Rate This Script





Search



This Category All Categories