常用函数

变为时间戳strtotime(time,now):

strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳。

echo(strtotime("now"));echo(strtotime("3 October 2005"));echo(strtotime("+5 hours"));

添加数组array_push(array,value1,value2...)

函数向第一个参数的数组尾部添加一个或多个元素(入栈),然后返回新数组的长度。

该函数等于多次调用 $array[] = $value

$a=array("Dog","Cat");array_push($a,"Horse","Bird");print_r($a);

返回包含数组中所有键名的一个新数组:array_keys(array,value)

$a=array("a"=>"Horse","b"=>"Cat","c"=>"Dog");print_r(array_keys($a));     //Array ( [0] => a [1] => b [2] => c )

销毁指定的变量void unset ( mixed $var [, mixed $... ] )

// 销毁单个变量   unset ($foo);

// 销毁单个数组元素   unset ($bar['quux']);

// 销毁一个以上的变量   unset($foo1, $foo2, $foo3);

如果在函数中 unset() 一个全局变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset() 之前一样的值。

function foo() {    unset($GLOBALS['bar']);     }   $bar = "something";

如果在函数中 unset() 一个通过引用传递的变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset()之前一样的值。

如果在函数中 unset() 一个静态变量,那么在函数内部此静态变量将被销毁。但是,当再次调用此函数时,此静态变量将被复原为上次被销毁之前的值。

function foo(){    static $bar;   $bar++;   echo "Before unset: $bar, ";   unset($bar);    $bar = 23;    echo "after unset: $bar ";  }   

foo();   //Before unset: 1, after unset: 23

foo();  //Before unset: 2, after unset: 23

 foo();  //Before unset:3, after unset: 23

强制转换  $name = 'Felipe';    var_dump((unset) $name);  //null

             var_dump($name);   //string(6) "Felipe"

进一法取整float ceil ( float $value )

echo ceil(-3.14);  // -3

eq相等   ne、neq不相等,   gt大于, lt小于 gte、ge大于等于   lte、le 小于等于   not非   mod求模   is [not] div by是否能被某数整除   is [not] even是否为偶数   is [not] even by $b即($a / $b) % 2 == 0   is [not] odd是否为奇   is not odd by $b即($a / $b) % 2 != 0 示例:equal/ not equal/ greater than/ less than/ less than or equal/ great than or equal/后面的就不用说了

检测变量是否设置,并且不是 NULL   bool isset ( mixed $var [, mixed $... ] )

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));
var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

$var = '';   isset($var)// 结果为 TRUE

unset ($a);   var_dump(isset($a));     // FALSE

返回文件路径的信息:mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], " ";   //   /www/htdocs/inc
echo $path_parts['basename'], " ";     //lib.inc.php
echo $path_parts['extension'], " ";     //php
echo $path_parts['filename'], " "; // since PHP 5.2.0    lib.inc   

计算数组中的单元数目或对象中的属性个数:count(array,mode)

对于数组,返回其元素的个数,对于其他值,返回 1

$people = array("Peter", "Joe", "Glenn", "Cleveland");$result = count($people);    //4

 获取变量的整数值 int intval ( mixed $var [, int $base = 10 ] )

echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34

时间减法:(  strtotime( $time )-time()  ) /3600/24

去除字符串首尾处的空白字符:string trim ( string $str [, string $charlist = "  x0B" ] )

 对浮点数进行四舍五入:float round ( float $val [, int $precision ] )

echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000

instanceof :判断一个对象是否是某个类的实例,(2)判断一个对象是否实现了某个接口。属于 类型运算符

class ParentClass{    }

class MyClass extends ParentClass{   }

$a = new MyClass;

var_dump($a instanceof MyClass); //bool(true)

var_dump($a instanceof ParentClass);  //bool(true)

字符串按要求的字符编码来转换:将字符串 str 从 in_charset 转换编码到 out_charset

string iconv ( string $in_charset , string $out_charset , string $str )  

