资讯专栏INFORMATION COLUMN

php记录

tainzhi / 1469人阅读

摘要:获取执行的语句天前月前周前二进制安全简单说就是传入的参数支持二进制数据,包括这种在中表示字符串结束的字符返回由于是非二进制安全,误判为相等返回负数捕捉异常中断脚本执行是否完成异

获取php pdo 执行的sql语句

</>复制代码

  1. class MyPDOStatement extends PDOStatement
  2. {
  3. protected $_debugValues = null;
  4. protected function __construct()
  5. {
  6. // need this empty construct()!
  7. }
  8. public function execute($values=array())
  9. {
  10. $this->_debugValues = $values;
  11. try {
  12. $t = parent::execute($values);
  13. // maybe do some logging here?
  14. } catch (PDOException $e) {
  15. // maybe do some logging here?
  16. throw $e;
  17. }
  18. return $t;
  19. }
  20. public function _debugQuery($replaced=true)
  21. {
  22. $q = $this->queryString;
  23. if (!$replaced) {
  24. return $q;
  25. }
  26. return preg_replace_callback("/:([0-9a-z_]+)/i", array($this, "_debugReplace"), $q);
  27. }
  28. protected function _debugReplace($m)
  29. {
  30. $v = $this->_debugValues[$m[1]];
  31. if ($v === null) {
  32. return "NULL";
  33. }
  34. if (!is_numeric($v)) {
  35. $v = str_replace(""", """", $v);
  36. }
  37. return """. $v .""";
  38. }
  39. }
  40. // have a look at http://www.php.net/manual/en/pdo.constants.php
  41. $options = array(
  42. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  43. PDO::ATTR_STATEMENT_CLASS => array("MyPDOStatement", array()),
  44. );
  45. // create PDO with custom PDOStatement class
  46. $pdo = new PDO($dsn, $username, $password, $options);
  47. // prepare a query
  48. $query = $pdo->prepare("INSERT INTO mytable (column1, column2, column3)
  49. VALUES (:col1, :col2, :col3)");
  50. // execute the prepared statement
  51. $query->execute(array(
  52. "col1" => "hello world",
  53. "col2" => 47.11,
  54. "col3" => null,
  55. ));
  56. // output the query and the query with values inserted
  57. //http://stackoverflow.com/questions/7716785/get-last-executed-query-in-php-pdo
  58. var_dump( $query->queryString, $query->_debugQuery() );
laravel Carbon

</>复制代码

  1. composer require nesbot/carbon
  2. use CarbonCarbon;
  3. CarbonCarbon::setLocale("zh");
  4. echo Carbon::now()->toDateTimeString();
  5. echo Carbon::parse("2016-10-15")->toDateTimeString();
  6. Carbon::parse("+3 days")->toDateTimeString();
  7. echo Carbon::parse("next wednesday")->toDateTimeString();
  8. echo Carbon::now()->modify("+15 days");
  9. $first = Carbon::create(2012, 9, 5, 23, 26, 11);
  10. $second = Carbon::create(2012, 9, 5, 20, 26, 11, "America/Vancouver");
  11. var_dump($first->gt($second)); // bool(false)
  12. var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second)); // bool(true)
  13. $dt = Carbon::now();
  14. $dt->isWeekday();
  15. echo Carbon::now()->subDays(5)->diffForHumans(); // 5天前
  16. echo $dt->diffForHumans($dt->copy()->addMonth()); // 1月前
  17. echo Carbon::now()->subDays(24)->diffForHumans(); // 3周前
PHP 二进制安全

</>复制代码

  1. //简单说就是传入的参数支持二进制数据,包括”″这种在 C 中表示字符串结束的字符
  2. $string1 = "Hello";
  3. $string2 = "Hellox00Hello";
  4. echo strcoll($string1, $string2); // 返回0, 由于是非二进制安全,误判为相等
  5. echo strcmp($string1, $string2); // 返回负数
PHP 捕捉异常中断

</>复制代码

  1. class IndexController extends Controller
  2. {
  3. /**
  4. * 脚本执行是否完成
  5. * @var bool
  6. */
  7. protected $complete = false;
  8. public function __construct()
  9. {
  10. register_shutdown_function([$this, "shutdown"]);
  11. }
  12. /**
  13. * 异常处理
  14. */
  15. public function shutdown()
  16. {
  17. if ($this->complete === false) {
  18. dump("log"); //此处应该输出日志并进行异常处理操作
  19. }
  20. }
  21. }
