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 61-80 of 106 total

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 '<div id="popup">'.$errormsg.'</div>';
        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."<br>";
        }
        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 <[email protected]>
 * @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( "<body.*>(.*)</body>", $t, $regs ) ) {
                $body_content = $regs[0];
        }

Small and simple MySQL (and PHP) Connection

<?php
$conn = mysql_connect("DBHOST", "DBUSERNAME", "DBPASSWORD");
mysql_select_db("DBTABLE", $conn) or die(mysql_error());
?>


This is probably the most basic way of connecting to your MySQL database. :)

Validate an email address

I don't remember where this came from, but it's very useful for validating input from a form


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;
  }

}

Clearing out ruby sessions less than a day old (meaning that etc periodic won't get)

find /tmp/ -name "ruby_sess*" -cmin +1 -exec rm \{} \;
find /tmp/ -name "*request_body*" -cmin +1 -exec rm \{} \;
find /tmp/ -name "*CGI*" -cmin +1 -exec rm \{} \;
find /tmp/ -name "*apr*" -cmin +1 -exec rm \{} \;
find /tmp/ -name "open-uri*" -cmin +1 -exec rm \{} \;
find /tmp/ -name "vi*" -cmin +1 -exec rm \{} \;
find /tmp/ -name "sess_*" -cmin +1 -exec rm \{} \;
find /var/tmp/ -name "sess_*" -cmin +1 -exec rm \{} \;

Date Page Last Modified

<?
$last_modified = filemtime("pagename.php");
print("Last Modified");
print(date("j/m/y h:i", $last_modified));
?>

Getting HTTP Auth to play nice with PHP run under FastCGI

<?php
/**
 * Get HTTP Auth to work with PHP+FastCGI
 *
 * @author  Jacques Marneweck <[email protected]>
 * @license PHP License v3.01
 */

/**
 * Get HTTP Auth to work with PHP+FastCGI
 */

    

if (isset($_SERVER["AUTHORIZATION"]) && !empty($_SERVER["AUTHORIZATION"])) {

    list ($type, $cred) = split (" ", $_SERVER['AUTHORIZATION']);

    if ($type == 'Basic') {
        list ($user, $pass) = explode (":", base64_decode($cred));
        $_SERVER['PHP_AUTH_USER'] = $user;
        $_SERVER['PHP_AUTH_PW'] = $pass;
    }

}

Parse .html files as PHP

To parse files with a .html extension as PHP, add this line to httpd.conf, your VirtualHost container, or .htaccess:
AddHandler application/x-httpd-php .html

You can substitute your own arbitrary file extensions for .html if you want to use, for example, filename.foo on your site.

Disallow serving of PHP pages if mod_php is not loaded

If mod_php doesn't load for some reason, your PHP files may be served unparsed, as plain text. This presents the possibility that your database passwords or other senstive information may be visible. Adding the following to your httpd.conf, VirtualHost container, or .htaccess file will deny access to any PHP files if the PHP module is not loaded.

<IfModule !mod_php4.c>
    <FilesMatch "\.php$">
        Order allow,deny
        Deny from all
        Allow from none
    </FilesMatch>
</IfModule>

Rails and php on directories example of a lighttpd HOST conditional

$HTTP["host"] =~ "textdrive.(org|com)" {
server.indexfiles          = ( "dispatch.fcgi", "index.php" )
server.document-root             = "/users/home/website/web/public/"
url.redirect = ( "^/forum/(.*)" => "http://forum.textdrive.com/$1",
                 "^/support/(.*)" => "http://support.textdrive.com/$1" )
#url.rewrite = ( "^/$" => "index.html", "^([^.]+)$" => "$1.html" )
server.error-handler-404   = "/dispatch.fcgi"
fastcgi.server = (
               ".fcgi" =>
                    ( "localhost" =>
                        (
                            "socket" => "/tmp/textdrive-new.socket",
                            "bin-path" => "/users/home/website/web/public/dispatch.fcgi",
                            "bin-environment" => ( "RAILS_ENV" => "production" )
                        )
                    ),
".php" =>
                    ( "localhost" =>
                        (
                            "socket" => "/tmp/textdrive-php5-fcgi.socket",
                            "bin-path" => "/usr/local/www/cgi-bin/php5-fcgi",
                            "bin-environment" => (
                            "PHP_FCGI_CHILDREN" => "4",
                            "PHP_FCGI_MAX_REQUESTS" => "5000"
                                                 )
                        )
                    )
)
}

How TextDrive does both PHP and Rails FCGI in one thing-a-ma-bob

fastcgi.server = (
".fcgi" =>
                    ( "localhost" =>
                        (
                            "socket" => "/tmp/textdrive-new.socket",
                            "bin-path" => "/users/home/website/web/public/dispatch.fcgi",
                            "bin-environment" => ( "RAILS_ENV" => "production" )
                        )
                    ),
".php" =>
                    ( "localhost" =>
                        (
                            "socket" => "/tmp/textdrive-php5-fcgi.socket",
                            "bin-path" => "/usr/local/www/cgi-bin/php5-fcgi",
                            "bin-environment" => (
                            "PHP_FCGI_CHILDREN" => "4",   
                            "PHP_FCGI_MAX_REQUESTS" => "5000"
                                                 )
                        )       
                    )
)

PHP HTTP Connection class

class HttpConnection {
  private $host;
  private $port;
  private $headers;
  
  public function __construct($host, $port) {
    $this->host    = $host;
    $this->port    = $port;
    $this->headers = new HeaderList(array(), "\r\n");
  }
  
  public function get($path, $params = array(), $headers = array()) {
    return $this->send($path, 'get', $params, $headers);
  }
  
  public function post($path, $params = array(), $headers = array()) {
    return $this->send($path, 'post', $params, $headers);
  }
  
  public static function serialize_auth($user, $pass) {
    return base64_encode("$user:$pass");
  }
  
  public static function serialize_params($params) {
   $query_string = array();
    foreach ($params as $key => $value) {
      $query_string[] = urlencode($key) . '=' . urlencode($value);
    }
    return implode('&', $query_string);
  }
  
  private function send($path, $method, $params = array(), $headers = array()) {  
    $this->headers->add($headers);  
    $params = self::serialize_params($params);
    
    $this->request = strtoupper($method) . " http://{$this->host}{$path}?{$params} HTTP/1.0\r\n";
    $this->request .= $this->headers->to_s() . "\r\n";    

    if ($fp = fsockopen($this->host, $this->port, $errno, $errstr, 15)) {
      if (fwrite($fp, $this->request)) {
        while (!feof($fp)) {
         $this->response .= fread($fp, 4096);
       }
      }
      fclose($fp);
    } else {
      throw new Exception("could not establish connection with $host");
    }
    
    return $this->parse_response();
  }
  
  private function parse_response() {
    $this->response = str_replace("\r\n", "\n", $this->response);
    list($headers, $body) = explode("\n\n", $this->response, 2);
    $headers = new HeaderList($headers);
    return array('headers' => $headers->to_a(), 'body' => $body, 'code' => $headers->get_response_code());
  }
}

class HeaderList {
  private $headers;
  private $response_code;
  private $linebreak;
  
  public function __construct($headers = array(), $linebreak = "\n") {
    $this->linebreak = $linebreak;
    $this->headers   = $headers;
    if (is_string($this->headers)) {
      $this->parse_headers_string();
    }
  }
  
  public function to_s() {
    $headers = '';
    foreach ($this->headers as $header => $value) {
      $headers .= "$header: $value{$this->linebreak}";
    }
    return $headers;
  }
  
  public function to_a() {
    return $this->headers;
  }
  
  public function __toString() {
    return $this->to_s();
  }
  
  public function add($headers) {
    $this->headers = array_merge($this->headers, $headers);
  }
  
  public function get($header) {
    return $this->headers[$header];
  }
  
  public function get_response_code() {
    return $this->response_code;
  }
  
  private function parse_headers_string() {
    $replace = ($this->linebreak == "\n" ? "\r\n" : "\n");
    $headers = str_replace($replace, $this->linebreak, trim($this->headers));
    $headers = explode($this->linebreak, $headers);
    $this->headers = array();
    if (preg_match('/^HTTP\/\d\.\d (\d{3})/', $headers[0], $matches)) {
      $this->response_code = $matches[1];
      array_shift($headers);
    }
    foreach ($headers as $string) {
      list($header, $value) = explode(': ', $string, 2);
      $this->headers[$header] = $value;
    }
  }
}

Random Number

$randomnumber= rand(1,10);


Replace 1 and 10 with the range you want to pick a number between.
« Newer Snippets
Older Snippets »
Showing 61-80 of 106 total