注意:第二个参数,除了可以指定要转化到的编码以外,还可以增加两个后缀://TRANSLIT 和 //IGNORE,其中 //TRANSLIT 会自动将不能直接转化的字符变成一个或多个近似的字符,//IGNORE 会忽略掉不能转化的字符,而默认效果是从第一个非法字符截断。 

使用发现iconv在转换字符”—”到gb2312时会出错,如果没有ignore参数,所有该字符后面的字符串都无法被保存。不管怎么样,这个”—”都无法转换成功,无法输出。 另外mb_convert_encoding没有这个bug.  一般情况下用 iconv,只有当遇到无法确定原编码是何种编码,或者iconv转化后无法正常显示时才用mb_convert_encoding 函数. 

      iconv不是php的默认函数,也是默认安装的模块。需要安装才能用的。 如果是windows2000+php,你可以修改php.ini文件,将extension=php_iconv.dll前的";"去掉,同时你要copy你的原php安装文件下的iconv.dll到你的winnt/system32下(如果你的dll指向的是这个目录) 在linux环境下,用静态安装的方式,在configure时加多一项 --with-iconv就可以了,phpinfo看得到iconv的项。(Linux7.3+Apache4.06+php4.3.2), 

$newdata=iconv('UTF-8', 'GBK', $data);

echo iconv('GB2312', 'UTF-8', $str); //将字符串的编码从GB2312转到UTF-8 
echo iconv_substr($str, 1, 1, 'UTF-8'); //按字符个数截取而非字节 
print_r(iconv_get_encoding()); //得到当前页面编码信息 
echo iconv_strlen($str, 'UTF-8'); //得到设定编码的字符串长度 

Fopen--打开文件或者 URL: resource fopen ( string $filename , string $mode [, bool $use_include_path = false [,resource $context ]] )

'r' 只读方式打开,将文件指针指向文件头。 'r+' 读写方式打开,将文件指针指向文件头。

'w' 写入方式打开,将文件指针指向文件头并将文件大小截为零。如文件不存在则尝试创建。

'w+' 读写方式打开,将文件指针指向文件头并将文件大小截为零。如文件不存在则尝试创建。

'a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建。

'a+' 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建。

'x'   ’c'    'c+'

fwrite — 写入文件 fwrite()  string 的内容写入 文件指针 handle 处

int fwrite ( resource $handle , string $string [, int $length ] )

fclose — 关闭一个已打开的文件指针  bool fclose ( resource $handle )

$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

rmdir -- 删除目录bool rmdir ( string dirname )

 该目录必须是空的,而且要有相应的权限。如果成功则返回 TRUE,失败则返回 FALSE。

function remove_directory($dir) {
  if ($handle = opendir("$dir")) {
   while (false !== ($item = readdir($handle))) {
     if ($item != "." && $item != "..") {
       if (is_dir("$dir/$item")) {
         remove_directory("$dir/$item");  } else {
         unlink("$dir/$item");
         echo " removing $dir/$item<br> ";}     }   }
   closedir($handle);
   rmdir($dir);
   echo "removing $dir<br> ";  }}
remove_directory("/path/to/dir");

file_put_contents — 将一个字符串写入文件 和依次调用 fopen()fwrite() 以及 fclose() 功能一样。

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource$context ]] )

$file = 'people.txt';// Open the file to get existing content
$current = file_get_contents($file);// Append a new person to the file
$current .= "John Smith "; // Write the contents back to the file
file_put_contents($file, $current);

file_get_contents — 将整个文件读入一个字符串string file_get_contents ( string $filename [, bool $use_include_path = false [, resource$context [, int $offset = -1 [, int $maxlen ]]]] )

      和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE。file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

$file = file_get_contents('http://www.example.com/', false, $context);

list() 函数用数组中的元素为一组变量赋值。list(var1,var2...)

注释:该函数只用于数字索引的数组,且假定数字索引从 开始。

$my_array = array("Dog","Cat","Horse");list($a, , $c) = $my_array;echo "$a and $c ";//the Dog and Horse.

Json_encode对变量进行 JSON 编码 str json_encode ( mixed $value [, int $options=0 ] ) 

