Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

Tracy Floyd http://www.coalescedesign.com

Force specific actions to use SSL

Force specific actions to use SSL

<?php
class AppController extends Controller {
	var $components = array('Security');

	function beforeFilter() {
		$this->Security->blackHoleCallback = 'forceSSL';
		$this->Security->requireSecure('login', 'checkout');
	}

	function forceSSL() {
		$this->redirect('https://' . $_SERVER['SERVER_NAME'] . $this->here);
	}
}
?>

Backing Up MySQL to remote server via bash

via http://www.sitepoint.com/blogs/2004/04/30/backing-up-mysql/


#!/bin/bash ##################################### ### MySQL Configuration Variables ### ##################################### # MySQL Hostname DBHOST='localhost' # MySQL Username DBUSER='root' # MySQL Password DBPASSWD='password' ##################################### ### FTP Configuration Variables ##### ##################################### # FTP Hostname FTPHOST='www.example.com' # FTP Username FTPUSER='username' # FTP Password FTPPASSWD='password' # Local Directory for Dump Files LOCALDIR=/path/to/local/directory/ # Remote Directory for Offsite Backup REMOTEDIR=/path/to/remote/directory/ # Prefix for offsite .tar file backup TARPREFIX=db1 ##################################### ### Edit Below If Necessary ######### ##################################### cd $LOCALDIR SUFFIX=`eval date +%y%m%d` DBS=`mysql -u$DBUSER -p$DBPASSWD -h$DBHOST -e"show databases"` for DATABASE in $DBS do if [ $DATABASE != "Database" ]; then FILENAME=$SUFFIX-$DATABASE.gz mysqldump -u$DBUSER -p$DBPASSWD -h$DBHOST $DATABASE | gzip --best > $LOCALDIR$FILENAME fi done chmod 400 $LOCALDIR*.gz tar -cf $TARPREFIX-$SUFFIX.tar $SUFFIX-*.gz ftp -n $FTPHOST <


This second script is updated to use mysqlhotcopy and is specifically for use with ISAM/MYISAM tables only. This script below will NOT work with InnoDB tables.

#!/bin/bash ### Configuration Variables DBHOST='localhost' DBUSER='root' DBPASSWD='password' FTPHOST='ftp.example.com' FTPUSER='username' FTPPASSWD='password' LOCALDIR=/path/to/local/ REMOTEDIR=/path/to/local/ TARPREFIX=db1 ### Do not edit anything below this line cd $LOCALDIR SUFFIX=`eval date +%y%m%d` DBS=`mysql -u$DBUSER -p$DBPASSWD -h$DBHOST -e"show databases"` for DATABASE in $DBS do if [ $DATABASE != "Database" ]; then FILENAME=$SUFFIX-$DATABASE.tar.gz mysqlhotcopy -u $DBUSER -p $DBPASSWD $DATABASE $LOCALDIR tar -czf $LOCALDIR$FILENAME $LOCALDIR$DATABASE rm -rf $LOCALDIR$DATABASE rm -rf $LOCALDIR$DATABASE-replicate fi done chmod 400 $LOCALDIR*.tar.gz tar -cf $TARPREFIX-$SUFFIX.tar $SUFFIX-*.tar.gz ftp -n $FTPHOST <

Bash script for mysql db backups

For use in a cron job


#!/bin/sh
DATE=`/bin/date +"%G%m%d"` ;
mysqldump --host=localhost --user=YOURUSER --password=YOURPASSWORD --all-databases --single-transaction --quick | gzip > ./YOURFILEPATH/backup-$DATE.sql.gz ;

trim_array()

// Recursively apply trim() to an array's values

function trim_array($x)
{
   if (is_array($x)) {
       return array_map('trim_array', $x);
   }
   return trim($x);
}

Weighted, Paginated MySQL Search Query for CakePHP

CakePHP formatted, weighted MySQL query

$this->paginate = array(
  'fields' => "*, (MATCH (title) AGAINST ('$q' IN BOOLEAN MODE)*100) + (MATCH (body) AGAINST ('$q' IN BOOLEAN MODE)*10) + MATCH (clients) AGAINST ('$q' IN BOOLEAN MODE) AS rating",
  'conditions' =>  "MATCH (title,body,clients) AGAINST ('$q' IN BOOLEAN MODE)",
  'order' => 'rating DESC',
  'limit' => 10
);
$results = $this->paginate('Article');

Convert an object to an associative array

// Converts a php object to an associative array

function object_to_array($data) 
{
  if(is_array($data) || is_object($data))
  {
    $result = array(); 
    foreach($data as $key => $value)
    { 
      $result[$key] = object_to_array($value); 
    }
    return $result;
  }
  return $data;
}

// insert code here..

Helpful localhosting terminal commands

// description of your code here


# Adding vhosts
mate /etc/httpd/httpd.conf
mate /etc/hosts

# Restart Apache
sudo apachectl graceful

# Recursively remove .svn folders
rm -rf `find . -type d -name .svn`

Force traffic over HTTPS

// Force traffic over HTTPS to avoid weird session dropping issues, Also handles addition or removal of www prefix as needed for your security cert,


<IfModule mod_rewrite.c>

RewriteEngine On

  # Force removal of www
  RewriteCond %{HTTP_HOST} ^www\.(.+)$
  RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

  # (Or force addition of www depending on your cert)
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] 

  # Now Force traffic to use HTTPS
  RewriteCond %{SERVER_PORT} !443
  RewriteRule ^(.*)$ https://securesiteurl.com/$1 [R=301,L]

</IfModule>

Email Form Validation Related Functions

// Email form validation functions

<?php

// Function to look for suspicious looking text in submitted values
function is_injected($str) 
{
  $injections = array('(Content-Type:)','(MIME-Version:)','(Content-Transfer-Encoding:)','(From:)','(to:)','(cc:)','(bcc:)');
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str)) {
    return true;
  }
  else {
    return false;
  }
}

// Logic for page that calls the mail() function
if ($not_injected)
{
  // email send code...
}




/* Strips html tags and trims whitespace from data */
function clean_up($data) {
   $data = strip_tags($data);
   $data = trim(htmlentities($data));
   return $data;
}


?>

Return the MySQL-formatted date for 60 days from today (PHP)

// Get the date in MySQL date format for 60 days from today

$new_expiration_date = date('Y-m-d',mktime(0,0,0,date('m'),date('d')+60,date('Y')));