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 21-40 of 99 total

LightTPD, PHP, MySQL on FreeBSD

// A method for installing LightTPD, PHP, MySQL on FreeBSD
// All source is stored in /usr/local/src
// Source tarballs are in /usr/local/src/tarballs
// Note this works pretty much the same on Mac OS X
// and I've done it on Ubuntu 6.06
# Have to do this via my Mac because of all the mirror servers
# I use scp to copy from Mac to FreeBSD box
# Downloaded into /usr/local/src/taballs:
- php-5.2.0.tar.bz2 from http://www.php.net/downloads.php
- mysql-5.0.27.tar.gz from http://dev.mysql.com/downloads/mysql/5.0.html#downloads

# On FreeBSD box
cd /usr/local/src
cd tarballs
fetch http://mirrors.cat.pdx.edu/lighttpd/lighttpd-1.4.13.tar.gz
cd ..
tar xzvf tarballs/php-5.2.0.tar.bz2
tar zxvf tarballs/mysql-5.0.27.tar.gz
tar zxvf tarballs/lighttpd-1.4.13.tar.gz

MySQL first
=======================================================
# Shut down MySQL:
/usr/local/mysql/bin/mysqladmin -u root -p shutdown
cd mysql-5.0.27
./configure --prefix=/usr/local/mysql \
            --localstatedir=/usr/local/mysql/data \
            --enable-assembler \
            --with-mysqld-ldflags=-all-static CFLAGS="-O3" CXX=gcc CXXFLAGS="-O3 \
            -felide-constructors -fno-exceptions -fno-rtti"

# Change to root
su

# I like to run the process in the background (&),
# redirect the output to a log file,
# and tail -f the log file.

# Make it:
make > ~/mysql_make.log &
# Watch the make:
tail -f ~/mysql_make.log

# Install it:
make install > ~/mysql_install.log &
# Watch the install:
tail -f ~/mysql_install.log

PHP as a CGI:
=====================================================================
cd /usr/local/src/php-5.2.0

# Make sure curl is where we think it is
locate curl | grep include

# Configure it
./configure --with-xml --with-zlib --with-mysql=/usr/local/mysql \
            --with-mysqli=/usr/local/mysql/bin/mysql_config \
            --with-curl=/usr/local/include \
            --enable-cgi --enable-fastcgi \
            --enable-force-redirect \
            > ~/phpconfig.log &
tail -f ~/phpconfig.log

# Edit the Makefile to eliminate duplicates in the EXTRA_LIBS line
pico Makefile
# New: EXTRA_LIBS = -lcrypt -lmysqlclient -liconv -lcurl -lz -lm -lxml2 -lssl -lcrypto

# Make it
make > ~/php_make.log &
tail -f ~/php_make.log

# Install it
make install > ~/php_install.log &
tail -f ~/php_install.log

LightTPD:
=================================================================
# Check requirements
locate libpcre
locate libz

# If those aren't there, find them in ports and install

cd /usr/local/src/lighttpd-1.4.11
./configure --prefix=/usr/local --with-pcre=/usr/local

# Make it
make > ~/lighttpd_make.log &
tail -f ~/lighttpd_make.log

# Install it
make install > ~/lighttpd_install.log &
tail -f ~/lighttpd_install.log

# Start MySQL
/usr/local/etc/rc.d/mysql.server.sh start
@HOSTNAME@: not found
@HOSTNAME@: not found
Starting MySQL. SUCCESS!

# Check MySQL version
/usr/local/mysql/bin/mysqladmin -v
/usr/local/mysql/bin/mysqladmin  Ver 8.41 Distrib 5.0.27, for unknown-freebsd6.0 on i386

# Add mysql to the path for root.
cd
pico .cshrc
 set path = (/sbin /bin /usr/sbin /usr/bin /usr/games /usr/local/sbin /usr/local/bin /usr/X11R6/bin $HOME/bin)
     becomes
 set path = (/sbin /bin /usr/sbin /usr/bin /usr/games /usr/local/sbin /usr/local/bin /usr/X11R6/bin $HOME/bin /usr/local/mysql/bin)

# Use the lighttpd.conf file I have posted separately
# Requires use of /var/log/lighttpd log directory
mkdir /var/log/lighttpd
chmod 777 /var/log/lighttpd

# Test the server?
lighttpd -f /usr/local/etc/lighttpd.conf
ps ax | grep light
59463  ??  S      0:00.02 lighttpd -f /usr/local/etc/lighttpd.conf
59537  p0  R+     0:00.00 grep light

# To shut off the server
# pid file is in /var/run/lighttpd.pid

LightTPD with named Virtual Hosts on Mac OS X

