Tutorial Get File Last Updated Date

by in , 0

/*
 * @param string $file Filepath
 * @param string $format dateformat
 * @link http://www.php.net/manual/de/function.date.php
 * @link http://www.php.net/manual/de/function.filemtime.php
 * @return string|bool Date or Boolean
 */

function getFiledate($file, $format) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
               $fileDate = filemtime($filePath);
               if ($fileDate) {
                       $fileDate = date("$format",$fileDate);
                       return $fileDate;
               }
               return false;
       }
       return false;
}

PHP Get FeedBurner Subscriber Count with cURL

by in , 0

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://feedburner.google.com/api/awareness/1.0/GetFeedData?id=7qkrmib4r9rscbplq5qgadiiq4');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
$content = curl_exec($ch);
$subscribers = get_match('/circulation="(.*)"/isU',$content);
curl_close($ch);

The $subscribers variable will then be your subscriber count, for echoing out (or whatever). You'll need to replace the ID at the end of the second line with your feed's ID (find it). You'll also need to have the Awareness feature of FeedBurner enabled.

Tutorial Get Current Page URL

by in , 0

function getUrl() {
  $url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
  $url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
  $url .= $_SERVER["REQUEST_URI"];
  return $url;
}

Tutorial Get Current File Name

by in , 0

<?php
    $pageName = basename($_SERVER['PHP_SELF']);
?>

Potential use:

<body id="body_<?php echo $pageName; ?>">

Append ID to body to do different CSS styles on different pages.

Tutorial Get All-Time Number of MySQL Queries

by in , 0

<?php
       $handle=@mysql_connect("localhost","root","");

       if (!$handle)
       {
               die("No connection to database");
       }

       echo 'Total number of all-time mysql-queries: '.getTotalNumberOfMySQLQuerys();


       //Returns integer-value of the total number of alltime mysql-calls that have been made
       function getTotalNumberOfMySQLQuerys()
       {
               //global mysql-status containing the number of querys has been renamed in newer versions of mysql
               $mysqlVersion=getMysqlVersion();

               //contact helper-function to receive the mysql-version
               if ($mysqlVersion()>=50002)
               {
                       $sql="SHOW GLOBAL STATUS LIKE 'Questions'";
               }
               else
               {
                       $sql="SHOW STATUS LIKE 'Questions'";
               }

               $result=@mysql_query( $sql );
               $row=@mysql_fetch_array( $result );
               return $row['Value'];
       }

       //helper function is needed to detect the exact mysql-version
       function getMysqlVersion()
       {
               $sql = 'SELECT VERSION() AS versionsinfo';
               $result = @mysql_query('SELECT VERSION() AS versionsinfo');
               $version = @mysql_result( $result, 0, "versionsinfo" );
               $match = explode('.',$version);
               return sprintf('%d%02d%02d',$match[0],$match[1],intval($match[2]));
       }
?>

Because the name of the global mysql-status-variable containing the number of queries changed in later versions of mysql, a helper-function is needed to detect the exact version of mysql you're running.

Tutorial Generate Expiring Amazon S3 Link

by in , 0

You don't have to make files on Amazon S3 public (they aren't by default). But you can generate special keys to allow access to private files. These keys are passed through the URL and can be made to expire.

<?php 

  if(!function_exists('el_crypto_hmacSHA1')){
    /**
    * Calculate the HMAC SHA1 hash of a string.
    *
    * @param string $key The key to hash against
    * @param string $data The data to hash
    * @param int $blocksize Optional blocksize
    * @return string HMAC SHA1
    */
    function el_crypto_hmacSHA1($key, $data, $blocksize = 64) {
        if (strlen($key) > $blocksize) $key = pack('H*', sha1($key));
        $key = str_pad($key, $blocksize, chr(0x00));
        $ipad = str_repeat(chr(0x36), $blocksize);
        $opad = str_repeat(chr(0x5c), $blocksize);
        $hmac = pack( 'H*', sha1(
        ($key ^ $opad) . pack( 'H*', sha1(
          ($key ^ $ipad) . $data
        ))
      ));
        return base64_encode($hmac);
    }
  }

  if(!function_exists('el_s3_getTemporaryLink')){
    /**
    * Create temporary URLs to your protected Amazon S3 files.
    *
    * @param string $accessKey Your Amazon S3 access key
    * @param string $secretKey Your Amazon S3 secret key
    * @param string $bucket The bucket (bucket.s3.amazonaws.com)
    * @param string $path The target file path
    * @param int $expires In minutes
    * @return string Temporary Amazon S3 URL
    * @see http://awsdocs.s3.amazonaws.com/S3/20060301/s3-dg-20060301.pdf
    */
    
    function el_s3_getTemporaryLink($accessKey, $secretKey, $bucket, $path, $expires = 5) {
      // Calculate expiry time
      $expires = time() + intval(floatval($expires) * 60);
      // Fix the path; encode and sanitize
      $path = str_replace('%2F', '/', rawurlencode($path = ltrim($path, '/')));
      // Path for signature starts with the bucket
      $signpath = '/'. $bucket .'/'. $path;
      // S3 friendly string to sign
      $signsz = implode("\n", $pieces = array('GET', null, null, $expires, $signpath));
      // Calculate the hash
      $signature = el_crypto_hmacSHA1($secretKey, $signsz);
      // Glue the URL ...
      $url = sprintf('http://%s.s3.amazonaws.com/%s', $bucket, $path);
      // ... to the query string ...
      $qs = http_build_query($pieces = array(
        'AWSAccessKeyId' => $accessKey,
        'Expires' => $expires,
        'Signature' => $signature,
      ));
      // ... and return the URL!
      return $url.'?'.$qs;
    }
  }

?>

Usage

<?php echo el_s3_getTemporaryLink('your-access-key', 'your-secret-key', 'bucket-name', '/path/to/file.mov'); ?>

Reference URL

Tutorial Generate CSV from Array

by in , 0

function generateCsv($data, $delimiter = ',', $enclosure = '"') {
       $handle = fopen('php://temp', 'r+');
       foreach ($data as $line) {
               fputcsv($handle, $line, $delimiter, $enclosure);
       }
       rewind($handle);
       while (!feof($handle)) {
               $contents .= fread($handle, 8192);
       }
       fclose($handle);
       return $contents;
}

Usage

$data = array(
       array(1, 2, 4),
       array('test string', 'test, literal, comma', 'test literal "quotes"'),
);

echo generateCsv($data);
// outputs:
// 1,2,4
// "test string","test, literal, comma","test literal""quote"""