PHP如何批量生成手机号

</>复制代码

  1. class Util {
  2. private static $mobileSegment = [
  3. "134", "135", "136", "137", "138", "139", "150", "151", "152", "157", "130", "131", "132", "155", "186", "133", "153", "189",
  4. ];
  5. public function nextMobile()
  6. {
  7. $prefix = self::$mobileSegment[array_rand(self::$mobileSegment)];
  8. $middle = mt_rand(2000, 9000);
  9. $suffix = mt_rand(2000, 9000);
  10. return $prefix . $middle . $suffix;
  11. }
  12. }
  13. //匹配手机号的正则表达式 #^(13[0-9]|14[47]|15[0-35-9]|17[6-8]|18[0-9])([0-9]{8})$#
  14. $arr = array(
  15. 130,131,132,133,134,135,136,137,138,139,
  16. 144,147,
  17. 150,151,152,153,155,156,157,158,159,
  18. 176,177,178,
  19. 180,181,182,183,184,185,186,187,188,189,
  20. );
  21. for($i = 0; $i < 10; $i++) {
  22. $tmp[] = $arr[array_rand($arr)]." ".mt_rand(1000,9999)." ".mt_rand(1000,9999);
  23. }
  24. var_export(array_unique($tmp));
  25. //输出
  26. array (
  27. 0 => "139 9182 8973",
  28. 1 => "144 7038 6282",
  29. 2 => "182 2183 9323",
  30. 3 => "176 1226 2322",
  31. 4 => "183 1072 4890",
  32. 5 => "153 8744 2917",
  33. 6 => "152 1150 5508",
  34. 7 => "147 3404 5840",
  35. 8 => "139 3547 8652",
  36. 9 => "151 1968 2090",
  37. )
global

</>复制代码

  1. $var1 = 1;
  2. function test(){
  3. global $var1;//global $var1;等于$var1=&$GLOBALS["var1"];
  4. unset($var1);
  5. }
  6. test();
  7. echo $var1;// 此处输出1
  8. $var1 = 1;
  9. function test(){
  10. unset($GLOBALS["var1"]);
  11. }
  12. test();
  13. echo $var1;// 此处报错PHP Notice: Undefined variable: var1
sprintf截取小数

</>复制代码

  1. $str1 = 12.34;
  2. $str2 = 12.35;
  3. $str3 = 12.36;
  4. echo sprintf("%.1f",$str1);//12.3
  5. echo sprintf("%.1f",$str2);//12.3
  6. echo sprintf("%.1f",$str3);//12.4
  7. echo sprintf("%.1f", floor($str3));//12.3
  8. echo sprintf("%.0f", 12.5); //12
  9. echo sprintf("%.0f", 15.5); //16
php递归无限分类

</>复制代码

  1. $pdo = new PDO("mysql:host=localhost;dbname=test", "root", "root");
  2. function getCategories(PDO $pdo, $pid = 0)
  3. {
  4. $sql = "SELECT * FROM `category` WHERE pid=:pid";
  5. $stmt = $pdo->prepare($sql);
  6. $stmt->bindParam(":pid", $pid, PDO::PARAM_INT);
  7. $stmt->execute();
  8. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  9. foreach ($data as &$row) {
  10. $row["subs"] = getCategories($pdo, $row["id"]);
  11. }
  12. return $data;
  13. }
  14. $a = getCategories($pdo);
  15. print_r($a);
递归

</>复制代码

  1. public function find_children_cat($cat_id, $data)
  2. {
  3. static $tem=array();
  4. foreach ($data as $val)
  5. {
  6. if ( $val["parent_id"] == $cat_id )
  7. {
  8. array_push($tem, $val["cat_id"]);
  9. $this->find_children_cat($val["cat_id"], $data);
  10. }
  11. }
  12. return $tem;
  13. }
HTTP Basic Authorization

</>复制代码

  1. //请求的时候添加 Authorization头,值为"Basic "+base64_encode(username+":"+password)
  2. $curl = curl_init();
  3. curl_setopt($curl, CURLOPT_URL, $url);
  4. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  5. curl_setopt($curl, CURLOPT_USERPWD, "[$username]:[$password]");
switch全等判断

