PHP 邮政编码验证

<?php
/*==============================================================================
Application:   Utiity Function
Author:        John Gardner

Version:       V1.0
Date:          25th December 2004
Description:   Used to check the validity of a UK postcode

Version:       V2.0
Date:          8th March 2005
Description:   BFPO postcodes implemented.
               The rules concerning which alphabetic characters are alllowed in 
               which part of the postcode were more stringently implementd.
  
Parameters:    $postcode - postcodeto be checked. This is returned reformatted 
                           if valid.

This function checks the value of the parameter for a valid postcode format. The 
space between the inward part and the outward part is optional, although is 
inserted if not there as it is part of the official postcode.

The functions returns a value of false if the postcode is in an invalid format, 
and a value of true if it is in a valid format. If the postcode is valid, the 
parameter is loaded up with the postcode in capitals, and a space between the 
outward and the inward code to conform to the correct format.
  
Example call:
  
    if (!checkPostcode($postcode) ) {
      echo 'Invalid postcode <br>';
    }
                    
------------------------------------------------------------------------------*/
function checkPostcode (&$toCheck) {

  // Permitted letters depend upon their position in the postcode.
  $alpha1 = "[abcdefghijklmnoprstuwyz]";                          // Character 1
  $alpha2 = "[abcdefghklmnopqrstuvwxy]";                          // Character 2
  $alpha3 = "[abcdefghjkstuw]";                                   // Character 3
  $alpha4 = "[abehmnprvwxy]";                                     // Character 4
  $alpha5 = "[abdefghjlnpqrstuwxyz]";                             // Character 5
  
  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  $pcexp[0] = '^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([0-9]{1}'.$alpha5.'{2})$';

  // Expression for postcodes: ANA NAA
  $pcexp[1] =  '^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([0-9]{1}'.$alpha5.'{2})$';

  // Expression for postcodes: AANA NAA
  $pcexp[2] =  '^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([0-9]{1}'.$alpha5.'{2})$';
  
  // Exception for the special postcode GIR 0AA
  $pcexp[3] =  '^(gir)(0aa)$';
  
  // Standard BFPO numbers
  $pcexp[4] = '^(bfpo)([0-9]{1,4})$';
  
  // c/o BFPO numbers
  $pcexp[5] = '^(bfpo)(c\/o[0-9]{1,3})$';

  // Load up the string to check, converting into lowercase and removing spaces
  $postcode = strtolower($toCheck);
  $postcode = str_replace (' ', '', $postcode);

  // Assume we are not going to find a valid postcode
  $valid = false;
  
  // Check the string against the six types of postcodes
  foreach ($pcexp as $regexp) {
  
    if (ereg($regexp,$postcode, $matches)) {
      
      // Load new postcode back into the form element  
      $toCheck = strtoupper ($matches[1] . ' ' . $matches [2]);
      
      // Take account of the special BFPO c/o format
      $toCheck = ereg_replace ('C\/O', 'c/o ', $toCheck);
      
      // Remember that we have found that the code is valid and break from loop
      $valid = true;
      break;
    }
  }
    
  // Return with the reformatted valid postcode in uppercase if the postcode was 
  // valid
  if ($valid){return true;} else {return false;};
}
?>

PHP 消息堆栈

<?php

	/**
	 *
	 * @author	MJB
	 * @date	18/01/06
	 * @desc	MessageStack & Message class - Error/Warning handling
	 * @ver		1.6
	 *
	 * @notes	* since the stack only exists for a single request-response
	 *			  the object never needs to be manually cleared of messages
	 *			* smarty frontend
	 *			* now does static methods and line numbers
	 */


	class MessageStack {

		var $_msgs;

		function MessageStack() {}
		
		/**
		 *	@desc	create new message on stack
		 *	@params	overriden message if error passed from outside (ie Pear)
		 */
		function add($source_class, $line_num, $error_code, $message="") {
			$this->_msgs[] = &new Message($source_class, $line_num, $error_code, $message);
		}


		/**
		 *	@desc	parse Message objects into array for smarty
		 */
		function display() {
			if(!isset($this->_msgs)) { return array(); }
			
			foreach($this->_msgs as $msg) {
				$output[] = array("class" => $msg->getClass(), 
								  "code" => $msg->getCode(), 
								  "line" => $msg->getLine(), 
								  "message" => $msg->getMessage(), 
								  "link" => $msg->getLink());
			}
			return $output;
		}

		function hasErrors() {
			return count($this->_msgs);
		}

	}


	class Message {

		var $_classMethod;	//source class name & getMessage method
		var $_line;		//erronous line
		var $_code;		//error code translates to a message
		var $_message;		//error message
		var $_link;		//link to solution

		function Message($source, $line, $code, $msg="") {
			$this->_classMethod = array($source, "getMessage");
			$this->_line = $line;
			$this->_code = $code;
			$this->_link = "";

			//use passed msg or attempt to get from calling class
			if(strlen($msg)>0) {
				$this->_message = $msg;

			}elseif(is_callable($this->_classMethod)) {
				//call getMessage on object statically
				$tmp = call_user_func($this->_classMethod, $code);

				//parse message & link if given
				if(count($tmp)==2) {
					$this->_message = $tmp['text'];
					$this->_link = $tmp['link'];
				}else{
					$this->_message = $tmp['text'];
				}

			}else{
				$this->_message = "Undefined error message";
			}
		}

		function getClass() {
			return $this->_classMethod[0];
		}
		function getLine() {
			return (DEBUG) ? $this->_line : "";
		}
		function getCode() {
			return $this->_code;	//code for info/error
		}
		function getMessage() {
			return $this->_message;
		}
		function getLink() {
			return $this->_link;
		}

	}