返回 value 值的 JSON 形式 或false;该函数只能接受 UTF-8 编码的数据 

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); //{"a":1,"b":2,"c":3,"d":4,"e":5}

Json_decodeJSON格式字符串进行编码 ,接受一个 JSON 格式的字符串并且把它转换为 PHP 变量 

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0]]] )

assoc该参数为 TRUE 时,将返回 array 而非 object 。 

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));  //object(stdClass)#1 (5) {["a"] => int(1)  ["b"] => int(2)  ["c"] => int(3)  ["d"] => int(4)  ["e"] => int(5)}

mysql_fetch_assoc — 从结果集中取得一行作为关联数组array mysql_fetch_assoc ( resource $result )

返回对应结果集的关联数组,并且继续移动内部数据指针。 mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二个可选参数 MYSQL_ASSOC 完全相同。它仅仅返回关联数组,如果没有更多行则返回 FALSE。

$result = mysql_query(...); 
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray)); 
mysql_fetch_row — 从结果集中取得一行作为枚举数组

array mysql_fetch_row ( resource $result )

返回根据所取得的行生成的数组,如果没有更多行则返回 FALSE

mysql_fetch_array — 从结果集中取得一行作为关联数组,或数字数组,或二者兼有array mysql_fetch_array ( resource $result [, int $ result_type ] )

返回根据从结果集取得的行生成的数组,如果没有更多行则返回 FALSE。第二个参数 result_type 是一个常量,可以接受以下值:MYSQL_ASSOCMYSQL_NUM 和 MYSQL_BOTH。本特性是 PHP 3.0.7 起新加的。本参数的默认值是 MYSQL_BOTH

 $result = mysql_query("SELECT id, name FROM mytable");
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        printf ("ID: %s  Name: %s", $row["id"], $row["name"]);  }

sprintf() 函数把格式化的字符串写入变量中string sprintf ( string $format [, mixed $args [, mixed $... ]] )

详细查看:http://www.w3school.com.cn/php/func_string_sprintf.asp  

$number = 2;$str = "Shanghai";$txt = sprintf("There are %u million cars in %s.",$number,$str);echo $txt;    //There are 2 million cars in Shanghai.

