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!)

« Newer Snippets
Older Snippets »
Showing 41-60 of 106 total

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."<sup>$th</sup>";
        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","&#8217;$1$2",$curlme);
        $curlme = preg_replace("/'([lrv])([el])([ .,?!\)\/<])/i","&#8217;$1$2$3",$curlme);
        $curlme = preg_replace("/(?<!=)(\s+)'((?:[^ >])?(?:.*?)(?:[^=]))'(\s*[^>&])/Ss","$1&#8216;$2&#8217;$3",$curlme);

        // time for the doubles
        $curlme = preg_replace('/(?<!=)(\s+)"(?=[ >]])((?:.*?)(?:[^=])?)"(\s*[^>&])/Ss',"$1&#8220;$2&#8221;$3",$curlme);
        // multi-paragraph
        $curlme = preg_replace('/<p>"(.*)<\/p>/U',"<p>&#8220;$1</p>",$curlme);

        // not a quote, but whatever
        $curlme = str_replace('Ñ','&#8212;',$curlme);
        $curlme = str_replace('Ð','&#8211;',$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";

State name to 2 letter code

Simple one-trick-pony PHP function to take a state name (case insensitive) and return the 2 letter abbreviation.

        function state_to_twoletter( $state_name ) {
                
                $state = array();
                $state['ALABAMA']='AL';
                $state['ALASKA']='AK';
                $state['AMERICAN SAMOA']='AS';
                $state['ARIZONA']='AZ';
                $state['ARKANSAS']='AR';
                $state['CALIFORNIA']='CA';
                $state['COLORADO']='CO';
                $state['CONNECTICUT']='CT';
                $state['DELAWARE']='DE';
                $state['DISTRICT OF COLUMBIA']='DC';
                $state['FEDERATED STATES OF MICRONESIA']='FM';
                $state['FLORIDA']='FL';
                $state['GEORGIA']='GA';
                $state['GUAM']='GU';
                $state['HAWAII']='HI';
                $state['IDAHO']='ID';
                $state['ILLINOIS']='IL';
                $state['INDIANA']='IN';
                $state['IOWA']='IA';
                $state['KANSAS']='KS';
                $state['KENTUCKY']='KY';
                $state['LOUISIANA']='LA';
                $state['MAINE']='ME';
                $state['MARSHALL ISLANDS']='MH';
                $state['MARYLAND']='MD';
                $state['MASSACHUSETTS']='MA';
                $state['MICHIGAN']='MI';
                $state['MINNESOTA']='MN';
                $state['MISSISSIPPI']='MS';
                $state['MISSOURI']='MO';
                $state['MONTANA']='MT';
                $state['NEBRASKA']='NE';
                $state['NEVADA']='NV';
                $state['NEW HAMPSHIRE']='NH';
                $state['NEW JERSEY']='NJ';
                $state['NEW MEXICO']='NM';
                $state['NEW YORK']='NY';
                $state['NORTH CAROLINA']='NC';
                $state['NORTH DAKOTA']='ND';
                $state['NORTHERN MARIANA ISLANDS']='MP';
                $state['OHIO']='OH';
                $state['OKLAHOMA']='OK';
                $state['OREGON']='OR';
                $state['PALAU']='PW';
                $state['PENNSYLVANIA']='PA';
                $state['PUERTO RICO']='PR';
                $state['RHODE ISLAND']='RI';
                $state['SOUTH CAROLINA']='SC';
                $state['SOUTH DAKOTA']='SD';
                $state['TENNESSEE']='TN';
                $state['TEXAS']='TX';
                $state['UTAH']='UT';
                $state['VERMONT']='VT';
                $state['VIRGIN ISLANDS']='VI';
                $state['VIRGINIA']='VA';
                $state['WASHINGTON']='WA';
                $state['WEST VIRGINIA']='WV';
                $state['WISCONSIN']='WI';
                $state['WYOMING']='WY';

                // Canadian Provinces
                // edited 12-5-07
                $state['ALBERTA']='AB';
                $state['BRITISH COLUMBIA']='BC';
                $state['MANITOBA']='MB';
                $state['NEW BRUNSWICK']='NB';
                $state['LABRADOR']='NL';
                $state['NEWFOUNDLAND]='NL';
                $state['NORTHWEST TERRITORIES']='NT';
                $state['NOVA SCOTIA']='NS';
                $state['NUNAVUT']='NU';
                $state['ONTARIO']='ON';
                $state['PRINCE EDWARD ISLAND']='PE';
                $state['QUEBEC']='QC';
                $state['SASKATCHEWAN']='SK';
                $state['YUKON']='YT';

                return $state[strtoupper( $state_name )]; 
                
        }

Calculate Thanksgiving Date

This is the most concise way I've seen to calculate Thanksgiving date (in PHP).

strtotime("3 weeks thursday",mktime(0,0,0,11,1,$year)

php include random file

<?
/* Directory Structure
/index1.html
/index2.html
/index3.html
/index4.html
/index5.html
*/
srand((double)microtime()*1000000);
$num = rand(1,5);

include ('index'.$num.'.html');

?>

PHP on mod_fcgid with Apache2 and mod_suexec

This took a little doing and some major tweaking. Assuming you have the LoadModule line already...

  AddHandler fcgid-script .php

  <Directory /home/elitesys/elite-systems.org/html>
    FCGIWrapper /home/elitesys/elite-systems.org/html/php.fcgi .php
  </Directory>

  IPCConnectTimeout 20
  IPCCommTimeout 300


Add the handler for php files, specify the wrapper (in this case the file in the root of the site) and setup connect and communication timeouts. The timeouts are in seconds and you need to set it like that or higher or else file uploads will timeout and I have heard of issues with Wordpress if you don't increase it.

And in php.fcgi...
#!/bin/sh
PHPRC="/usr/php4/etc"
export PHPRC
PHP_FCGI_CHILDREN=4
export PHP_FCGI_CHILDREN
PHP_FCGI_MAX_REQUESTS=5000
export PHP_FCGI_MAX_REQUESTS
exec /usr/php4/bin/php


This should look familiar to another post...

There isn't a definition for suexec in terms of executable location. There doesn't have to be. Apache will automatically wrap it properly. This configuration is far easier than mod_fastcgi and works just as well. Probably easily expanded to work with ruby on rails although I havn't tried yet...

serve suitable mime type with php

An updated version of the keystone method. If you are wanting to use it for a doctype other than XHTML 1.1 then a little easy editing is needed. Simon Jessey (another Brit') sent me this updated version which differs to the original in that it works just fine with the W3C Validator.

<?php


/*
    This script determines the preferred MIME type of a user agent
    and then delivers either application/xhtml+xml or text/html.
    Copyright (c) 2003 - 2004 Keystone Websites and Simon Jessey
*/


$charset = "utf-8";
$mime = "text/html";

function fix_code($buffer) {
    return (str_replace(" />", ">", $buffer));
}

if(stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml")) {
        if(preg_match("/application\/xhtml\+xml;q=([01]|0\.\d{1,3}|1\.0)/i",$_SERVER["HTTP_ACCEPT"],$matches)) {
                $xhtml_q = $matches[1];
                if(preg_match("/text\/html;q=q=([01]|0\.\d{1,3}|1\.0)/i",$_SERVER["HTTP_ACCEPT"],$matches)) {
                        $html_q = $matches[1];
                        if((float)$xhtml_q >= (float)$html_q) {
                        $mime = "application/xhtml+xml";
                        }
                }
        } else {
                $mime = "application/xhtml+xml";
                }
}

if(stristr($_SERVER["HTTP_USER_AGENT"],"WDG_Validator") ||
   stristr($_SERVER["HTTP_USER_AGENT"],"W3C_Validator")) {
        $mime = "application/xhtml+xml";
}

if($mime == "application/xhtml+xml") {
        $doc_head = "<?xml version=\"1.0\" encoding=\"$charset\"?>\n";
        $doc_head = $doc_head."<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"";
        $doc_head = $doc_head." \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n";
        $doc_head = $doc_head."<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n\n";
        $doc_head = $doc_head."  <head profile=\"http://gmpg.org/xfn/1\">\n";
} else {
        ob_start("fix_code");
    $doc_head = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"";
    $doc_head = $doc_head." \"http://www.w3.org/TR/html4/loose.dtd\">\n";
    $doc_head = $doc_head."<html lang=\"en\">\n\n";
    $doc_head = $doc_head."  <head profile=\"http://gmpg.org/xfn/1\">\n";
    $doc_head = $doc_head."    <meta http-equiv=\"content-type\" content=\"$mime;charset=$charset\">\n";
}

header("Content-Type: $mime;charset=$charset");
header("Vary: Accept");

print $doc_head;

?>


Replace you doctype declaration, mime type in the head of your document or template with:
<?php include("pathtowhateveryouhavecalledit.php"); ?>


Many thanks to Simon Jessey for this version.

PHP as FastCGI program

If you have problem with compiling php as cgi-fastcgi *run* make clean. It worked for me and, probably, it will work for you.

And here's my ./configure options for compiling php as cgi-fastcgi with some features I need.

simanyay $ make clean
simanyay $ ./configure --prefix=/usr/local/php5/ --enable-mbstring --with-mysql=/usr/local/mysql --with-mysql-sock=/t
mp/mysql.sock --with-mysqli --with-pdo-mysql=/usr/local/mysql --enable-force-cgi-redirect --enable-fastcgi --with-cur
l --with-sockets --enable-memory-limit --with-config-file-scan-dir=/usr/local/php5/sharecfg
simanyay $ make
simanyay $ sudo make install
simanyay $ /usr/local/php5/bin/php -v
PHP 5.1.4 (cgi-fcgi) (built: May 23 2006 20:03:51)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies

Simple PHP Loop

// a loop from 1 to 10

for ( $counter = 1; $counter <= 10; $counter += 1) {

}

HTML tag stripper

// *UNTESTED*
// Strips complete and incomplete HTML tags from $html

function strip_bad_tags($html)
{
   $s = preg_replace ("@</?[^>]*>*@", "", $html);
   return $s;
}

PHP - Using Absolute URLs with header()

// Redirects a user to the current domain, the current directory, and the new page. Won't break if you move the scripts to another folder/domain etc.

header ("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/newpage.php");

Image resize

Resize an image, keeping proportions to a new width or a new height. oh, and it caches.
You'll need to setup a writable directory $_SERVER[ 'DOCUMENT_ROOT' ].'/images/cache/ to use it.
<?php

if (isset($_GET[ 'image' ]))
{
    $image = realpath($_SERVER[ 'DOCUMENT_ROOT' ].urldecode($_GET[ 'image' ]));
    
    if (!file_exists($image))
    {
        die ( 'no such image!' );
    }
} else {
    die ( 'Missing argument!' );
}

function between($x, $y, $z)
{
    return $x >= $y && $x <= $z;
}

function cachefilename( $o, $w, $h)
{
    return $_SERVER[ 'DOCUMENT_ROOT' ].'/images/cache/'.base64_encode( $o.$w.$h ).'jpeg';
}

$imageinfo = getimagesize($image);
$w = $imageinfo[0];
$h = $imageinfo[1];
// the 64 and 1024 are minimum and maximum, change to please
if (isset ($_GET[ 'width' ]) && between($_GET[ 'width' ], 64, 128))
{
    $resizedwidth = $_GET[ 'width' ];
    $wf = $w / $resizedwidth;
    $resizedheight = $h / $wf;

} else {
    // same here
    if (isset ($_GET[ 'height' ]) && between($_GET[ 'height' ], 64, 1024))
    {
        $resizedheight = $_GET[ 'height' ];
        $hf = $h / $resizedheight;
        $resizedwidth = $w / $hf;

    } else {
        $resizedwidth = 600;
        $wf = $w / $resizedwidth;
        $resizedheight = $h / $wf;
    }
}

if (file_exists( cachefilename($image, $resizedwidth, $resizedheight) ))
{
    header ("Content-type: image/jpeg");
    readfile(cachefilename($image, $resizedwidth, $resizedheight) );
} else {
    $img = imagecreatefromstring(file_get_contents( $image ));
    $thumb = imagecreatetruecolor($resizedwidth, $resizedheight);
    imagecopyresampled($thumb, $img, 0, 0, 0, 0, $resizedwidth, $resizedheight, $w, $h);
    header ("Content-type: image/jpeg");
    imagejpeg($thumb, cachefilename($image, $resizedwidth, $resizedheight), 70);
    readfile(cachefilename($image, $resizedwidth, $resizedheight) );
    imagedestroy($img);
    imagedestroy($thumb);
}

?>

KFileFinder OOPHP5

<?php

/**
  * Recursively find a file by its name in a directory.
  *
  * Found files are cached onto the current session for
  * quicker access next time.
  *
  * Requires PHP 5
  *
  * by theredhead
  */
class KFileFinder
{
        public $dir  = null;
        public $file = null;
        
        public function __construct( $file = null, $dir = null )
        {
            // did we give a directory?
                if ( $dir == null )
                {
                    // no, start searching under the servers public root
                        $this->dir = realpath( $_SERVER[ 'DOCUMENT_ROOT' ].'/../' );
                } else {
                        $this->dir = $dir;
                }

        // let the instance know what file to look for
                if ( $file !== null )
                {
                        $this->file = $file;
                }
                
                return $this;
        }
        
        // static method: $result = KFileFinder::findFile( 'guestbook.xml' );
        public static function findFile( $file, $dir = null )
        {
                $finder = new KFileFinder( $file, $dir );
                $result = $finder->find();
                unset($finder);
                return $result;
        }
        
        // instance method: $result = $myFinder->find( 'guestbook.xml' );
        public function find( $dir = null )
        {
            // cache found file into the session so we only have to search
            // for it the first time and when it moved    
            if (isset($_SESSION[ 'KFileFinder' ][ $this->file ]) &&
                file_exists($_SESSION[ 'KFileFinder' ][ $this->file ]))
            {
                return $_SESSION[ 'KFileFinder' ][ $this->file ];
            }
            
                $found = false;

                if ( $dir == null )
                {
                        $d = $this->dir;
                } else {
                        $d = $dir;
                }

                $iterator = new DirectoryIterator( $d );
        // the loop
                while( $iterator->valid() && $found == false )
                {
                        if ( !$iterator->isDot() && $iterator->isDir() )
                        {
                                $pathToCheck = $iterator->getPathname().'/'.$this->file;
                                // test if the file existts and if we can read it
                                if ( file_exists( $pathToCheck ) && is_readable( $pathToCheck ))
                                {
                                        $found = $pathToCheck;
                                } else {
                                        $found = $this->find( $iterator->getPathname() );
                                }
                        }
                        $iterator->next();
                }
                // cache the result
                $_SESSION[ 'KFileFinder' ][ $this->file ] = $found;
                return $found;
        }
}

?>

add zeros to number or string

function to add zeros to number or string


function addZeros($numcount, $value, $where) {
    if ($value=="") echo "Error: value is missing";
    if ($numcount=="") echo "Error: numcount is missing";
    $newnum = "";
    $n = strlen($value);
    if ($where==">") $newnum .= $value;
    for ($i=0; $i<($numcount-$n); $i++) {
        $newnum .= "0";
    }
    if ($where=="<") $newnum .= $value;
    return $newnum;   
}

// usage:
echo addZeros(8, "122", "<");
// echos 00000122
echo addZeros(5, "2", ">");
// echos 200000

standard sql query in php

url to access: test.php?do=something


if ($_GET['do'] == 'something') {
    echo '
        <table>
            <tr>
                <th>First</th>
                <th>Second</th>
                <th>Third</th>
            </tr>
    ';
    $sql = "SELECT * FROM table WHERE row=1"; 
    $query = mysql_query($sql);
    while ($result = mysql_fetch_array($query)) {
        echo '<tr><td>'.$result['first'].'</td><td>'.$result['second'].'</td><tr>';
    }
    echo '</table>';
}


« Newer Snippets
Older Snippets »
Showing 41-60 of 106 total