# 安装php

manjaro

sudo pacman -S php

ubuntu | debian

sudo apt-get install php

Cnetos

sudo yum install php

# php扩展安装

Ubuntu

# 使用扩展安装请先安装这两个东西
sudo apt-get install php-pear
sudo apt-get install php-dev

安装php扩展

http://pecl.php.net/package/redis

pecl install redis

# window安装pecl

安装步骤 PECL是 The PHP Extension Community Library 缩写。

  • 下载go-pear.phar 到 d:/tool/go-pear.phar
  • 执行 php d:/tool/go-pear.phar 下载地址:http://pear.php.net/go-pear.phar 官方文档:https://pear.php.net/manual/en/installation.getting.php

关键事项

  • 注意事项:第一个一定是选择 local。
  • 第一次执行的时候一定要指定 php的路径,输入13弹出对话框选择PHP的目录。
  • 之后直接按 Enter 继续。完成!

安装过程:

D:\pear>php d:/tool/go-pear.phar

Are you installing a system-wide PEAR or a local copy?
(system|local) [system] : local
Please confirm local copy by typing 'yes' : yes

Below is a suggested file layout for your new PEAR installation.  To
change individual locations, type the number in front of the
directory.  Type 'all' to change all of them or simply press Enter to
accept these locations.

 1. Installation base ($prefix)                   : D:\pear
 2. Temporary directory for processing            : D:\pear\tmp
 3. Temporary directory for downloads             : D:\pear\tmp
 4. Binaries directory                            : D:\pear
 5. PHP code directory ($php_dir)                 : D:\pear\pear
 6. Documentation directory                       : D:\pear\docs
 7. Data directory                                : D:\pear\data
 8. User-modifiable configuration files directory : D:\pear\cfg
 9. Public Web Files directory                    : D:\pear\www
10. System manual pages directory                 : D:\pear\man
11. Tests directory                               : D:\pear\tests
12. Name of configuration file                    : D:\pear\pear.ini
13. Path to CLI php.exe                           :

1-13, 'all' or Enter to continue: 13
php.exe (sapi: cli) found.



Below is a suggested file layout for your new PEAR installation.  To
change individual locations, type the number in front of the
directory.  Type 'all' to change all of them or simply press Enter to
accept these locations.

 1. Installation base ($prefix)                   : D:\pear\
 2. Temporary directory for processing            : D:\pear\\tmp
 3. Temporary directory for downloads             : D:\pear\\tmp
 4. Binaries directory                            : D:\pear\
 5. PHP code directory ($php_dir)                 : D:\pear\\pear
 6. Documentation directory                       : D:\pear\\docs
 7. Data directory                                : D:\pear\\data
 8. User-modifiable configuration files directory : D:\pear\\cfg
 9. Public Web Files directory                    : D:\pear\\www
10. System manual pages directory                 : D:\pear\\man
11. Tests directory                               : D:\pear\\tests
12. Name of configuration file                    : D:\pear\\pear.ini
13. Path to CLI php.exe                           : D:\php73\