// description of your code here
// Sample lighttpd.conf file for Mac OS X
// Look at the FastCGI and Virtual Host sections
// Substitute your username for "username"
# Mac OS X lighttpd configuration file

############ Options you really have to take care of ####################

## modules to load
# mod_access, mod_accesslog and mod_alias are loaded by default
# all other module should only be loaded if neccesary
# - saves some time
# - saves memory

server.modules = ( 
           "mod_access",
           "mod_alias",
           "mod_accesslog",
           "mod_fastcgi",
           "mod_proxy",
           "mod_rewrite", 
#           "mod_redirect", 
#           "mod_status", 
           "mod_evhost",
#           "mod_compress",
#           "mod_usertrack",
#           "mod_rrdtool",
#           "mod_webdav",
#           "mod_expire",
#           "mod_flv_streaming",
#           "mod_evasive"
)

# fastcgi per LightTPD docs
fastcgi.server = ( ".php" =>
   (( "socket" => "/tmp/php-fastcgi.socket",
      "bin-path" => "/usr/local/bin/php",
      "bin-environment" => ( 
        "PHP_FCGI_CHILDREN" => "16",
        "PHP_FCGI_MAX_REQUESTS" => "10000" ),
      "bin-copy-environment" => (
        "PATH", "SHELL", "USER" ),
      "broken-scriptfilename" => "enable"
   )),
     ".html" =>
   (( "socket" => "/tmp/php-fastcgi.socket",
      "bin-path" => "/usr/local/bin/php",
      "bin-environment" => (
        "PHP_FCGI_CHILDREN" => "16",
        "PHP_FCGI_MAX_REQUESTS" => "10000" ),
      "bin-copy-environment" => (
        "PATH", "SHELL", "USER" ),
      "broken-scriptfilename" => "enable"
   ))

 )

## a static document-root, for virtual-hosting take look at the 
## server.virtual-* options
#server.document-root       = "/var/www/"
server.document-root     = "/Users/username/Sites"

## where to send error-messages to
server.errorlog            = "/var/log/lighttpd/error.log"

## files to check for if .../ is requested
index-file.names           = ( "index.php", "index.html", 
                               "index.htm", "default.htm" )

## Virtual host

$HTTP["host"] == "site1" {
  server.document-root = "/Users/username/Sites/site1"
  alias.url = ( "/css/" => "/Users/username/Sites/site1/css/",
                "/js/" => "/Users/username/Sites/site1/js/" ,
                "/images/" => "/Users/username/Sites/site1/images/" )
  server.errorlog = "/var/log/lighttpd/site1/error.log"
  accesslog.filename = "/var/log/lighttpd/site1/access.log"
}

$HTTP["host"] == "site2" {
  server.document-root = "/Users/username/Sites/site2"
  alias.url = ( "/css/" => "/Users/username/Sites/site2/css/",
                "/js/" => "/Users/username/Sites/site2/js/" ,
                "/images/" => "/Users/username/Sites/site2/images/" )
  server.errorlog = "/var/log/lighttpd/site2/error.log"
  accesslog.filename = "/var/log/lighttpd/site2/access.log"
}

## Use the "Content-Type" extended attribute to obtain mime type if possible
#mimetype.use-xattr = "enable"
#mimetype.use-xattr = "disable"

##
## mimetype mapping
##
mimetype.assign  = (
".pdf"          =>      "application/pdf",
".sig"          =>      "application/pgp-signature",
".spl"          =>      "application/futuresplash",
".class"        =>      "application/octet-stream",
".ps"           =>      "application/postscript",
".torrent"      =>      "application/x-bittorrent",
".dvi"          =>      "application/x-dvi",
".gz"           =>      "application/x-gzip",
".pac"          =>      "application/x-ns-proxy-autoconfig",
".swf"          =>      "application/x-shockwave-flash",
".tar.gz"       =>      "application/x-tgz",
".tgz"          =>      "application/x-tgz",
".tar"          =>      "application/x-tar",
".zip"          =>      "application/zip",
".mp3"          =>      "audio/mpeg",
".m3u"          =>      "audio/x-mpegurl",
".wma"          =>      "audio/x-ms-wma",
".wax"          =>      "audio/x-ms-wax",
".ogg"          =>      "application/ogg",
".wav"          =>      "audio/x-wav",
".gif"          =>      "image/gif",
".jpg"          =>      "image/jpeg",
".jpeg"         =>      "image/jpeg",
".png"          =>      "image/png",
".xbm"          =>      "image/x-xbitmap",
".xpm"          =>      "image/x-xpixmap",
".xwd"          =>      "image/x-xwindowdump",
".css"          =>      "text/css",
".html"         =>      "text/html",
".htm"          =>      "text/html",
".js"           =>      "text/javascript",
".asc"          =>      "text/plain",
".c"            =>      "text/plain",
".cpp"          =>      "text/plain",
".log"          =>      "text/plain",
".conf"         =>      "text/plain",
".text"         =>      "text/plain",
".txt"          =>      "text/plain",
".spec"         =>      "text/plain",
".dtd"          =>      "text/xml",
".xml"          =>      "text/xml",
".mpeg"         =>      "video/mpeg",
".mpg"          =>      "video/mpeg",
".mov"          =>      "video/quicktime",
".qt"           =>      "video/quicktime",
".avi"          =>      "video/x-msvideo",
".asf"          =>      "video/x-ms-asf",
".asx"          =>      "video/x-ms-asf",
".wmv"          =>      "video/x-ms-wmv",
".bz2"          =>      "application/x-bzip",
".tbz"          =>      "application/x-bzip-compressed-tar",
".tar.bz2"      =>      "application/x-bzip-compressed-tar",
# make the default mime type application/octet-stream.
#""              =>      "application/octet-stream",
)

