<?php

function url_exists( $url = NULL ) {
    if( empty( $url ) ){
        return FALSE;
    }

    $ch = curl_init( $url );

    // Set a timeout
    curl_setopt( $ch, CURLOPT_TIMEOUT, 5 );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 5 );

    // Set NOBODY to true to make a HEAD-type request
    curl_setopt( $ch, CURLOPT_NOBODY, true );
    // Allow follow redirects
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    // Receive the response as string, not output
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

    $data = curl_exec( $ch );

    // Get the response code
    $httpcode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
    // close connection
    curl_close( $ch );

    // Accept only answer 200 (Ok), 301 (permanent redirect) or 302 (temporary redirect)
    $accepted_response = array( 200, 301, 302 );
    if( in_array( $httpcode, $accepted_response ) ) {
        return TRUE;
    } else {
        return FALSE;
    }
}

function video_exists( $url ) {
    @$headers = get_headers( $url );

    $result = FALSE;

    if (is_array($headers) || is_object($headers)) {
        foreach ( $headers as $hdr ) {
            if ( preg_match( '/^HTTP\/\d\.\d\s+(403|404)/', $hdr ) ) {
                $result = TRUE; // Found 403 Error
            }
        }
    }

    if ( $result === TRUE ) {
        return FALSE; // Not exist video
    } else {
        return TRUE; // Exist video
    }
}

function secToDuration( $seconds ) {
    $minutes  = intval( $seconds/60 );
    $seconds = ( $seconds - ( $minutes * 60 ) );
    return $minutes . ' minutes ' . $seconds . ' seconds';
}

function bytes( $a ) {
    $unim = array("","K","M","G","T","P");
    $c = 0;
    while ($a>=1000) {
        $c++;
        $a = $a/1000;
    }
    return number_format( $a,( $c ? 2 : 0 ),",","." )." ".$unim[$c];
}