</>复制代码

  1. switch($value){
  2. case null: echo "null";
  3. break;
  4. case "": echo "空";
  5. break;
  6. }
  7. 当$value = ""时,switch会进入第一个case
  8. switch(true) {
  9. case null === $value : echo "null";
  10. break;
  11. case "" === $value: echo "空";
  12. break;
  13. }
  14. /**
  15. * 移除字符串的BOM
  16. *
  17. * @param string $str 输入字符串
  18. * @return string 输出字符串
  19. */
  20. function removeBOM($str)
  21. {
  22. $str_2 = substr($str, 0, 2);
  23. $str_3 = substr($str, 0, 3);//$str_2.$str{2};
  24. $str_4 = substr($str, 0, 4);//$str_3.$str{3};
  25. if ($str_3 == pack("CCC",0xef,0xbb,0xbf)) //utf-8
  26. return substr($str, 3);
  27. elseif ($str_2 == pack("CC",0xfe,0xff) || $str_2 == pack("CC",0xff,0xfe)) //unicode
  28. return substr($str, 2);
  29. elseif ($str_4 == pack("CCCC",0x00,0x00,0xfe,0xff) || $str_4 == pack("CCCC",0xff,0xfe,0x00,0x00)) //utf-32
  30. return substr($str, 4);
  31. return $str;
  32. }
数组重新组合

</>复制代码

  1. $arr1 = [
  2. ["tracking1","abc@qq.com","80"],
  3. ["tracking1","abc@qq.com","50"],
  4. ["tracking2","efg@qq.com","60"],
  5. ["tracking2","efg@qq.com","30"],
  6. ];
  7. $arr2 = [];
  8. foreach ($arr1 as $data) {
  9. list($account,$mail,$val) = $data;
  10. isset($arr2[$account.$mail]) || $arr2[$account.$mail]=[$account,$mail,[]];
  11. array_push($arr2[$account.$mail][2],$val);
  12. }
  13. $arr2 = array_values($arr2);
  14. var_dump($arr2);
  15. $arr = [["tracking1","abc@qq.com","80"],
  16. ["tracking1","abc@qq.com","50"],
  17. ["tracking2","efg@qq.com","60"],
  18. ["tracking2","efg@qq.com","30"]];
  19. $finalArr = [[[]]];
  20. $mailArr =[];
  21. foreach ($arr as $k=>$v){
  22. $mailKey = array_search($v[1],$mailArr);
  23. if($mailKey!==false){
  24. array_push($finalArr[$mailKey][2],$v[2]);
  25. }else{
  26. $finalArr[$k] = $v;
  27. $finalArr[$k][2] = [$v[2]];
  28. $mailArr[$k]=$v[1];
  29. }
  30. }
  31. $finalArr = array_values($finalArr);
  32. var_dump($finalArr);
preg_replace_callback

</>复制代码

  1. $items = [
  2. "a > 1",
  3. "b > 0",
  4. "abc" => "c > 1"
  5. ];
  6. $subject = "#0 and #1 or (#0) and #abc #nooo";
  7. echo preg_replace_callback("/#([a-z0-9_]+)/i", function($v) use ($items){
  8. return isset($items[$v[1]]) ? $items[$v[1]] : $v[0];
  9. }, $subject);//a > 1 and b > 0 or (a > 1) and c > 1 #nooo
用json保存二进制数

$data = ["a1" => sprintf("0b%06b", 0b000100)]; // 转成JSON后: {"a1": "0b000100"}

保留1位小数,不四舍五入,为整数时补0

echo sprintf("%.1f", floor($str));
sprintf("%.1f",12.35);//12.3
sprintf("%.1f",12.36);//12.4
number_format(12.35,1,".","")//12.4
number_format(12.36,1,".","")//12.4

json_decode 后,数字对象转换成了 科学计数法

</>复制代码

  1. $obj="{"order_id":213477815351175,"buyer":100001169269154}";
  2. $obj=$this->json_decode($obj,TRUE);
  3. print_r($obj);
  4. Array
  5. (
  6. [order_id] => 2.1347781535118E+14
  7. [buyer] => 1.0000116926915E+14
  8. )
  9. $obj="{"order_id":213477815351175,"buyer":100001169269154}";
  10. $obj=$this->json_decode($obj,TRUE);
  11. foreach ($obj as $key=>$val){
  12. $obj[$key]=number_format($val,0,"","");
  13. }
  14. print_r($obj);
  15. Array
  16. (
  17. [order_id] => 213477815351175
  18. [buyer] => 100001169269154
  19. )
