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 97 total

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."\"-//W3C//DTD XHTML 1.1//EN\"";
        $doc_head = $doc_head." \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n";
        $doc_head = $doc_head."\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n\n";
        $doc_head = $doc_head."  \"http://gmpg.org/xfn/1\">\n";
} else {
        ob_start("fix_code");
    $doc_head = "\"-//W3C//DTD HTML 4.01 Transitional//EN\"";
    $doc_head = $doc_head." \"http://www.w3.org/TR/html4/loose.dtd\">\n";
    $doc_head = $doc_head."\"en\">\n\n";
    $doc_head = $doc_head."  \"http://gmpg.org/xfn/1\">\n";
    $doc_head = $doc_head."    \"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 '
        ';$sql="SELECT * FROM table WHERE row=1";$query=mysql_query($sql);while($result=mysql_fetch_array($query)){echo'';}echo'
First Second Third
'.$result['first'].''.$result['second'].'
'; }

read url or file

read url or file

function readUrl($url) {
        $handle = fopen($url, "r");
        $contents = '';
        while (!feof($handle)) {
                $contents .= fread($handle, 8192);
        }
        fclose($handle);
        return $contents;     
}

make error div


function showError($errormsg, $exitstatus) {
        echo '';
        if ($exitstatus==1) exit();
}

random text generator



function RandGen($length) {
        $chars=array();
        for($i=48;$i<=57;$i++) {
                array_push($chars, chr($i));
        }
        for($i=65;$i<=90;$i++) {
                array_push($chars, chr($i));
        }
        for($i=97;$i<=122;$i++) {
                array_push($chars, chr($i));
        }
        while(list($k, $v)=each($chars)) {
        $k." -> ".$v."
"; } for($i=0;$i<$length;$i++) { mt_srand((double)microtime()*1000000); $passwd.=$chars[mt_rand(0,count($chars))]; } return $passwd; }

sql dates to european dates

converts sql dates to european dates and reverse.
2005-04-02 -> 02.04.2005
02.04.2005 -> 2005-04-02


function SqlToEuroDate($date) {
        $fd = substr($date, 8, 2)+0;
        $fm = substr($date, 5, 2)+0;
        $fy = substr($date, 0, 4);
        if ($fm<10) $fm = '0'.$fm;
        if ($fd<10) $fd = '0'.$fd;
        return  $newdate = $fd.'.'.$fm.'.'.$fy;
}

function EuroToSqlDate($date) {
        $fd = substr($date, 0, 2)+0;
        $fm = substr($date, 3, 2)+0;
        $fy = substr($date, 6, 4);
        if ($fm<10) $fm = '0'.$fm;
        if ($fd<10) $fd = '0'.$fd;
        return  $newdate = $fy.'-'.$fm.'-'.$fd;
}

how many days in year

calc days in year

function daysInYear($date) {
        $fd = (int)substr($date, 8, 2);
        $fm = (int)substr($date, 5, 2);
        $fy = (int)substr($date, 0, 4);
        return $days=date('z',mktime(0,0,0,$fm,$fd,$fy));
}

adjust date

adjust date. needed if you want to substract dates
example: date is 2005-12-31, and you want to get 1 month and 2 days greater date, then you just access adjustdate('2005-12-31', $years=0,$months=1,$days=2)

function adjustdate($date,$years=0,$months=0,$days=0) {
        $year=substr($date, 0, 4);
        $month=substr($date, 5, 2);
        $day=substr($date, 8, 2);
        return date("Y-m-d", mktime(0,0,0,$month+$months,$day+$days,$year+ $years));
}

locale process

// description of your code here


/**
 * Enter description here...
 * 
 * @author chenn 
 * @version $Id: Local.php 56 2006-04-11 14:04:39Z chenn $
 */
class Local {
        
        /**
         * Enter description here...
         * 
         * @var string
         */
        private static $lang;
        
        /**
         * local language code, eg. zh_CN, es_ES, etc
         *
         * @var unknown_type
         */
        private $language;
        
        /**
         * Enter description here...
         *
         * @var string
         */
        private $encoding = "UTF-8";
        
        
        function __construct($language) {
                $this->language = $language;
                $this->encoding = DEFAULT_ENCODING;
                $this->loadLocal();
        }
        
        /**
         * Load local language pakege
         *
         */
        private function loadLocal() {
                if (self::$lang == null) {
                        $lang = array();
                        $filename = ROOT_PATH . "language/lang_" . $this->language . ".php";
                        if (is_readable($filename)) {
                                include_once($filename);
                        }
                        
                        if ($handle = opendir(ROOT_PATH . "plugins/")) {
                            while (false !== ($file = readdir($handle))) {
                                if ($file != "." && $file != "..") {
                                    $pLang = ROOT_PATH . "plugins/$file/language/lang_" 
                                                        . $this->language . ".php"; 
                                    if (is_file($pLang)) {
                                        include_once($pLang);
                                    }
                                }
                            }
                            closedir($handle);
                        }

                        // $lang is defined in the lang_xx.php file
                        self::$lang = $lang;
                        unset($lang);
                }
        }
        
        
        /**
         * Get the translated string by key
         *
         * @param       string $key
         * @return      string
         */
        public function getString($key) {
                if (array_key_exists($key, self::$lang)) {
                        return self::$lang[$key];
                } else {
                        return $key;
                }
        }
        
        /**
         * Enter description here...
         *
         * @return array
         */
        public function getStrings() {
                return self::$lang;
        }
        
}

?>

PHP e-mail validator

// regular expression to check for e-mail address validity

function valid_email($email) {

  if( eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email) ) { 
    return true;
  }
  else { 
    return false;
  }

}

Parse out body content from html file in PHP

Parse out the body content of an html file. If no tags found, assume whole file is the content to be used.

        $body_content = join( "", file( $file_to_be_read ) );
        if (eregi( "(.*)", $t, $regs ) ) {
                $body_content = $regs[0];
        }
« Newer Snippets
Older Snippets »
Showing 41-60 of 97 total