Jun
9
2013

Output images with fallback and defined variables

/**
 * Function to output clean images with sizes defined
 * Checks for absolute OR relative paths and determines if the file exists
 * Example with local file (Same technique for remote files):
 * <?php image( 'assets/images/crowd4.png', true, 'Local File Alt tag', 'magic-class bigger' ); ?>
 *
 * @access public
 * @param string url to image (Required)
 * @param bool specify if the size should be calculated
 * @param string image alt text (Optional)
 * @param string class (Optional)
 * @param fallback image url (Optional)
 * @return string image in HTML tags
 */
function image( $image, $calculate_size = true, $alt = '', $class = '', $default = '' )
{
    //We'll start out assuming the image doesn't exist
    //until proven otherwise
    $exists = false;
    
    //Then we check to see if we're handling a local
    //or remote one
    if( preg_match( "/(http|https)/", $image ) )
    {
        //It's remote, and CURL is pretty fast
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $image );
        curl_setopt( $ch, CURLOPT_NOBODY, 1 );
        curl_setopt( $ch, CURLOPT_FAILONERROR, 1 );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        
        //And it WAS remote, and it DOES exist
        if( curl_exec( $ch ) !== FALSE )
        {
            $exists = true;
        }
        curl_close($ch);
    }
    //Alright, it's a local file, so check it
    elseif( file_exists( $image ) )
    {
        //And again, it DOES exist
        $exists = true;
    }
    
    //Since there are multiple params, we have to start with nothing
    $output = '';
    if( $exists )
    {
        //Put together the base, this is not optional
        $output .= '<img src="'.$image.'"';
        
        //Sometimes, we don't want to specify a size     
        if( $calculate_size )
        {
            //But here we did, so we'll get it added
            list( $width, $height ) = getimagesize( $image );
            $output .= ' height="'.$height.'" width="'.$width.'"';   
        }
        
        //Alt tags, recommended- frequently missing
        if( !empty( $alt ) )
        {
            $output .= ' alt="'.$alt.'"';
        }
        
        //And the never ending classes
        if( !empty( $class ) )
        {
            $output .= ' class="'.$class.'"';
        }
        
        //Close it
        $output .= ' />';
        
        //Echo it
        echo $output;
    }
    
    //Alright, so the file didn't exist
    //But we DO have a fallback, so we'll hit it
    elseif( !$exists && !empty( $default ) )
    {
        $output .= '<img src="'.$default.'" />';
        echo $output;
    }
    
    //And here, we're empty.  Null.
    else
    {
        return false;
    }
}

Leave a comment