?>

PHP 交换结构的多个案例

switch (value)
  
          {
 
          case 1:
 
              echo "Value was 1";
  
              break;
  
          case 2:
   
          case 3:
  
              echo "Value was 2 or 3";
  
              break;

          case 4: 

              echo "Value was 4";
 
              break;

          default:   
  
              echo "Value was not 1-4";
  
              break;
  
          }

PHP 从网络发送电子邮件

<?php
      $email = "test@test.de";

      /* Absender */
      $absender = "Testuser <".$email.">";
      /* Rueckantwort */
      $reply = $email;
      /* Betreff */
      $subject = "Kontaktformular";

      /* Nachricht */
      $message = '
      <html>
          <head>
              <title>BlaBla</title>
          </head>
          <body bgcolor="#ff4500" link="#FFD700" vlink="#FFD700" alink="#ff7813">
              <table width="500" border="0" cellspacing="5" cellpadding="5">
                  <tr>
                      <td>
                          <p>Inhalt der Email</p>
                      </td>
                  </tr>
              </table>
          </body>
      </html>
      ';
      /* Baut Header der Mail zusammen */
      $headers .= "From: $absender";
      $headers .= "Reply-To:$reply";
      $headers .= "X-Mailer: PHP/".phpversion()."";
      $headers .= "X-Sender-IP: $REMOTE_ADDR";
      $headers .= "Content-type: text/html";

      /* Verschicken der Mail */
      if(mail($email, $subject, $message, $headers)) echo "<tr><td><p>Ihre Nachricht wurde erfolgreich verschickt.</p></td></tr>";
?>

PHP 简单的UUID

function uuid($length=32) {
	mt_srand((double)microtime()*1000000);
	$r = strtoupper(md5(time().$_SERVER["REMOTE_ADDR"].$_SERVER["UNIQUE_ID"].mt_rand(0,9999)));
	if ($length<32){ $r=substr($r,0,$length-1); }	
	return $r;	
}

PHP 自动化Snipplr spambot保护

<?

$q = "What does seven * eight equal?";


$word_numbers = array("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen");
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);

$q = str_ireplace($word_numbers, $numbers, $q);

$word_signs = array("plus", "minus", "times", "x", "divided");
$signs = array("+", "-", "*", "*", "/");

$q = str_ireplace($word_signs, $signs, $q);

preg_match("!(\d{1,3}) ([^~]*?) (\d{1,3})!", $q, $out);

$first_number = $out[1];
$second_number = $out[3];

switch($out[2]) {
	case '+' :
		$answer = $first_number+$second_number;
	break;
	
	case '-' :
		$answer = $first_number-$second_number;
	break;
	
	case '*' :
		$answer = $first_number*$second_number;
	break;
	
	case '/' :
		$answer = $first_number/$second_number;
	break;
	
	default : 
		$answer = "Failed";
	break;	
}

echo $answer;

?>

PHP 将变量转储到字符串。

ob_start();
var_dump($my_variable);
$my_string = ob_get_contents();
ob_end_clean();

PHP PHP - 12小时到24小时

function hours12ToTimestamp24( $hora ){
	#Saco solo hora y min en un array
	$horaArray = explode(":", $hora);
	if( sizeof( $horaArray ) < 2 ) return 0;
	#Si tiene pm en el string le sumo 12 hs al mod de la hora sobre 12.
	$extra = strstr(strtolower($hora), 'pm') || strstr(strtolower($hora), 'p.m')? 12 : 0;
	return mktime(($horaArray[0]%12)+$extra, $horaArray[1], 0, 1, 1, 1970 );
}

PHP tmpl.inc-的header.php

