Never been to TextSnippets 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 www.cdnm.com

« Newer Snippets
Older Snippets »
18 total  XML / RSS feed 

is_valid_email_address function

// description of your code here


/* Regex for validating email address */
function is_valid_email_address($email_address)
{
  if (ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$",$email_address) )
  {
    return TRUE;
  }
  else
  {
    return FALSE;
  }
}

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("\"",""",$text); // Get rid of curly quotation marks
        $text=str_replace("  "," ",$text); // Get rid of double spaces (not tabs)
        $text=str_replace("\r","

",$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);
}

Make Title Case

// Run text throughthis to make it title case
// "from russia with love" becomes:
// "From Russia with love"


function title_case($title) {
  // Our array of 'small words' which shouldn't be capitalised if
  // they aren't the first word.  Add your own words to taste.
  $smallwordsarray = array(
    'of','a','the','and','an','or','nor','but','is','if','then','else','when',
    'at','from','by','on','off','for','in','out','over','to','into','with'
    );
  // Split the string into separate words
  $words = explode(' ', $title);
  foreach ($words as $key => $word)
  {
    // If this word is the first, or it's not one of our small words, capitalise it
    // with ucwords().
    if ($key == 0 or !in_array($word, $smallwordsarray))
      $words[$key] = ucwords(strtolower($word));
  }
  // Join the words back into a string
  $newtitle = implode(' ', $words);
  return $newtitle;
}

Make Sentence Case

// Run text through this to make it sentence case...
// "the pretty pink sandwich" becomes:
// "The pretty pink sandwich"


function sentence_case($s) {
   $str = strtolower($s);
   $cap = true;
   for($x = 0; $x < strlen($str); $x++){
       $letter = substr($str, $x, 1);
       if($letter == "." || $letter == "!" || $letter == "?"){
           $cap = true;
       }elseif($letter != " " && $cap == true){
           $letter = strtoupper($letter);
           $cap = false;
       }
       $ret .= $letter;
   }
   return $ret;
}

Proper Ending for Numbers (i.e. 2nd, 3rd, 8th)

// Run numbers through this to add proper endings (i.e. 2nd, 3rd, 8th)


 function nth_num($age, $small = 0) {
        $last_char_age = substr("$age", -1);
        switch($last_char_age) {
                case '1' :
                        $th = 'st';
                        break;
                case '2' :
                        $th = 'nd';
                        break;
                case '3' :
                        $th = 'rd';
                        break;
                default :
                        $th = 'th';
                        break;
        }
        if ($age > 10 && $age < 20) $th = 'th';
        if (0 == $small) $niceage = $age.$th;
        if (1 == $small) $niceage = $age."$th";
        return $niceage;
        }

Curly Quote Maker

// Run text through this function to make curly quotes


        function curl_me($curlme) {
        // This should take care of the single quotes
        $curlme = preg_replace("/'([dmst])([ .,?!\)\/<])/i","’$1$2",$curlme);
        $curlme = preg_replace("/'([lrv])([el])([ .,?!\)\/<])/i","’$1$2$3",$curlme);
        $curlme = preg_replace("/(?\s+)'((?:[^ >])?(?:.*?)(?:[^=]))'(\s*[^>&])/Ss","$1‘$2’$3",$curlme);

        // time for the doubles
        $curlme = preg_replace('/(?]])((?:.*?)(?:[^=])?)"(\s*[^>&])/Ss',"$1“$2”$3",$curlme);
        // multi-paragraph
        $curlme = preg_replace('/

"(.*)<\/p>/U',"

“$1

",$curlme); // not a quote, but whatever $curlme = str_replace('Ñ','',$curlme); $curlme = str_replace('Ð','',$curlme); return $curlme; }

Resize Images (create thumbnails)


// this script creates a thumbnail image from an image file - can be a .jpg .gif or .png file 
// where $thumbsize is the maximum width or height of the resized thumbnail image
// where this script is named resize.php 
// call this script with an image tag 
// <img src="resize.php?path=imagepath"> where path is a relative path such as subdirectory/image.jpg 
$thumbsize = 200; 
$imagesource =  $_GET['path']; 
$filetype = substr($imagesource,strlen($imagesource)-4,4); 
$filetype = strtolower($filetype); 
if($filetype == ".gif")  $image = @imagecreatefromgif($imagesource);  
if($filetype == ".jpg")  $image = @imagecreatefromjpeg($imagesource);  
if($filetype == ".png")  $image = @imagecreatefrompng($imagesource);  
if (!$image) die(); 
$imagewidth = imagesx($image); 
$imageheight = imagesy($image);  
if ($imagewidth >= $imageheight) { 
  $thumbwidth = $thumbsize; 
  $factor = $thumbsize / $imagewidth; 
  $thumbheight = $imageheight * $factor; 
} 
if ($imageheight >= $imagewidth) { 
  $thumbheight = $thumbsize; 
  $factor = $thumbsize / $imageheight; 
  $thumbwidth = $imagewidth * $factor; 
} 
$thumb = @imagecreatetruecolor($thumbwidth,$thumbheight); 
imagecopyresized($thumb, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $imagewidth, $imageheight); 
imagejpeg($thumb); 
imagedestroy($image); 
imagedestroy($thumb); 

Show the last modified date of a page

// Show the last modified date of a page
echo "Last modified: " . date ("F d, Y", getlastmod());

Set the server time zone

// Set the server time zone (Eastern time in this example)
putenv('TZ=EST5EDT');

Validate the format of an email address format

// Validate the format of an email address format
if (!preg_match("(^[-\w\.]+@([-a-z0-9]+\.)+[a-z]{2,4}$)i", $email)) echo "Email address $email is not valid";

Validate format of a domain name

// Validate format of a domain name
if (!preg_match("(^([-a-z0-9]+\.)+[a-z]{2,4}$)i", $domain)) echo "Domain name $domain is not valid";
« Newer Snippets
Older Snippets »
18 total  XML / RSS feed