从指定数字中获取随机组合的方法

</>复制代码

  1. //http://blog.csdn.net/fdipzone/article/details/51794055
  2. function getNumGroups($var, $num){
  3. // 数量不正确
  4. if($var<$num){
  5. return array();
  6. }
  7. $total = 0;
  8. $result = array();
  9. for($i=1; $i<$num; $i++){
  10. $tmp = mt_rand(1, $var-($num-$i)-$total);
  11. $total += $tmp;
  12. $result[] = $tmp;
  13. }
  14. $result[] = $var-$total;
  15. return $result;
  16. }
  17. $result = getNumGroups(100, 3);
  18. print_r($result);
  19. Array
  20. (
  21. [0] => 42
  22. [1] => 25
  23. [2] => 33
  24. )
crontab 精确到执行分钟内某一秒执行的方法

</>复制代码

  1. test.php
  2. echo date("Y-m-d H:i:s").PHP_EOL;
  3. * * * * * php /Users/fdipzone/test.php >> /Users/fdipzone/test.log
  4. * * * * * sleep 30; php /Users/fdipzone/test.php >> /Users/fdipzone/test.log
callable强制指定回调类型

</>复制代码

  1. function dosth($callback){
  2. call_user_func($callback);
  3. }
  4. function callback(){
  5. echo "do sth callback";
  6. }
  7. dosth("callback");
  8. function dosth(callable $callback){
  9. call_user_func($callback);
  10. }
  11. dosth("abc");//提示错误:TypeError: Argument 1 passed to dosth() must be callable
lcg_value与mt_rand生成0~1随机小数的效果比较

</>复制代码

  1. /**
  2. * 生成0~1随机小数http://blog.csdn.net/fdipzone/article/details/52829930
  3. * @param Int $min
  4. * @param Int $max
  5. * @return Float
  6. */
  7. function randFloat($min=0, $max=1){
  8. return $min + mt_rand()/mt_getrandmax() * ($max-$min);
  9. }
  10. // 获取microtime
  11. function get_microtime(){
  12. list($usec, $sec) = explode(" ", microtime());
  13. return (float)$usec + (float)$sec;
  14. }
  15. lcg_value();
  16. //lcg_value()执行速度快,但随机效果不及基于mt_rand()与mt_getrandmax()算法实现
  17. header("content-type: image/png");
  18. $im = imagecreatetruecolor(512, 512);
  19. $color1 = imagecolorallocate($im, 255, 255, 255);
  20. $color2 = imagecolorallocate($im, 0, 0, 0);
  21. for($y=0; $y<512; $y++){
  22. for($x=0; $x<512; $x++){
  23. $rand = randFloat();
  24. if(round($rand,2)>=0.5){
  25. imagesetpixel($im, $x, $y, $color1);
  26. }else{
  27. imagesetpixel($im, $x, $y, $color2);
  28. }
  29. }
  30. }
  31. imagepng($im);
  32. imagedestroy($im);
  33. /**
  34. * 检查连接是否可用
  35. * @param Link $dbconn 数据库连接
  36. * @return Boolean
  37. */
  38. function pdo_ping($dbconn){
  39. try{
  40. $dbconn->getAttribute(PDO::ATTR_SERVER_INFO);
  41. } catch (PDOException $e) {
  42. if(strpos($e->getMessage(), "MySQL server has gone away")!==false){
  43. return false;
  44. }
  45. }
  46. return true;
  47. }
Maximum function nesting level of "100" reached, aborting! in

