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

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..

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')));

Create Simple Excel File from MySQL Results

// Create Excel Fle from MySQL Results


//Written by Dan Zarrella. Some additional tweaks provided by JP Honeywell
//pear excel package has support for fonts and formulas etc.. more complicated
//this is good for quick table dumps (deliverables)


include('register_config.php'); // Include db connect script

$result = mysql_query('SELECT * FROM table_name');
$count = mysql_num_fields($result);

for ($i = 0; $i < $count; $i++){
    $header .= mysql_field_name($result, $i)."\t";
}

while($row = mysql_fetch_row($result)){
  $line = '';
  foreach($row as $value){
    if(!isset($value) || $value == ""){
      $value = "\t";
    }else{
# important to escape any quotes to preserve them in the data.
      $value = str_replace('"', '""', $value);
# needed to encapsulate data in quotes because some data might be multi line.
# the good news is that numbers remain numbers in Excel even though quoted.
      $value = '"' . $value . '"' . "\t";
    }
    $line .= $value;
  }
  $data .= trim($line)."\n";
}
# this line is needed because returns embedded in the data have "\r"
# and this looks like a "box character" in Excel
  $data = str_replace("\r", "", $data);


# Nice to let someone know that the search came up empty.
# Otherwise only the column name headers will be output to Excel.
//if ($data == "") {
//  $data = "\nno matching records found\n";
//}

# This line will stream the file to the user rather than spray it across the screen
header("Content-type: application/octet-stream");

# replace Spreadsheet.xls with whatever you want the filename to default to
header("Content-Disposition: attachment; filename=Spreadsheet.xls");
header("Pragma: no-cache");
header("Expires: 0");

echo $header."\n".$data; 

Turn on PHP Error Reporting

// Turn on PHP Error Reporting

ini_set("display_errors","2");
ERROR_REPORTING(E_ALL);

Image Uploader with ImageMagik Thumbnail Creation

// Place in document within an if stmnt that fires if upload form submitted
// $img_max_width = set to max desired width
// $img_max_height = set to max desired height
// $img_dir = set to path to upload file to NO trailing slash!!!
// $resize = Default is 0, Set to 1 to resize uploaded files
// $thumbnail = Default is 0, Set to 1 to create thumbnails


function file_uploader($img_max_width, $img_max_height, $img_th_max_width, $img_th_max_height, $img_dir, $resize = 0, $thumbnail = 0 ) {
	$image_name = date ('Ymd-His'); // Create unique name using date/time
	$extension = explode ('.', $_FILES['file_to_upload']['name']); // Get the file extension from the uploaded file
	$filename = $image_name .'.'. strtolower ($extension[1]); // Build the LARGE image's filename
	// If the file was uploaded to the temp directory, move to the user specified directory
	if (move_uploaded_file ($_FILES['file_to_upload']['tmp_name'], "$img_dir/$filename")) {

		// If the resize option was set, resize the uploaded image to make a final version
		if ($resize == 1) {
			$imagemagick_path = "/usr/bin/convert"; // Set the path to ImageMagick
			$size = getimagesize ($img_dir ."/". $filename); // Get the uploaded images dimensions
				if ($size[0] > $size[1]) { // Is a Wide Image
					$image_width = $img_max_width;
					$image_height = (int)($img_max_width * $size[1] / $size[0]);
					$photo_orientation = "h";
				} else { // Is a Tall Image
					$image_width = (int)($img_max_height * $size[0] / $size[1]);
					$image_height = $img_max_height;
					$photo_orientation = "v";
				}
			exec ("$imagemagick_path -geometry " . "{$image_width}x{$image_height} " . "$img_dir/$filename $img_dir/$filename");

			// If the thumbnail option was set, resize the uploaded image to make a final version
			if ($thumbnail == 1) {
				// Build the SMALL image's filename by appending "_th" to its name
				$filename_th = $image_name .'_th.'. strtolower ($extension[1]);
					if ($size[0] > $size[1]) { // Is a Wide Image
						$th_width = $img_th_max_width;
						$th_height = (int)($img_th_max_width * $size[1] / $size[0]);
					} else { // Is a Tall Image
						$th_width = (int)($img_th_max_height * $size[0] / $size[1]);
						$th_height = $img_th_max_height;
					}
				exec ("$imagemagick_path -geometry " . "{$th_width}x{$th_height} " . "$img_dir/$filename $img_dir/$filename_th");
			}
		}
		return TRUE;
	} else {
		return FALSE;
	}
}

Text Cleaner

// This function will remove unwanted stuff from submitted text.
// usage: $var = text_cleaner($str);


function text_cleaner($text){
	$text=str_replace("\"","&quot;",$text); // Get rid of curly quotation marks
	$text=str_replace("  "," ",$text); // Get rid of double spaces (not tabs)
	$text=str_replace("\r","</p>",$text); //Windows files do \r\n, this is for a file created in Windows
}

Character Chopper

// This function will limit by number of characters.
// usage: $var = char_chop($str(string), $string_length limit of chars, default: 30));


function char_chop($str, $string_length = 30) {
	$s = strlen($str);
	if($s > $string_length){
		$str = substr(0, $string_length, $str);
		$str .= '...';
	}
	return($str);
}

Word Chopper

// The following will limit a string to $max_words words
// usage: $var = word_chop($str(string), $max_words(limit of words, default: 15));


function word_chop($str, $max_words = 15) {
	$e = explode(' ', $str);
	$w = count($e);
	if($w > $max_words) {
		$str = '';
		for($i=0;$i<$max_words;$i++) {
			$str .= ' '.$e[$i];
		}
	$str .= '...';
	}
	return($str);
}