#### accesslog module
accesslog.filename         = "/var/log/lighttpd/access.log"

## deny access the file-extensions
#
# ~    is for backupfiles from vi, emacs, joe, ...
# .inc is often used for code includes which should in general not be part
#      of the document-root
url.access-deny            = ( "~", ".inc" )

######### Options that are good to be but not neccesary to be changed #######

## bind to port (default: 80)
#server.port               = 81

## bind to localhost only (default: all interfaces)
#server.bind                = "localhost"

## error-handler for status 404
#server.error-handler-404  = "/error-handler.html"
#server.error-handler-404  = "/error-handler.php"

## to help the rc.scripts
server.pid-file            = "/var/run/lighttpd.pid"

## 
## Format: .html
## -> ..../status-404.html for 'File not found'
#server.errorfile-prefix    = "/var/www/"

## virtual directory listings
dir-listing.encoding        = "utf-8"
server.dir-listing          = "enable"

## send unhandled HTTP-header headers to error-log
#debug.dump-unknown-headers  = "enable"

### only root can use these options
#
# chroot() to directory (default: no chroot() )
#server.chroot            = "/"

## change uid to  (default: don't care)
#server.username            = "www-data"

## change uid to  (default: don't care)
#server.groupname           = "www-data"

#### compress module
#compress.cache-dir          = "/var/tmp/lighttpd/cache/compress/"
#compress.filetype           = ("text/plain", "text/html")

#### status module
# status.status-url = "/server-status"
# status.config-url = "/server-config"

#### url handling modules (rewrite, redirect, access)
# url.rewrite                 = ( "^/$"             => "/server-status" )
# url.redirect                = ( "^/wishlist/(.+)" => "http://www.123.org/$1" )

#
# define a pattern for the host url finding
# %% => % sign
# %0 => domain name + tld
# %1 => tld
# %2 => domain name without tld
# %3 => subdomain 1 name
# %4 => subdomain 2 name
#
# evhost.path-pattern = "/home/storage/dev/www/%3/htdocs/"

#### expire module
# expire.url = ( "/buggy/" => "access 2 hours", "/asdhas/" => "access plus 1 seconds 2 minutes")

#### rrdtool
# rrdtool.binary = "/usr/bin/rrdtool"
# rrdtool.db-name = "/var/www/lighttpd.rrd"

## this is a hack
alias.url = ("___invalid___" => "___invalid___")

#### handle Debian Policy Manual, Section 11.5. urls
#### and by default allow them only from localhost

$HTTP["host"] == "localhost" {
        global {
                alias.url += ( 
                        "/doc/" => "/usr/share/doc/",
                        "/images/" => "/usr/share/images/"
                )
        }
        dir-listing.activate = "enable"
}

#### variable usage:
## variable name without "." is auto prefixed by "var." and becomes "var.bar"
#bar = 1
#var.mystring = "foo"

## integer add
#bar += 1
## string concat, with integer cast as string, result: "www.foo1.com"
#server.name = "www." + mystring + var.bar + ".com"
## array merge
#index-file.names = (foo + ".php") + index-file.names
#index-file.names += (foo + ".php")


#### external configuration files
## mimetype mapping
#include_shell "/usr/share/lighttpd/create-mime.assign.pl"

## load enabled configuration files, 
## read /etc/lighttpd/conf-available/README first
#include_shell "/usr/share/lighttpd/include-conf-enabled.pl"

mimimee 123

// description of your code here

index.php
<html>
        <head>
                <script type="text/javascript" src="modul - clock.php">script>
                



