PHP 带有域名的Cookie包装器

class Cookie
{
   var $__setting;

   function __construct($name = 'FuseLogic',$live = 31104000)
   {
      $this->__setting = new open();
      $this->__setting->name = $name;
      $this->__setting->_cookies = array();
      $this->__setting->space = '___';

      $this->setDomain();
      $this->setPath();
      $this->setLive($live);

      if(is_array($_COOKIE))
      {
         foreach($_COOKIE as $k =>$v)
         {
            $temp = explode($this->__setting->space,$k);
            if($temp[0] == $this->__setting->name)
            {
               $k = str_replace($this->__setting->name.$this->__setting->space,'',$k);
               $this->__setting->_cookies[$k] = $v;
            }
         }
      }
   }
    
   function setDomain($domain = '')
   {
      $this->__setting->domain = $domain;
   }

   function setLive($time = 3600)
   {
      $this->__setting->live = (int) $time;
   }

   function setPath($path = '/')
   {
      $this->__setting->path = $path;
   }

   function name($name = null)
   {
      return $this->__setting->name.$this->__setting->space.$name;
   }

   public function __get($name)
   {
      return $this->__setting->_cookies[$name];
   }
  
   public function __set($name,$value)
   {
      $this->__setting->_cookies[$name] = $value;
      $name = $this->name($name);
      $_COOKIE[$name] = $value;
      if($value == null)
      {
         setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
      }else
      {
         setcookie($name,$value,time()+$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
      }
   }

   public function __isset($name)
   {
      return isset($this->__setting->_cookies[$name]);
   }

   function clean()
   {
      foreach($this->__setting->_cookies as $name => $value)
      {
         $name = $this->name($name);
         setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
         @$_COOKIE[$name] = null;
      }
      $this->__setting->_cookies = array();
   }

   function cleanAll()
   {
      foreach($_COOKIE as $name => $value)
      {
         setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
      }
      @$_COOKIE = array();
   }

   function toArray()
   {
      return $this->__setting->_cookies;
   }

   function fromArray($a = null)
   {
      if(is_array($a))
      {
         foreach($a as $k => $v ) $this->$k = $v;
      }
   }

}

PHP PHP函数示例

/*
Título:     Explicación de funciones (básica)
Autor:         Angel Velásquez (a.k.a angvp)
E-Mail:        angelvelasquez@gmail.com
Web:        http://www.anacosoft.com
Fecha:         02/01/2006
Licencia:     Creative Commons j/k (BAHHH GNU MY FRIEND!)
======================================================
Las funciones usualmente son pequeñas partes de un script usadas para devolver resultados, ¿Lógico no?, pero la idea es que entiendan el correcto uso de las mismas.

*/

function holamundo() {
    return "Hola Mundo!";
}
/*
Esa es la clásica Hola Mundo, ahora llevada a función (es como inútil una función tan corta), aunque en cierto y sólo ciertos casos, nos ahorraría mucho para ahorrar código, pero, este no es el caso, el caso es que a esta función no hay que pasarle parámetros para que se ejecute, con sólo poner echo holamundo(); se verá reflejado en pantalla "Hola Mundo!".
*/
function holamundov2($nombre) {
    $var = "Hola $nombre . Bienvenido al mundo!";
    return $var;
}

/*
 Para ejecutar esa función se requiere pasarle un parámetro, su correcta ejecución sería así:
 echo holamundov2("Pepe"), como salida obtendríamos Hola Pepe . Bienvenido al mundo!.
 
 Bien, no siempre las funciones dependen de parámetros, o podemos decirle que sino le pasamos un parámetro, ella misma lo declare, ¿Cómo?, muy sencillo, en el próximo ejemplo, lo veremos.
*/

function holamundov3($nombre = "Pepe") {
    $var = "Hola $nombre . Bienvenido al mundo!";
    return $var;
}

/*
En el caso de holamundov3, es distinto, la función comprueba si se le pasó un parámetro, en caso de no haberse pasado un parámetro ($nombre), ella asignará automáticamente, Pepe, también es útil, la idea de hacer funciones es hacer funciones genéricas que nos ahorren trabajo, no hacer mil funciones personalizadas (aunque sea más fácil).

FAQ:
====
1.- Q: Si pongo echo en vez de return también funciona...
    A: Si, funciona, pero y si quieres guardar el resultado en una variable y luego concatenarlo con otra cosa.. unuseful...
2.- Q: ¿Tengo que poner siempre return?
    A: Sí, si vas a usar una función con condiciones te recomiendo que guardes el resultado de la condición positiva o negativa en una variable (con el mismo nombre) ejemplo:
   
    function holamundov4($nombre = "Pepe") {
        if ($nombre == "Pepe") {
            $var = "Hola Mundo!";
        }
        else {
            $var = "Hola $nombre . Bienvenido al mundo!";
        }
        return $var;
    }
   
Enjoy the tutorial, sorry que no fui más específico

Angel
*/

PHP smart_trim

#################################################
####
#### smart_trim
#### This function trims a string to a specified length.
#### Words are separated by space characters, and they are not
#### chopped if possible.
#### 
#### @package smart_trim
#### @author  Michael Gauthier <mike@silverorange.com>
#### silverorange
#### labs.silverorange.com
#### 
#### Copyright (c) 2003, silverorange Inc.
#### All rights reserved.
#### 
#### Redistribution and use in source and binary forms, with or without modification,
#### are permitted provided that the following conditions are met:
#### 
####     * Redistributions of source code must retain the above copyright notice, this
####       list of conditions and the following disclaimer.
####     * Redistributions in binary form must reproduce the above copyright notice,
####       this list of conditions and the following disclaimer in the documentation
####       and/or other materials provided with the distribution.
####     * Neither the name of silverorange Inc. nor the names of its contributors may
####       be used to endorse or promote products derived from this software without
####       specific prior written permission.
#### 
#### THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#### ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#### WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#### IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
#### INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
#### BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#### DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#### LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
#### OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
#### OF THE POSSIBILITY OF SUCH DAMAGE.
#### 
#################################################

/**
 * Trim the string.
 *
 * @param  string  $text        The line to trim.
 * @param  integer $max_len     The maximum length of the trimmed line.
 *                              This ignores the length of the characters
 *                              that indicate trimming has occured.
 * @param  boolean $trim_middle Trimming takes place in the middle of the line
 *                              iff true. Otherwise, the line is trimmed at the
 *                              end. Defaults to false.
 * @param  string  $trim_chars  Characters to use to indicate trimming has
 *                              occured. Defaults to '...'.
 *
 * @return string               The trimmed line of text.
 */
function smart_trim($text, $max_len, $trim_middle = false, $trim_chars = '...')
{
	$text = trim($text);

	if (strlen($text) < $max_len) {

		return $text;

	} elseif ($trim_middle) {

		$hasSpace = strpos($text, ' ');
		if (!$hasSpace) {
			/**
			 * The entire string is one word. Just take a piece of the
			 * beginning and a piece of the end.
			 */
			$first_half = substr($text, 0, $max_len / 2);
			$last_half = substr($text, -($max_len - strlen($first_half)));
		} else {
			/**
			 * Get last half first as it makes it more likely for the first
			 * half to be of greater length. This is done because usually the
			 * first half of a string is more recognizable. The last half can
			 * be at most half of the maximum length and is potentially
			 * shorter (only the last word).
			 */
			$last_half = substr($text, -($max_len / 2));
			$last_half = trim($last_half);
			$last_space = strrpos($last_half, ' ');
			if (!($last_space === false)) {
				$last_half = substr($last_half, $last_space + 1);
			}
			$first_half = substr($text, 0, $max_len - strlen($last_half));
			$first_half = trim($first_half);
			if (substr($text, $max_len - strlen($last_half), 1) == ' ') {
				/**
				 * The first half of the string was chopped at a space.
				 */
				$first_space = $max_len - strlen($last_half);
			} else {
				$first_space = strrpos($first_half, ' ');
			}
			if (!($first_space === false)) {
				$first_half = substr($text, 0, $first_space);
			}
		}

		return $first_half.$trim_chars.$last_half;

	} else {

		$trimmed_text = substr($text, 0, $max_len);
		$trimmed_text = trim($trimmed_text);
		if (substr($text, $max_len, 1) == ' ') {
			/**
			 * The string was chopped at a space.
			 */
			$last_space = $max_len;
		} else {
			/**
			 * In PHP5, we can use 'offset' here -Mike
			 */
			$last_space = strrpos($trimmed_text, ' ');
		}
		if (!($last_space === false)) {
			$trimmed_text = substr($trimmed_text, 0, $last_space);
		}
		return remove_trailing_punctuation($trimmed_text).$trim_chars;

	}

}

/**
 * Strip trailing punctuation from a line of text.
 *
 * @param  string $text The text to have trailing punctuation removed from.
 *
 * @return string       The line of text with trailing punctuation removed.
 */
function remove_trailing_punctuation($text)
{
	return preg_replace("'[^a-zA-Z_0-9]+$'s", '', $text);
}

PHP ViewController格式日期回调

function vc_format_create_date($table, $val, $row) { return date("m/d/Y", strtotime($val)); }

PHP FuseLogic - 依赖注入的Lite版本

//PHP5 only
class fuselogic_container
{
   var $__x = array();

