Checking valid URL and pulling title in PHP

Discussion in 'PHP' started by olddocks, Dec 17, 2007.

  1. #1
    I am after php code which does...

    1. Validate URL.
    2. Check URL if really exists
    3. Pull the <title> from the given URL

    how do i do this?
     
    olddocks, Dec 17, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    
    
    function fetch_title($url)
    {
        if (!preg_match('~^https?://~i', $url))
        {
            trigger_error('Invalid URL given in ' . __FUNCTION__, E_USER_NOTICE);
            return false;
        }
    
        if (!$content = @file_get_contents($url))
        {
            return false;
        }
        else if (!preg_match('~<title>(.*?)</title>~si', $content, $title))
        {
            return false;
        }
    
        return $title[1];
    }
    
    
    PHP:
     
    nico_swd, Dec 17, 2007 IP
  3. olddocks

    olddocks Notable Member

    Messages:
    3,275
    Likes Received:
    165
    Best Answers:
    0
    Trophy Points:
    215
    #3
    great code! thanks nico :)
     
    olddocks, Dec 17, 2007 IP