try{}catch{}是异常处理.try { //...} catch(Exception $e) { //...}

将要执行的代码放入TRY块中,如果这些代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,$e收集错误信息和显示.任何调用 可能抛出异常的方法的代码都应该使用try语句。Catch语句用来处理可能抛出的异常。通过结合使用throw关键字和PHPtry{}catch{},我们可以避免错误标记“污染”类方法返回的值。因为“异常”本身就是一种与其它任何对象不同的PHP内建的类型,不会产生混淆。

如果抛出了一个异常,try语句中的脚本将会停止执行,然后马上转向执行catch语句中的脚本。如果异常抛出了却没有被捕捉到,就会产生一个fatal error

function inverse($x) {    if (!$x) {

        throw new Exception('Division by zero.');   }    return 1/$x;    }

try {   echo inverse(5) . " ";  } catch (Exception $e) {

    echo 'Caught exception: ',  $e->getMessage(), " ";   } finally {

    echo "First finally. ";}

try {   echo inverse(0) . " ";} catch (Exception $e) {

    echo 'Caught exception: ',  $e->getMessage(), " ";} finally {

    echo "Second finally. ";}

echo "Hello World ";

try {
    if (file_exists('test_try_catch.php')) {
    require ('test_try_catch.php');    } else {
    throw new Exception('file is not exists');  }
} catch (Exception $e) {
    echo $e->getMessage();  }

filesize() :返回指定文件的大小。若成功,则返回文件大小的字节数。若失败,则返回 false 并生成一条 E_WARNING 级的错误。filesize(filename)

echo filesize("test.txt"); //20  

提示:本函数的结果会被缓存。请使用 clearstatcache() 来清除缓存。

header() 函数:必须在任何实际的输出被发送之前调用 header() 函数

string

必需。规定要发送的报头字符串。

replace

可选。指示该报头是否替换之前的报头,或添加第二个报头。默认是 true(替换)。false(允许相同类型的多个报头)。

http_response_code

可选。把 HTTP 响应代码强制为指定的值。(PHP 4 以及更高版本可用)

header(string,replace,http_response_code)

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");header("Cache-Control: no-cache");header("Pragma: no-cache");

注释:用户可能会设置一些选项来更改浏览器的默认缓存设置。通过发送上面的报头,您可以覆盖任何这些设置,强制浏览器不进行缓存!

提示用户保存一个生成的 PDF 文件(Content-Disposition 报头用于提供一个推荐的文件名,并强制浏览器显示保存对话框):

header("Content-type:application/pdf");// 文件将被称为Downloaded.pdf

header("Content-Disposition:attachment;filename='downloaded.pdf'");//PDF 源在 original.pdf 中readfile("original.pdf");

重定向

Header("Location: http://www.php.net";);exit;//每个重定向后须加exit避免发生错误后继续执行。

header("refresh:3;url=http://axgle.za.net");
print('正在加载,请稍等...<br>三秒后自动跳转~~~');

禁止页面在IE中缓存

header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' ); //兼容http1.0https

CacheControl = no-cache//浏览器就不会缓存该网页
Pragma=no-cache //如果客户端通过安全连接 (https://) 与服务器通讯,且服务器在响应中返回 Pragma:no-cache 标题,则 Internet Explorer 不会缓存此响应。
Expires = -1//如果服务器上的网页经常变化,就把它设置为-1,表示立即过期。如果一个网页每天凌晨1点更新,可以把Expires设置为第二天的凌晨1

http-equiv meta来标记指定的http消息头部

让使用者的浏览器出现找不到档案的信息

header(”http/1.1 404 Not Found”);
第一部分为HTTP协议的版本(HTTP-Version);第二部分为状态代码(Status);第三部分为原因短语(Reason-Phrase)

让使用者下载档案隐藏文件的位置 )

header("Content-type: application/x-gzip");
header("Content-Disposition: attachment; filename=文件名");
header("Content-Description: PHP3 Generated Data");

header函数前输入内容

一般来说在header函数前不能输出html内容,类似的还有setcookie() 和 session 函数,这些函数需要在输出流中增加消息头部信息。

header('HTTP/1.1 200 OK');// ok
header('HTTP/1.1 404 Not Found');//设置一个404:
header('HTTP/1.1 301 Moved Permanently');//设置地址被永久的重定向
header('Location: http://www.example.org/');//转到一个新地址

header('Refresh: 10; url=http://www.example.org/');//文件延迟转向:
print 'You will be redirected in 10 seconds';

<meta http-equiv="refresh" content="10;http://www.example.org/ />//使用html语法实现
header('X-Powered-By: PHP/4.4.0');// override X-Powered-By: PHP:
header('X-Powered-By: Brain/0.6b');
header('Content-language: en');//文档语言
$time = time() - 60; // or filemtime($fn), etc//告诉浏览器最后一次修改时间
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');
header('HTTP/1.1 304 Not Modified');//告诉浏览器文档内容没有发生改变
header('Content-Length: 1234');//设置内容长度
header('Content-Type: application/octet-stream');//设置为一个下载类型
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
readfile('example.zip');// load the file to send:
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');//当前文档禁缓存
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');
header('Content-Type: text/html; charset=iso-8859-1'); //设置内容类型:
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); //纯文本格式
header('Content-Type: image/jpeg'); //JPG图片

header('Content-Type: application/zip'); // ZIP文件
header('Content-Type: application/pdf'); // PDF文件
header('Content-Type: audio/mpeg'); // 音频文件
header('Content-Type: application/x-shockwave-flash'); //Flash动画
header('HTTP/1.1 401 Unauthorized');//显示登陆对话框
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';

注意传统的标头一定包含下面三种标头之一,并只能出现一次。

Content-Type: xxxx/yyyy

Location: xxxx:yyyy/zzzz