</>复制代码

  1. function test() {
  2. echo count(debug_backtrace()) . "
  3. ";
  4. }
  5. function test2() {
  6. test();
  7. }
  8. test(); //输出1
  9. test2(); //输出2
  10. 惰加载 只是给$this->["config"]一个匿名函数,当你要用到的时候,才会进行new Config($config)的操作
  11. public function __construct($config)
  12. {
  13. parent::__construct();
  14. $this["config"] = function () use ($config) {
  15. return new Config($config);
  16. };
laravel验证两个字段必须有一个必填

</>复制代码

  1. "email" => "required_without:phone",
  2. "phone" => "required_without:email",
  3. set_time_limit 可以控制秒级的最大执行时间,一个500毫秒的超时
  4. declare(ticks=1);
  5. $start = microtime(true);
  6. register_tick_function(function () use ($start) {
  7. (microtime(true) - $start < 0.5) or die("timeout
  8. ");
  9. });
  10. function a() {
  11. echo "do some work
  12. ";
  13. usleep(600000);
  14. echo "do another work
  15. ";
  16. }
  17. a();
利用cookie模拟登陆

</>复制代码

  1. //设置post的数据
  2. $post = array (
  3. "email" => "账户",
  4. "pwd" => "密码"
  5. );
  6. //登录地址
  7. $url = "登陆地址";
  8. //设置cookie保存路径
  9. $cookie = dirname(__FILE__) . "/cookie.txt";
  10. //登录后要获取信息的地址
  11. $url2 = "登陆后要获取信息的地址";
  12. //模拟登录
  13. login_post($url, $cookie, $post);
  14. //获取登录页的信息
  15. $content = get_content($url2, $cookie);
  16. //删除cookie文件
  17. @ unlink($cookie);
  18. var_dump($content);
  19. //模拟登录
  20. function login_post($url, $cookie, $post) {
  21. $curl = curl_init();
  22. curl_setopt($curl, CURLOPT_URL, $url);
  23. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
  24. curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
  25. curl_setopt($curl, CURLOPT_POST, 1);
  26. curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
  27. curl_exec($curl);
  28. curl_close($curl);
  29. }
  30. //登录成功后获取数据
  31. function get_content($url, $cookie) {
  32. $ch = curl_init();
  33. curl_setopt($ch, CURLOPT_URL, $url);
  34. curl_setopt($ch, CURLOPT_HEADER, 0);
  35. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  36. curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
  37. $rs = curl_exec($ch);
  38. curl_close($ch);
  39. return $rs;
  40. }
php self

</>复制代码

  1. class Base {
  2. public function log() {
  3. // 目标类,输出:A/C
  4. echo static::class;
  5. // 基类,输出:Base
  6. //echo __CLASS__;
  7. echo self::class;
  8. }
  9. }
  10. class A extends Base {
  11. public function log1() {
  12. echo self::class;
  13. }
  14. }
  15. class C extends A {
  16. public function log2() {
  17. echo self::class;
  18. }
  19. }
  20. //self 指向基类 Fruit,也就是 __CLASS__ 的类
  21. //static、$this 指向最终new的类 Apple
  22. $a = new A();$c = new C();
  23. $a->log(); //输出 A Base
  24. $c->log(); //输出 C Base
  25. $c->log1(); //输出 A
  26. $c->log2(); //输出 C
mysql session cookie

</>复制代码

  1. CREATE TABLE sessions (
  2. user_id int(10) unsigned NOT NULL,
  3. session text NOT NULL,
  4. md5 char(32) NOT NULL,
  5. PRIMARY KEY (user_id)
  6. ) ENGINE=MEMORY DEFAULT CHARSET=utf8;
  7. 其中:
  8. user_id存储的是用户ID,作为主键.
  9. session存储的是用户的会话数组经过serialize或json_encode后的字符串.
  10. md5存储的是session字段的MD5值,用于实现Check And Set版本号乐观锁:
  11. --读取会话
  12. SELECT session, md5 --写入会话时需要用到这里查出来的md5,就是下面的$last_md5
  13. FROM sessions WHERE user_id = $user_id
  14. --写入会话
  15. UPDATE sessions
  16. SET session = $str, md5 = md5($str)
  17. WHERE user_id = $user_id
  18. AND md5 = $last_md5 --检查MD5,确保session字段没有被修改过

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/21952.html

相关文章

  • PHP框架中的日志系统

    摘要:一的几个函数异常捕获自定义处理函数注册错误捕获自定义处理函数注册程序执行时异常终止错误捕获处理函数注册这三个函数在错误处理控制中给开发者提供了很大的自主空间,在日志系统中记录日志信息有他们的功劳。下面要说的类库是借鉴了日志系统的设计。 引言 接触过php框架的朋友们可能都知道,日志在项目中的重要作用了,他可以帮助我们定位错误的位置,让程序更友好(处理得当的话不会直接抛出一大堆只有程...

    ningwang 评论0 收藏0

发表评论

0条评论

tainzhi

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<