<?php

	global $DB, $SESS;
	
	$show_access_debug = false;
	
	// Check to see if a) group has privileges to access QDB, and b) user has privileges to access QDB
	$query = "SELECT exp_qdb_group_privileges.group_can_access_qdb FROM exp_qdb_group_privileges WHERE " .
		"exp_qdb_group_privileges.group_id = '" . $SESS->userdata['group_id'] . "'";
	$result = $DB->query($query);
	$group_can_access_qdb = 1;
	if ($result->num_rows > 0)
		$group_can_access_qdb = intval($result->row['group_can_access_qdb']);
	
	$query = "SELECT exp_qdb_member_privileges.member_can_access_qdb FROM exp_qdb_member_privileges WHERE " .
		"exp_qdb_member_privileges.member_id = '" . $SESS->userdata['member_id'] . "'";
	$result = $DB->query($query);
	$member_can_access_qdb = 1;
	if ($result->num_rows > 0)
		$member_can_access_qdb = intval($result->row['member_can_access_qdb']);
	
	$can_access_qdb = 1;
	if ($group_can_access_qdb >0 && $member_can_access_qdb <= 0)
		$can_access_qdb = 0;
	else if ($group_can_access_qdb <= 0 && $member_can_access_qdb > 0)
		$can_access_qdb = 1;
	else if ($group_can_access_qdb <= 0 && $member_can_access_qdb <= 0)
		$can_access_qdb = 0;
	
	if (!$can_access_qdb)
		$FNS->redirect('');
	
	// Check to see if member has privileges to submit quotes
	if ($can_access_qdb) {
		$query = "SELECT exp_qdb_group_privileges.group_can_add_quotes from exp_qdb_group_privileges WHERE " .
			"exp_qdb_group_privileges.group_id = '" . $SESS->userdata['group_id'] . "'";
		$result = $DB->query($query);
		$group_can_add_quotes = 1;
		if ($result->num_rows > 0)
			$group_can_add_quotes = intval($result->row['group_can_add_quotes']);
		
		$query = "SELECT exp_qdb_member_privileges.member_can_add_quotes from exp_qdb_member_privileges WHERE " .
			"exp_qdb_member_privileges.member_id = '" . $SESS->userdata['member_id'] . "'";
		$result = $DB->query($query);
		$member_can_add_quotes = 1;
		if ($result->num_rows > 0)
			$member_can_add_quotes = intval($result->row['member_can_add_quotes']);
		
		$can_add_quotes = 1;
		if ($group_can_add_quotes > 0 && $member_can_access_qdb <= 0)
			$can_add_quotes = 0;
		else if ($group_can_add_quotes <= 0 && $member_can_add_quotes > 0)
			$can_add_quotes = 1;
		else if ($group_can_add_quotes <= 0 && $member_can_add_quotes <= 0)
			$can_add_quotes = 0;
	}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>Disciples of Bork - Quote Database</title>
	<link rel="stylesheet" type="text/css" media="all" href="{stylesheet=qdb/css_screen}" />
</head>
<body>
	<div id="wrapper">
		
		<div id="header"><h1>
				Quote Database <span class="version">Some things people have said</span>
				<span id="nav"> <?php if ($can_access_qdb && $can_add_quotes): ?><a href="{path=qdb/submit}">Submit a Quote</a><?php endif; ?></span>
		</h1></div>
		
		<!-- Access debug information -->
		<?php if ($show_access_debug): ?>
			<div style="display: block; width: 49%; float: left;">
				<h2>QDB Access</h2>
				<ul>
					<li><b>$group_can_access_qdb</b> = <?=$group_can_access_qdb;?></li>
					<li><b>$member_can_access_qdb</b> = <?=$member_can_access_qdb;?></li>
					<li><b>$can_access_qdb</b> = <?=$can_access_qdb;?></li>
				</ul>
			</div>
		
			<div style="display: block; width: 49%; float: right;">
				<h2>Submit Quote Access</h2>
				<ul>
					<li><b>$group_can_add_quotes</b> = <?=$group_can_add_quotes;?></li>
					<li><b>$member_can_add_quotes</b> = <?=$member_can_add_quotes;?></li>
					<li><b>$can_add_quotes</b> = <?=$can_add_quotes;?></li>
				</ul>
			</div>
		<?php endif; ?>

PHP 旋转头像

/*
rotating avatars
create a directory on your webserver, call it avatars and put a few avatars in it, along with this file. (index.php)
( make sure the avatars are about the same size, and preferably square ( width == height ) )
check http://www.yourdomain.com/avatars/ to see the result. Refresh the page to see another avatar.
*/

function listImages ( )//reads images in current directory, returns array with filenames
{
	$allowed_extensions = array ( ".jpg", ".png", ".gif" );
	$dir = opendir ( getcwd ( ) );
	while ( $file = readdir ( $dir ) )
	{
		$extension = strtolower ( substr ( $file, strlen ( $file ) - 4, strlen ( $file ) ) );
		if ( in_array ( $extension, $allowed_extensions ) ) $linklist[] = $file;
	}
	closedir ( $dir );
	return $linklist;
}
function mkImg ( $file, $ftype )//returns an image with filetype $ftype, sourceimage is $file
{
	$img = imagecreatefromstring ( file_get_contents ( $file ) );
 	switch ( $ftype )
 	{
		case ".jpg":
			header('Content-Type: image/jpg');
			imagejpeg($img);
			break;
		case ".gif":
			header('Content-Type: image/gif');
	  		imagegif($img);
			break;
		case ".png":
		default:
			header('Content-Type: image/png');
	  		imagepng($img);
			break;
	}
}
//read the images in the current directory
$images = listImages ( );
//pick a random one
$rnd = $images[array_rand ( $images )];
//for use on forums -> link to /path/to/index.php?ftype=.jpg (fools SOME forum software into thinking it's a jpg)
$ftype = $_REQUEST['ftype'] ? $_REQUEST['ftype'] : ".png";
//return the randomly picked image
mkImg ( $rnd, $ftype );