   function __construct($path = null)
   {
      static $instances = array();
      $class_name = strtolower(get_class($this));
      if(!isset($instances[$class_name]))
      {
         $instances[$class_name] = $this;
      }
      foreach(get_class_vars($class_name) as $var => $value)
      {
         $this->$var = &$instances[$class_name]->$var;
      }
      $this->__path = isset($path)?$path:getcwd();
   }

   function __get($name)
   {
       $lowercase = strtolower($name);
       if(isset($this->__x[$lowercase]))
       {
          return $this->__x[$lowercase];
       }else
       {
          $this->__x[$lowercase] = $this->$name();
          $instance = &$this->__x[$lowercase];
          return $instance;
       }
   }

   function __call($name,$var)
   {
       if(class_exists($name))
       {
          if(isset($var[0]))
          {
             return new $name($var[0]);
          }else
          {
             return new $name();
          }
       }else
       {
          $this->_start();
          if(@include_once('class.'.$name.'.php'))
          {
             return new $name();
          }
          $this->_end();
       }
   }

   function _start()
   {
      $this->__path_back = getcwd();
      chdir($this->__path);
   }

   function _end()
   {
      chdir($this->__path_back);
   }

   function __set($name,$val)
   {
       $this->__x[$name] = $val;
   }

   function __isset($name)
   {
      $name = strtolower($name);
      if(isset($this->__x[$name]))
      {
         return true;
      }elseif(method_exists($this,$name))
      {
         return true;
      }else return false;
   }
}

PHP Php validar rango de codigos

function validarCodigoReferencia( $str, $pais ){
	global $conn, $paises;
	$str = strtoupper( $str );
	#Primero, que tenga 6 caracteres, sino afuera de con el pichicho.
	if( strlen( $str ) != 6 ){
		return false;
	}else{
		#Dividimos en dos, limpiamos la primer parte de todo lo que no sea letras y la segunda de todo lo que no sea número
		$primeraParte = soloLetras( substr( $str, 0, 3 ) );
		$segundaParte = soloNum( substr( $str, 3, 6 ) );
		#echo $primeraParte . "-" . $segundaParte;
		#Con estas partes generamos un nuevo str
		$strNew = $primeraParte . $segundaParte;
		#Y si no quedo de 6 no es valido.
		if( strlen( $strNew ) != 6 ){
			return false;
		}else{
			#Si quedo de 6 es que es de 3 letras + 3 numeros. Veamos si está en el rango del pais
			$rangoDesde = ord( $paises[$pais]["rangoDesde"] );
			$rangoHasta = ord( $paises[$pais]["rangoHasta"] );
			$esteRango = ord( $strNew{0} );
			#echo $rangoDesde . '-' . $rangoHasta .'-'. $esteRango;
			if( $esteRango > $rangoHasta || $esteRango < $rangoDesde ){
				return false;
			}else{
				return true;
			}
		}
	}
}

PHP PHP-信息

<?

echo phpinfo();

?>

PHP Php extraer mayor valor de un array

function mayorValor( $array ){
	$a = array_unique( $array );
	$s = 0;
	if( is_array( $a ) )
		foreach( $a as $v )
			$s = intval( $v ) > $s ? $v : $s;
	return $s;
}

$arr = array(9,3,5,6,7,8,99,9,7,8,9,4);
echo mayorValor( $arr ) #out 99

PHP ITwebinfo.com - 调整jpeg图像的大小

<?

/*this can be used to resize image in jpeg format only
which provive a good quality thumbnails*/
// This is the temporary file created by PHP

$uploadedfile = $_FILES['simage']['tmp_name'];

// Create an Image from it so we can do the resize
$src = imagecreatefromjpeg($uploadedfile);

// Capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);
$newwidth=300;
//$newheight=($height/$width)*100;
$newheight=200;
$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = $_FILES['simage']['name'];
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp);
?>

PHP 读取原始发布数据,对于从Flash XmlSocket中获取XML非常有用。

/**
     Using php://input
     -----------------
     Version: 4.3+
     
     Reading [php://input][1] is the preferred method since PHP 4.3.
     
     The Content-Type header of the posted content must _NOT_ be 
     application/x-www.form-urlencoded or multipart/form-data.
     
     For XML you can use the Content-Type: text/xml.
     
      [1]: http://us2.php.net/manual/en/wrappers.php.php
    */

    // Make sure the user is posting
    if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
    {
        // Read the input from stdin
        $postText = trim(file_get_contents('php://input'));
    }
  
    /**
     Using $HTTP_RAW_POST_DATA
     -------------------------
     Version 3.0+
     
     __Note__: Reading php://input is preferred.
     
     
     As with php://input, the Content-Type header of the 
     posted content must _NOT_ be application/x-www.form-urlencoded or
     multipart/form-data.     
     
     PHP 4.1+
     ~~~~~~~~
     You can also enable [always-populate-raw-post-data][1] in the php.ini to
     have the value always populated reguardless of Content-Type. However
     since this requires config changes it is less portable.
     
      [1]: http://us2.php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data
    */
    $postText = $GLOBALS['HTTP_RAW_POST_DATA'];