Status: nnn xxxxxx

extract() 函数:该函数使用数组键名作为变量名,使用数组键值作为变量值。extract(array,extract_rules,prefix)

针对数组中的每个元素,将在当前符号表中创建对应的一个变量

$a = "Original";

$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");extract($my_array);

echo "$a = $a; $b = $b; $c = $c"; //$a = Cat; $b = Dog; $c = Horse

Strpos:查找位置mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

    var_dump(strpos(12345,1));//false
    var_dump(strpos(12345,'1'));//0
    var_dump(strpos('12345',1));//false
    var_dump(strpos('12345','1'));//0
    $a = 12345;    $b = 1;
    var_dump(strpos(strval($a),strval($b)));//0
    var_dump(strpos((string)$a,(string)$b));//0  

Thinkphp方法

I方法:I('变量类型.变量名',['默认值'],['过滤方法'])变量类型是指请求方式或者输入类型,   

       意为{input}

get    获取GET参数               post    获取POST参数    

request    获取REQUEST 参数      put    获取PUT 参数    

session    获取 $_SESSION 参数    cookie    获取 $_COOKIE 参数    

server    获取 $_SERVER 参数      globals    获取 $GLOBALS参数 

param    自动判断请求类型获取GETPOST或者PUT参数 param类型变量还可以用数字索引的方式获取URL参数(必须是PATHINFO模式参数有效,无论是GET还是POST方式都有效) 

注意:变量类型不区分大小写。变量名严格区分大小写。默认值和过滤方法均属于可选参数。

echo I('get.name');// 相当于 $_GET['name']

I('session.user_id',0);// 获取$_SESSION['user_id'] 如果不存在则默认为0

echo I('get.name','','htmlspecialchars');// 采用htmlspecialchars方法对$_GET['name'] 进行过滤,如果不存在则返回空字符串

http://serverName/index.php/New/2013/06/01 

echo I('param.1');// 输出2013   

param变量类型的写法可简化:I('id');// I('param.id')I('name');// I('param.name')

Thinkphp3.2添加了一个I方法,取义Input,用来获取前台提交过来的数据。
I方法是放在了/ThinkPHP/Common/function.php之中

C()方法:C方法是ThinkPHP用于设置、获取,以及保存配置参数的方法,使用频率较高。

     设置参数 

C('DB_NAME','thinkphp');

表示设置DB_NAME配置参数的值为thinkphp,由于配置参数不区分大小写

$config['user_id'] = 1;$config['user_type'] = 1;C($config);

如果C方法的第一个参数传入数组,就表示批量赋值,上面的赋值相当于:

C('USER_ID',1);C('USER_TYPE',1);

获取参数 
要获取设置的参数,可以用:

$userId = C('USER_ID');$userType = C('USER_TYPE');

如果USER_ID参数尚未定义过,则返回NULL。

如果传入的配置参数为空,表示获取全部的参数:

$config = C();

保存设置 
3.1版本增加了一个永久保存设置参数的功能,仅针对批量赋值的情况,例如:

$config['user_id'] = 1;$config['user_type'] = 1;C($config,'name');

在批量设置了config参数后,会连同当前所有的配置参数保存到缓存文件(或者其他配置的缓存方式)。
保存之后,如果要取回保存的参数,可以用

$config = C('','name');

其中name就是前面保存参数时用的缓存的标识,必须一致才能正确取回保存的参数。取回的参数会和当前的配置参数合并,无需手动合并

Mysql

数据库字段查询:FIND_IN_SET(str,strlist)

如果str不在strlist strlist 为空字符串,则返回值为 。如任意一个参数为NULL,则返回值为 NULL。这个函数在第一个参数包含一个逗号(‘,’)时将无法正常运行。

 

select FIND_IN_SET('2', '12'); 返回2     select FIND_IN_SET('6', '1');  返回0

其他:

浏览器更改编码方式,需改乱码问题

左上角---工具--编码--utf-8

原文地址:https://www.cnblogs.com/jingzi111/p/5044988.html