CSS-TricksPHP Snippets Feed | CSS-Tricks https://css-tricks.com Tips, Tricks, and Techniques on using Cascading Style Sheets. Tue, 21 May 2024 20:43:44 +0000 hourly 1 https://wordpress.org/?v=6.5.2 https://i0.wp.com/css-tricks.com/wp-content/uploads/2021/07/star.png?fit=32%2C32&ssl=1 PHP Snippets Feed | CSS-Tricks https://css-tricks.com 32 32 45537868 Test if String Starts With Certain Characters in PHP https://css-tricks.com/snippets/php/test-if-string-starts-with-certain-characters-in-php/ https://css-tricks.com/snippets/php/test-if-string-starts-with-certain-characters-in-php/#comments Sun, 02 Feb 2020 20:57:18 +0000 Chris Coyier https://css-tricks.com/?page_id=303093 We can test if a certain string is the exact start of another string:

<?php 
  
function startsWith($string, $startString) { 
  $len = strlen($startString); 
  return (substr($string, 0, $len) === $startString); 
} 

// usage
echo startsWith("cat", "c"); // true
echo startsWith("dog", "x"); // 
…]]>
We can test if a certain string is the exact start of another string:

<?php 
  
function startsWith($string, $startString) { 
  $len = strlen($startString); 
  return (substr($string, 0, $len) === $startString); 
} 

// usage
echo startsWith("cat", "c"); // true
echo startsWith("dog", "x"); // false

?> 

Testing the position in the string, making sure it’s at 0, works too:

function startsWith($string, $startString) {
  return strpos($string, $startString) === 0;
}
(more…)]]>
https://css-tricks.com/snippets/php/test-if-string-starts-with-certain-characters-in-php/feed/ 2 303093
HTTP or HTTPS https://css-tricks.com/snippets/php/http-or-https/ https://css-tricks.com/snippets/php/http-or-https/#comments Fri, 07 Sep 2012 23:11:37 +0000 Chris Coyier http://css-tricks.com/?page_id=18098 if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) { // HTTPS } else { // HTTP }…]]> if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) { // HTTPS } else { // HTTP } ]]> https://css-tricks.com/snippets/php/http-or-https/feed/ 2 18098 Get Width/Height of Image https://css-tricks.com/snippets/php/get-widthheight-of-image/ https://css-tricks.com/snippets/php/get-widthheight-of-image/#comments Sat, 18 Aug 2012 17:19:22 +0000 Chris Coyier http://css-tricks.com/?page_id=17780 If all you have for an image is the URL, you can still find the dimensions:

<?php

  list($width, $height, $type, $attr) = getimagesize("url/to/image.jpg");

  echo "Image width " . $width;
  echo "Image height " . $height;
  echo "Image type " . 
…]]>
If all you have for an image is the URL, you can still find the dimensions:

<?php

  list($width, $height, $type, $attr) = getimagesize("url/to/image.jpg");

  echo "Image width " . $width;
  echo "Image height " . $height;
  echo "Image type " . $type;
  echo "Attribute " . $attr;

?>
]]>
https://css-tricks.com/snippets/php/get-widthheight-of-image/feed/ 2 17780
Import CSV into MySQL https://css-tricks.com/snippets/php/import-csv-into-mysql/ https://css-tricks.com/snippets/php/import-csv-into-mysql/#comments Sun, 05 Aug 2012 14:51:53 +0000 Chris Coyier http://css-tricks.com/?page_id=17655 <?php $databasehost = "localhost"; $databasename = "test"; $databasetable = "sample"; $databaseusername ="test"; $databasepassword = ""; $fieldseparator = ","; $lineseparator = "\n"; $csvfile = "filename.csv"; /********************************/ /* Would you like to add an ampty field at the beginning of these records? …]]> <?php $databasehost = "localhost"; $databasename = "test"; $databasetable = "sample"; $databaseusername ="test"; $databasepassword = ""; $fieldseparator = ","; $lineseparator = "\n"; $csvfile = "filename.csv"; /********************************/ /* Would you like to add an ampty field at the beginning of these records? /* This is useful if you have a table with the first field being an auto_increment integer /* and the csv file does not have such as empty field before the records. /* Set 1 for yes and 0 for no. ATTENTION: don't set to 1 if you are not sure. /* This can dump data in the wrong fields if this extra field does not exist in the table /********************************/ $addauto = 0; /********************************/ /* Would you like to save the mysql queries in a file? If yes set $save to 1. /* Permission on the file should be set to 777. Either upload a sample file through ftp and /* change the permissions, or execute at the prompt: touch output.sql && chmod 777 output.sql /********************************/ $save = 1; $outputfile = "output.sql"; /********************************/ if (!file_exists($csvfile)) { echo "File not found. Make sure you specified the correct path.\n"; exit; } $file = fopen($csvfile,"r"); if (!$file) { echo "Error opening data file.\n"; exit; } $size = filesize($csvfile); if (!$size) { echo "File is empty.\n"; exit; } $csvcontent = fread($file,$size); fclose($file); $con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error()); @mysql_select_db($databasename) or die(mysql_error()); $lines = 0; $queries = ""; $linearray = array(); foreach(split($lineseparator,$csvcontent) as $line) { $lines++; $line = trim($line," \t"); $line = str_replace("\r","",$line); /************************************ This line escapes the special character. remove it if entries are already escaped in the csv file ************************************/ $line = str_replace("'","\'",$line); /*************************************/ $linearray = explode($fieldseparator,$line); $linemysql = implode("','",$linearray); if($addauto) $query = "insert into $databasetable values('','$linemysql');"; else $query = "insert into $databasetable values('$linemysql');"; $queries .= $query . "\n"; @mysql_query($query); } @mysql_close($con); if ($save) { if (!is_writable($outputfile)) { echo "File is not writable, check permissions.\n"; } else { $file2 = fopen($outputfile,"w"); if(!$file2) { echo "Error writing to the output file.\n"; } else { fwrite($file2,$queries); fclose($file2); } } } echo "Found a total of $lines records in this csv file.\n"; ?> ]]> https://css-tricks.com/snippets/php/import-csv-into-mysql/feed/ 11 17655 Generate Expiring Amazon S3 Link https://css-tricks.com/snippets/php/generate-expiring-amazon-s3-link/ https://css-tricks.com/snippets/php/generate-expiring-amazon-s3-link/#comments Tue, 03 Jul 2012 13:39:21 +0000 Chris Coyier http://css-tricks.com/?page_id=17382 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 

  
…]]>
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'); ?>
]]>
https://css-tricks.com/snippets/php/generate-expiring-amazon-s3-link/feed/ 15 17382