"".date("d-m-Y")."<br>".date("H:i:s").""; /*NECESAR pentru a inlocui delay-ul pana ce se incarca script-ul*/?>
"clock" style="position:relative;">



Somewhat ridiculous XML parser + image generator

Seriously needs caching. SRSLY

<?php
        class ImageGeneration {
                function getInfo($name) {
                        $this->loadDefaultInfo();
                        $XML = new XMLReader;
                        $XML->open("http://chat.hypermutt.net/online/user/".$name.".xml");
                        $wn = array();

                        while($XML->read()) {
                                if ($XML->nodeType == XMLReader::ELEMENT) {
                                        $wn[] = $XML->name;
                                }
                                if ($XML->nodeType == XMLReader::TEXT) {
                                        if ("user/info/nick" == implode('/', $wn)) {
                                                $this->name = $XML->value . ". ";
                                        }
                                        if ("user/info/online" == implode('/', $wn)) {
                                                $this->away = ($XML->value == "TRUE") ? true : false;
                                        }


                                        if ("user/info/connected" == implode('/', $wn)) {
                                                $this->onlinefor = strtotime($XML->value);
                                        }
                                        if ("user/info/timenow" == implode('/', $wn)) {
                                                $sc = (strtotime($XML->value) - $this->onlinefor);
                                                $t = floor($sc/86400);
                                                        $c["days"] = ($t > 0) ? $t."D " : ""; $sc = ($sc-$t*86400);
                                                $t = floor($sc/3600);
                                                        $c["hours"] = ($t > 0) ? $t."H " : ""; $sc = ($sc-$t*3600);
                                                $t = floor($sc/60);
                                                        $c["minutes"] = ($t > 0) ? $t."M " : "";
                                                $this->onlinefor = $c["days"].$c["hours"].$c["minutes"];
                                        }
                                        

                                        if ("user/info/away" == implode('/', $wn)) {
                                                $this->away = ($XML->value == "TRUE") ? true : false;
                                        }
                                        if ("user/info/awaymsg" == implode('/', $wn)) {
                                                $this->awaymessage = $XML->value;
                                        }
                                        if ("user/channels/channel/name" == implode('/', $wn)) {
                                                $this->channels .= str_replace('#','',$XML->value)." ";
                                        }
                                }
                                if ($XML->nodeType == XMLReader::END_ELEMENT) {
                                        array_pop($wn);
                                }
                        }
                        $XML->close();
                }
                
                function loadDefaultInfo() {
                        $this->name = ". ";
                        $this->online = true;
                        $this->onlinefor = "";
                        $this->away = true;
                        $this->awaymessage = "";
                        $this->channels = "";
                }
        
                function drawImage() {
                        header("Content-type: image/png");
                        $image = imagecreatefrompng("background.png");
                                $white = imagecolorallocate($image, 255, 255, 255);
                                $red   = imagecolorallocate($image, 255, 0, 0);
                                $green = imagecolorallocate($image, 0, 255, 0);
                                $feb = "slkscreb.ttf";
                                $fnn = "slkscr.ttf";
                        
                        $sizes["name"]   = imagettfbbox(6, 0, $feb, $this->name);
                        $sizes["online"] = imagettfbbox(6, 0, $feb, "online: ");
                        $sizes["away"]   = imagettfbbox(6, 0, $feb, "away: ");
                        $sizes["yes"]    = imagettfbbox(6, 0, $feb, "yes ");
                        $sizes["#"]     = imagettfbbox(6, 0, $feb, "#: ");
                        
                        imagettftext($image, 6, 0, 22, 8, -$white, $feb, $this->name);
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4]), 8, -$white, $feb, "online:");
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + ($sizes["online"][4] - $sizes["away"][4])), 18, -$white, $feb, "away:");
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + ($sizes["online"][4] - $sizes["#"][4])),    28, -$white, $feb, "#: ");
                        
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4]),  8, -(($this->online) ? $green : $red), $feb, (($this->online) ? "yes" : "no"));
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4]), 18, -((!$this->away)  ? $green : $red), $feb, (($this->away)   ? "yes" : "no"));
                        
                        if ($this->online)
                                imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4] + $sizes["yes"][4]),  8, $white, $fnn, $this->onlinefor);
                        if ($this->away)
                                imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4] + $sizes["yes"][4]), 18, $white, $fnn, $this->awaymessage);
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4]), 28, $white, $fnn, $this->channels);
                        
                        imagepng($image);
                        imagedestroy($image);
                }
        }
        
        $x = new ImageGeneration;
        $x->getInfo($_GET['name']);
        $x->drawImage();
?>

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 »
Showing 21-40 of 99 total