1-13, 'all' or Enter to continue:
Beginning install...
Configuration written to D:\pear\\pear.ini...
Initialized registry...
Preparing to install...
installing phar://D:/tool/go-pear.phar/PEAR/go-pear-tarballs/Archive_Tar-1.4.7.t
ar...
installing phar://D:/tool/go-pear.phar/PEAR/go-pear-tarballs/Console_Getopt-1.4.
2.tar...
installing phar://D:/tool/go-pear.phar/PEAR/go-pear-tarballs/PEAR-1.10.9.tar...
installing phar://D:/tool/go-pear.phar/PEAR/go-pear-tarballs/Structures_Graph-1.
1.1.tar...
installing phar://D:/tool/go-pear.phar/PEAR/go-pear-tarballs/XML_Util-1.4.3.tar.
..
install ok: channel://pear.php.net/Archive_Tar-1.4.7
install ok: channel://pear.php.net/Console_Getopt-1.4.2
install ok: channel://pear.php.net/Structures_Graph-1.1.1
install ok: channel://pear.php.net/XML_Util-1.4.3
install ok: channel://pear.php.net/PEAR-1.10.9
PEAR: Optional feature webinstaller available (PEAR's web-based installer)
PEAR: Optional feature gtkinstaller available (PEAR's PHP-GTK-based installer)
PEAR: Optional feature gtk2installer available (PEAR's PHP-GTK2-based installer)

PEAR: To install optional features use "pear install pear/PEAR#featurename"

******************************************************************************
WARNING!  The include_path defined in the currently used php.ini does not
contain the PEAR PHP directory you just specified:
<D:\pear\\pear>
If the specified directory is also not in the include_path used by
your scripts, you will have problems getting any PEAR packages working.


Would you like to alter php.ini <D:\PHP73\php.ini>? [Y/n] : Y

php.ini <D:\PHP73\php.ini> include_path updated.

Current include path           : .;C:\php\pear
Configured directory           : D:\pear\\pear
Currently used php.ini (guess) : D:\PHP73\php.ini
Press Enter to continue:

** WARNING! Old version found at C:\Program Files (x86)\Common Files\Oracle\Java
\javapath\pear.bat, please remove it or be sure to use the new d:\pear\\pear.bat
 command

The 'pear' command is now at your service at d:\pear\\pear.bat

** The 'pear' command is not currently in your PATH, so you need to
** use 'd:\pear\\pear.bat' until you have added
** 'D:\pear\' to your PATH environment variable.

Run it without parameters to see the available actions, try 'pear list'
to see what packages are installed, or 'pear help' for help.

For more information about PEAR, see:

  http://pear.php.net/faq.php
  http://pear.php.net/manual/

Thanks for using go-pear!

# php常用函数

# 字符串处理

explode():使用一个字符串分割另一个字符串

$str= 'one|two|three|four';

print_r(explode('|',$str));

str_split() 将字符串分割为一个数组,成功返回一个数组。

arraystr_split( string string [, int length] )

# 文字包含判断

if(strpos("云南省","云南") !== false)

# 汉字截取

mb_substr("清华大学",0,2); //清华

# 一维数组无限极分类后排序

array_multisort(array_column($list,'sort'),SORT_ASC,$list);

# 随机验证码

$pattern='1234567890';
for( $i=0; $i<6; $i++ ) {
	$code_number .= $pattern[mt_rand(0, 9)];
}

# php数值处理

  • 四舍五入

    echo(ceil(0.60); 	// 1
    echo(ceil(-5.1); 	// -5
    
  • 四舍五入保留小数点位数

    echo round(3.4);     // 3 
    echo round(3.5);     // 4 
    echo round(3.6);     // 4 
    echo round(1.95583, 2); // 1.96 
    echo round(5.045, 2);  // 5.05 
    echo round(5.055, 2);  // 5.06 
    
  • 舍去小数点

    echo floor(0.1); 	// 0
    echo floor(1.6); 	// 1
    

# 生成唯一SN

/**
 * 生成sn 
*/
private function createSn()
{
    $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $number = substr(microtime(),-4);
    return date('Ymd').substr(str_shuffle($str),10,15).$number;
}

# fiel_get_contents 请求

// 淘宝ip地址
    protected function HttpIp($ip)
    {
        $query_info = ['ip' => $ip, 'accessKey'=>'alibaba-inc'];
        $context = stream_context_create([
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => http_build_query($query_info),
                'timeout' => 30
            ),
        ]);
        $httpRes = file_get_contents('http://ip.taobao.com/outGetIpInfo', false, $context);
        return json_decode($httpRes,true);
    }

# php请求封装

<?php
/**
 * HttpCurl Curl模拟Http工具类
 * @author OrangBus
 * @blog https://doc.orangbus.cn
 */
namespace app\admin\extend;

class HttpCurl {
    private $ch = null; // curl handle
    private $headers = array();// request header
    private $proxy = null; // http proxy
    private $timeout = 5;    // connnect timeout
    private $httpParams = null;

    public function __construct()
    {
        $this->ch = curl_init();
    }

    /**
     * 设置http header
     * @param $header
     * @return $this
     */
    public function setHeader($header) {
        if(is_array($header)) {
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $header);
        }
        return $this;
    }

    /**
     * 设置http 超时
     * @param int $time
     * @return $this
     */
    public function setTimeout($time) {
        // 不能小于等于0
        if($time <= 0) $time = 5;
        //只需要设置一个秒的数量就可以
        curl_setopt($this->ch, CURLOPT_TIMEOUT, $time);
        return $this;
    }


    /**
     * 设置http 代理
     * @param string $proxy
     * @return $this
     */
    public function setProxy($proxy) {
        if($proxy) curl_setopt ($this->ch, CURLOPT_PROXY, $proxy);
        return $this;
    }

    /**
     * 设置http 代理端口
     * @param int $port
     * @return $this
     */
    public function setProxyPort($port) {
        if(is_int($port)) curl_setopt($this->ch, CURLOPT_PROXYPORT, $port);
        return $this;
    }

    /**
     * 设置来源页面
     * @param string $referer
     * @return $this
     */
    public function setReferer($referer = ""){
        if (!empty($referer)) curl_setopt($this->ch, CURLOPT_REFERER , $referer);
        return $this;
    }

    /**
     * 设置用户代理
     * @param string $agent
     * @return $this
     */
    public function setUserAgent($agent = "") {
        if ($agent) {
            // 模拟用户使用的浏览器
            curl_setopt($this->ch, CURLOPT_USERAGENT, $agent);
        }
        return $this;
    }

    /**
     * http响应中是否显示header,1表示显示
     * @param $show
     * @return $this
     */
    public function showResponseHeader($show) {
        curl_setopt($this->ch, CURLOPT_HEADER, $show);
        return $this;
    }


    /**
     * 设置http请求的参数,get或post
     * @param array $params
     * @return $this
     */
    public function setParams($params) {
        $this->httpParams = $params;
        return $this;
    }

    /**
     * 设置证书路径
     * @param $file
     */
    public function setCainfo($file) {
        curl_setopt($this->ch, CURLOPT_CAINFO, $file);
    }

    /**
     * 模拟GET请求
     * @param string $url
     * @param string $dataType
     * @return bool|mixed
     */
    public function get($url, $dataType = 'text') {
        if(stripos($url, 'https://') !== FALSE) {
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($this->ch, CURLOPT_SSLVERSION, 1);
        }
        // 设置get参数
        if(!empty($this->httpParams) && is_array($this->httpParams)) {
            if(strpos($url, '?') !== false) {
                $url .= http_build_query($this->httpParams);
            } else {
                $url .= '?' . http_build_query($this->httpParams);
            }
        }
        // end 设置get参数
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1 );
        $content = curl_exec($this->ch);
        $status = curl_getinfo($this->ch);
        curl_close($this->ch);
        if (isset($status['http_code']) && $status['http_code'] == 200) {
            if ($dataType == 'json') {
                $content = json_decode($content, true);
            }
            return $content;
        } else {
            return FALSE;
        }
    }

    /**
     * 模拟POST请求
     *
     * @param string $url
     * @param array $fields
     * @param string $dataType
     * @return mixed
     *
     * HttpCurl::post('http://api.example.com/?a=123', array('abc'=>'123', 'efg'=>'567'), 'json');
     * HttpCurl::post('http://api.example.com/', '这是post原始内容', 'json');
     * 文件post上传
     * HttpCurl::post('http://api.example.com/', array('abc'=>'123', 'file1'=>'@/data/1.jpg'), 'json');
     */
    public function post($url, $dataType='json') {
        if(stripos($url, 'https://') !== FALSE) {
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($this->ch, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($this->ch, CURLOPT_URL, $url);
        // 设置post body
        if(!empty($this->httpParams)) {
            if(is_array($this->httpParams)) {
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($this->httpParams));
            } else if(is_string($this->httpParams)) {
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->httpParams);
            }
        }
        // end 设置post body
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($this->ch, CURLOPT_POST, true);
        $content = curl_exec($this->ch);
        $status = curl_getinfo($this->ch);
        curl_close($this->ch);
        if (isset($status['http_code']) && $status['http_code'] == 200) {
            if ($dataType == 'json') return json_decode($content, true);
        } else {
            return FALSE;
        }
    }
}

# 案例

<?php

use app\admin\extend\HttpCurl;

class Test
{
	public function(){
		$http = new HttpCurl();
        $header = array("Content-type:application/json;charset=utf-8","Accept:application/json");
        $requestData = ["user" => "orangbus.cn"];
        $response = $http->setHeader($header)->setParams(json_encode($requestData))->post("https://httpbin.org/post");
        return $response;
	}
}

# 函数工具

# Check

<?php
    
 trait Check{
    /**
     * 检查手机号格式
     * @param string $phone
     * @return bool|string[]
     */
    public function phone(string $phone){
        $check = '/^(1(([35789][0-9])|(47)))\d{8}$/';
        if (preg_match($check, $phone)) return true;
        return ["msg" => "手机号码格式不对!"];
    }
}

# 【PHP】代码规范检查工具PHPCS

  • PHP代码规范有PSRs,为了能做到代码规范的自动化检查和修复,就需要用到PHPCS了。

  • 项目官网:https://github.com/squizlabs/PHP_CodeSniffer

  • PHPCS安装

  • curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
    php phpcs.phar -h
    curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar
    php phpcbf.phar -h
    // 也许需要 sudo
    sudo mv phpcs.phar /usr/bin/phpcs
    sudo mv phpcbf.phar /usr/bin/phpcbf
    sudo chmod +x /usr/bin/phpcs
    sudo chmod +x /usr/bin/phpcbf
    
  • 常用命令

    • 检查单个文件:phpcs /path/to/code
    • 检查目录下的文件:phpcs /path/to/code/
    • 查看已经安装的标准:phpcs -i
    • 设置默认检查标准:phpcs --config-set default_standard /path/to/standard_file
    • 查看配置:phpcs --config-show
    • 指定报告格式:phpcs --report=summary /path/to/code ;可用的报告格式有full, xml, checkstyle, csv, json, emacs, source, summary, diff, svnblame, gitblame, hgblame, notifysend,默认为full
    • 查看帮助:phpcs -h
    • 自动修复:phpcbf /path/to/code
    • 详细的使用说明见官方wiki

# php设计模式

https://learnku.com/docs/php-design-patterns/2018

# 单例模式

# 观察者模式

# 织梦的数据库操作

dedecms的数据库操作类,非常实用,在二次开发中尤其重要,这个数据库操作类说明算是奉献给大家的小礼物了。

引入common.inc.php文件

require_once  (dirname( __FILE__ ) . "/include/common.inc.php" );

获取一条记录的内容

$row  = $dsql ->GetOne( "Select * From dede_* where id = $aid" );
echo  $row [ 'id' ];

将查询获取总数输出

$row  = $dsql ->GetOne( "select count(*) as dd where typeid = $typeid" );
echo  $row [ 'dd' ]; //输出总数

将查询的若干条记录输出

$sql  = "Select * from dede_*" ;
$dsql ->SetQuery( $sql ); //将SQL查询语句格式化
$dsql ->Execute(); //执行SQL操作
//通过循环输出执行查询中的结果
while ( $row  = $dsql ->GetArray()){
  echo  $row [ 'id' ];
  echo  $row [ 'title' ];
}
//或者采取这种方式输出内容
while ( $row  = $dsql ->GetObject()){
  echo  $row ->id;
  echo  $row ->Title;
}

将查询的若干条记录输出dedecms5

$dsql ->SetQuery( "Select id,typename From `#@__arctype` where reid=0 And channeltype=1 And ishidden=0 And ispart<>2 order by sortrank" );
$dsql ->Execute();
while ( $row = $dsql ->GetObject())
{
     $channellist  .= "<a href='wap.php?action=list&id={$row->id}'>{$row->typename}</a> ";
     echo  $row ->id;
}

插入一条记录

$sql  = "
INSERT INTO `dede_member_flink`(mid,title,url,linktype,imgurl,imgwidth,imgheight)
VALUES( ".$cfg_ml->M_ID." , '$title' , '$url' , '$linktype' , '$imgurl' , '$imgwidth' , '$imgheight' );"; //插入记录数据库
$dsql ->SetQuery( $sql ); //格式化查询语句
$dsql ->ExecNoneQuery(); //执行SQL操作

经实践证明,上面的语句不能正常插入数据库,下面是正确的语句

$sql  = "
INSERT INTO `dede_member_flink`(mid,title,url,linktype,imgurl,imgwidth,imgheight)
VALUES( ".$cfg_ml->M_ID." , '$title' , '$url' , '$linktype' , '$imgurl' , '$imgwidth' , '$imgheight' );"; //插入记录数据库
$dsql ->ExecuteNoneQuery( $sql ); //执行SQL操作
$gid  = $dsql ->GetLastID(); //获取刚刚插入的id

删除一条记录

$sql  = "Delete From dede_member_flink where aid='$aid' And mid='" . $cfg_ml ->M_ID. "';" ;
$dsql ->SetQuery( $sql );
$dsql ->ExecNoneQuery();
//或者使用简化模式
$dsql ->ExecNoneQuery( "Delete From dede_member_flink where aid='$aid' And mid='" . $cfg_ml ->M_ID. "';" );

更新一条记录

$upquery  = "
  Update dede_member_flink set
  title= '$title' ,url= '$url' ,linktype= '$linktype' ,
  imgurl= '$imgurl' ,imgwidth= '$imgwidth' ,imgheight= '$imgheight'
  where aid= '$aid'  And mid= '".$cfg_ml->M_ID."' ;
";
$rs  = $dsql ->ExecuteNoneQuery( $upquery );

判断获取数据库内容的常用方法

$row  = $dsql ->GetOne( "Select * From dede_moneycard_type where tid={$pid}" );
if (! is_array ( $row )){
  echo  "失败" ;
  exit ();
}


$upquery  = " Update dede_member_flink set
title= '$title' ,url= '$url' ,linktype= '$linktype' ,
imgurl= '$imgurl' ,imgwidth= '$imgwidth' ,imgheight= '$imgheight'
where aid= '$aid'  And mid= '".$cfg_ml->M_ID."' ;
";
$rs  = $dsql ->ExecuteNoneQuery( $upquery );
if ( $rs ){
	echo  "成功" ;
} else {
	echo  "失败" ;
}

获取总数

$dsql  = new  DedeSql(false);
$dsql ->SetQuery( "Select * from `dede_admin` where userid='$userid' Or uname='$uname'" );
$dsql ->Execute();
$ns  = $dsql ->GetTotalRow();

关闭数据库

$dsql ->Close();

实例

<?php
/*
DedeCms 数据库使用实例说明
*/
require_once  dirname( __FILE__ ). "pub_db_mysql.php" ; //引用数据库文件

//确保数据库信息填写正确
//数据库连接信息
$cfg_dbhost  = 'localhost' ;
$cfg_dbname  = 'sccms' ;
$cfg_dbuser  = 'root' ;
$cfg_dbpwd  = '123456' ;
$cfg_dbprefix  = 'sc_' ;
$cfg_db_language  = 'utf8' ;

//新建一个数据库操作类
$dsql  = new  ScSql(false);

获取一条记录的内容///
//下面是获取一条记录使用实例
$row  = $dsql ->GetOne( "Select * From dede_* where id = $aid" );
//获取数据内容保存在数组$row中,通过下标可以将其调用出来
echo  $row [ 'id' ];
//下面是循环调用记录
///


//将查询获取总数输出/
//获取一个查询记录总数
$row  = $dsql ->GetOne( "select count(*) as dd where typeid = $typeid" );
echo  $row [ 'dd' ]; //输出总数
///


//将查询的若干条记录输出//
$sql  = "Select * from dede_*" ;
$dsql ->SetQuery( $sql ); //将SQL查询语句格式化
$dsql ->Execute(); //执行SQL操作
//通过循环输出执行查询中的结果
while ( $row  = $dsql ->GetArray()){
  echo  $row [ 'id' ];
  echo  $row [ 'title' ];
}
//或者采取这种方式输出内容


while ( $row  = $dsql ->GetObject()){
  echo  $row ->id;
  echo  $row ->Title;
}
///

//插入一条记录///
$sql  = "
INSERT INTO `dede_member_flink`(mid,title,url,linktype,imgurl,imgwidth,imgheight)
VALUES( ".$cfg_ml->M_ID." , '$title' , '$url' , '$linktype' , '$imgurl' , '$imgwidth' , '$imgheight' );"; //插入记录数据库
$dsql ->SetQuery( $sql ); //格式化查询语句
$dsql ->ExecNoneQuery(); //执行SQL操作
///

/删除一条记录///
$sql  = "Delete From dede_member_flink where aid='$aid' And mid='" . $cfg_ml ->M_ID. "';" ;
$dsql ->SetQuery( $sql );
$dsql ->ExecNoneQuery();
//或者使用简化模式
$dsql ->ExecNoneQuery( "Delete From dede_member_flink where aid='$aid' And mid='" . $cfg_ml ->M_ID. "';" );
///

//更新一条记录//
$upquery  = "
Update dede_member_flink set
title= '$title' ,url= '$url' ,linktype= '$linktype' ,
imgurl= '$imgurl' ,imgwidth= '$imgwidth' ,imgheight= '$imgheight'
where aid= '$aid'  And mid= '".$cfg_ml->M_ID."' ;
";
$rs  = $dsql ->ExecuteNoneQuery( $upquery );

///

判断获取数据库内容的常用方法///
$row  = $dsql ->GetOne( "Select * From dede_moneycard_type where tid={$pid}" );
if (! is_array ( $row )){
	echo  "失败" ;
	exit ();
}

/
$upquery  = " Update dede_member_flink set
title= '$title' ,url= '$url' ,linktype= '$linktype' ,
imgurl= '$imgurl' ,imgwidth= '$imgwidth' ,imgheight= '$imgheight'
where aid= '$aid'  And mid= '".$cfg_ml->M_ID."' ;
";
$rs  = $dsql ->ExecuteNoneQuery( $upquery );
if ( $rs ){
	echo  "成功" ;
} else {
	echo  "失败" ;
}
//获取总数//
$dsql  = new  DedeSql(false);
$dsql ->SetQuery( "Select * from `dede_admin` where userid='$userid' Or uname='$uname'" );
$dsql ->Execute();
$ns  = $dsql ->GetTotalRow();
关闭数据库///
$dsql ->Close();
///
?>