jiazhizhongphp@163.com 发布的文章

php面试题

1、用PHP打印出前一天的时间格式是2006-5-10 22:21:21

$a = date("Y-m-d H:i:s", strtotime("-1 day"));   
print_r($a);

2、echo(),print(),print_r()的区别

echo 和print不是一个函数,是一个语言结构   
int print(string $arg), 只有一个参数   
echo arg1,arg1,arg2; 可以输出多个参数,返回void   
echo和print只能打印出string,不能打印出结构   
print_r能打印出结构   
比如    
$arr = array("key"=>"value");   
print_r($arr);

3、能够使HTML和PHP分离开使用的模板引擎

smarty,phplib

4、使用哪些工具进行版本控制?

svn,git,cvs

5、如何实现字符串翻转?

#中文:GB2312, 代码是使用GB2312编码   
<?php       
function reverse($str)   {   
    $ret = "";       
    len=mbstrwidth(len=mbstrwidth(str,"GB2312");   
    for(i=0;i=0;i< len;len;i++)   
    {   
        arr[]=mbsubstr(arr[]=mbsubstr(str, $i, 1, "GB2312");   
    }   
    return implode("", array_reverse($arr));   
}   
print_r(reverse("你好"));

6、优化MYSQL数据库的方法

语句方面:
1、使用索引,增加查询效率
2、优化查询语句,提高索引命中率

数据库涉及方面:
1、构造分库分表,提高数据库的存储和扩展能力
2、根据需要使用不同的存储引擎

7、PHP的意思

超级文本预处理语言
Hypertext PreProcessor

8、MYSQL取得当前时间的函数是?,格式化日期的函数是

CURRENT_TIMESTAMP()   
DATE_FORMAT()   
select DATE_FORMAT("2011-11-21 10:10:10", "%Y-%m-%d");

9、实现中文字串截取无乱码的方法。

mb_substr($str, 1, 1, "GB2312");

10、您是否用过版本控制软件? 如果有您用的版本控制软件的名字是

svn
git

11、您是否用过模板引擎? 如果有您用的模板引擎的名字是?

smarty

12、对于大流量的网站,您采用什么样的方法来解决访问量问题?

1、有效使用缓存,增加缓存命中率
2、使用负载均衡
3、对静态文件使用CDN进行存储和加速
4、想法减少数据库的使用
5、查看出现统计的瓶颈在哪里

13、用PHP写出显示客户端IP与服务器IP的代码

$_SERVER["REMOTE_ADDR"]
$_SERVER["SERVER_ADDR"]

14、语句include和require的区别是什么?为避免多次包含同一文件,可用(?)语句代替它们?

在失败的时候:
include产生一个warning,而require产生直接产生错误中断
require在运行前载入
include在运行时载入
require_once
include_once

15、如何修改SESSION的生存时间

session_set_cookie_params 

16、有一个网页地址, 比如PHP研究室主页: http://www.phpv.net/index.html,如何得到它的内容?

file_get_contents
curl

17、在HTTP 1.0中,状态码401的含义是(?);如果返回“找不到文件”的提示,则可用 header 函数,其语句为

未授权
header("HTTP/1.0 404 Not Found");
fast CGI中:
header("Status: 404 Not Found");

18、在PHP中,heredoc是一种特殊的字符串,它的结束标志必须?

成对出现
$a = <<EOD
good test
EOD;

19、谈谈asp,php,jsp的优缺点

asp是需要依赖IIS,是微软开发的语言
php和jsp可以依赖apache或者 nginx等其他服务器

20、谈谈对mvc的认识

model : 数据结构层
view :展现
control : 接收和判断处理输入

21、写出发贴数最多的十个人名字的SQL,利用下表:members(id,username,posts,pass,email)

select top 10 id,username from members order by posts desc

22、请说明php中传值与传引用的区别。什么时候传值什么时候传引用?

&表示传引用
函数中参数传引用会将参数进行改变
一般在输出参数有多个的时候可以考虑使用引用

23. 在PHP中error_reporting这个函数有什么作用?

设定error的展示级别

24. 请写一个函数验证电子邮件的格式是否正确

$str = "jiazhizhong@126.com";   
$regex="([a?z0?9\.?]+)@([\da?z\.?]+)\.([a?z\.]2,6)" ; //正则   
preg_match($regex,$str,$matches);
return $matches;

25. 简述如何得到当前执行脚本路径,包括所得到参数。

$argc --获取参数数量
$argv --获取参数列表

26.如何修改SESSION的生存时间.

session_set_cookie_params

27、JS表单弹出对话框函数是?获得输入焦点函数是?

alert()
confirm()
promopt()
focus()

28、JS的转向函数是?怎么引入一个外部JS文件?

window.location.href="#"
<script src="#"></script>

29、foo()和@foo()之间有什么区别?

@代表所有warning忽略

30、如何声明一个名为”myclass”的没有方法和属性的类?

class myclass
{
}

31、如何实例化一个名为”myclass”的对象?

$myclass = new myclass();

32、你如何访问和设置一个类的属性?

<?php   
class A   
{   
    public $name = "A";   
}   
$a = new A();   
$n=$a->name;   
print_r($n);

**33、mysql_fetch_row() 和mysql_fetch_array之间有什么区别? **

mysql_fetch_array() 是 mysql_fetch_row() 的扩展版本。除了将数据以数字索引方式储存在数组中之外,还可以将数据作为关联索引储存,用字段名作为键名。
<?php  
mysql_connect("localhost", "mysql_user", "mysql_password") or   
    die("Could not connect: " . mysql_error());   
mysql_select_db("mydb");   
$result = mysql_query("SELECT id, name FROM mytable");   
while ($row=mysqlfetcharray($result, MYSQL_ASSOC)) {   
    printf ("ID: %s  Name: %s", $row["id"],$row["id"],$row["name"]);   
}   
mysql_free_result($result);

34、GD库是做什么用的?

动态的开放的图片处理库

35、指出一些在PHP输入一段HTML代码的办法。

echo "{html}";
echo <<EOD
{html}
EOD;

36、下面哪个函数可以打开一个文件,以对文件进行读和写操作? 答案: C

(a) fget() (b) file_open() (c) fopen() (d) open_file()

37、下面哪个选项没有将 john 添加到users 数组中? 答案: B

(a) $users[] = ‘john’;   
(b) array_add($users,’john’);   
(c) array_push($users,‘john’);   
(d) $users ||= ‘john’;

38、下面的程序会输出什么? 答案: 10

$num = 10;   
function multiply(){   

   $num=$num * 10;
}
multiply();
echo $num;
?>

39、使用php写一段简单查询,查出所有姓名为“张三”的内容并打印出来。

表名 UserName Tel Content Date
张三 13333663366 大专毕业 2006-10-11
张三 13612312331 本科毕业 2006-10-15
张四 021-55665566 中专毕业 2006-10-15

请根据上面的题目完成代码:
$mysql_db=mysql_connect("local","root","pass");   

   @mysql_select_db("DB",$mysql_db);
$sql = sprintf("select * from %s where UserName = '%s'",
"表名",
"张三");
$values=mysqlquery($sql);
while($item=mysqlfetchqueryarray($values))
{
echo sprintf("用户名:%s, 电话 %s, 学历: %s, 毕业日期: %s",
item[′UserName′],item['Tel'], item[′Content′],item['Date']
);
}

40、如何使用下面的类,并解释下面什么意思?

class test{   
    function Get_test($num){   

   $num=md5(md5($num)."En");
   return $num;
}
}
$test = new test();
$ret = $test->Get_test(11);
print_r($ret);exit;
#将num进行MD5编码之后生成的32位字符串a1和"En"联系起来之后再进行一次MD5编码

41、写出 SQL语句的格式 : 插入 ,更新 ,删除

表名 UserName Tel Content Date
张三 13333663366 大专毕业 2006-10-11
张三 13612312331 本科毕业 2006-10-15
张四 021-55665566 中专毕业 2006-10-15

(a) 有一新记录(小王 13254748547 高中毕业 2007-05-06)请用SQL语句新增至表中

insert into 表名 values('小王', '13254748547', '高中毕业', '2007-05-06')

(b) 请用sql语句把张三的时间更新成为当前系统时间
update 表名 set Date = GETDATE() where UserName = "张三"

(c) 请写出删除名为张四的全部记录
delete from 表明 where UserName = "张四"

42、请写出数据类型(int char varchar datetime text)的意思; 请问varchar和char有什么区别

int 整型
char 存储定长
varchar 存储变长
datetime 时间
text 存储变长的
varchar是变长
char(20) 定长

43、MySQ自增类型(通常为表ID字段)必需将其设为(?)字段

auto_increment

44、写出以下程序的输出结果? 答案:4

$b=201;   
$c=40;   
$a=$b>$c ? 4 : 5;   
echo $a;   
?>  

45、检测一个变量是否有设置的函数是否?是否为空的函数是?

isset()
empty()

46、取得查询结果集总数的函数是?

mysql_num_rows()

47、$arr = array('james', 'tom', 'symfony'); 请打印出第一个元素的值

print_r($arr[0]);   
reset($arr);   
print_r(current($arr));   
print_r(array_shift($arr));

48、请将41题的数组的值用','号分隔并合并成字串输出

implode

49、$a=array('abcdef');请取出$a=array('abcdef');请取出$a的值并打印出第一个字母

$a[0];
substr($a, 0, 1);

50、PHP可以和sql server/oracle等数据库连接吗?

可以
有现成的库

51、请写出PHP5权限控制修饰符

public  (公共的)
private (私有的)
protected (受保护的)

52、请写出php5的构造函数和析构函数

public function __construct()   {   
}   
public function __destruct()   {   
}

[编程题]

1、写一个函数,尽可能高效的,从一个标准 url 里取出文件的扩展名

例如: http://www.sina.com.cn/abc/de/fg.php?id=1 需要取出 php 或 .php
<?php   
$url = "http://www.sina.com.cn/abc/de/fg.php?id=1";   
$arr = parseurl($url);   
$pathArr= pathinfo($arr['path']);   
print_r($pathArr['extension']);

2. 写一个函数,算出两个文件的相对路径

如 $a = '/a/b/c/d/e.php';   
$b = '/a/b/12/34/c.php';   
计算出 b相对于b相对于a 的相对路径应该是 http://www.cnblogs.com/12/34/c.php将添上   
<?php   
$a = '/a/b/c/d/e.php';   
$b = '/a/b/12/34/c.php';   
//获取path相对于conpath的相对路径   
function sGetRelativePath($path,$path,$conpath)   {   
    $pathArr=explode("/",$path);   
    $conpathArr=explode("/",$conpath);   
    $dismatchlen = 0;   
    for(i=0;i < count($pathArr);i++)   
    {   
        if($conpathArr[i] != $pathArr[i])   
        {   
            $dismatchlen=count($pathArr) - $i;   
            $arrLeft=arrayslice($pathArr, $i);   
            break;   
        }   
    }   
    $ret=strrepeat("../",$dismatchlen).implode("/", $arrLeft);   
    return $ret;   
}   
print_r(sGetRelativePath($b,$b,$a));

3、写一个函数,能够遍历一个文件夹下的所有文件和子文件夹。

<?php   
function aGetAllFile($folder)   {   
    $aFileArr = array();   
    if(is_dir($folder))   
    {   
        $handle=opendir(#folder);   
        while(($file=readdir($handle)) !== false)   
        {   
            //如果是.或者..则跳过   
            if($file=="."||$file == "..")   
            {   
                continue;   
            }   
            if(is_file($folder."/".$folder."/".file))   
            {   
                $aFileArr[]=$file;    
            }   
            else if(is_dir($folder."/".$folder."/".file))   
            {   
                $aFileArr[$file] = aGetAllFile($folder."/".$folder."/".file);   
            }   
        }   
        closedir($handle);   
    }   
    return $aFileArr;   
}   
$path = "/home/test/sql";   
print_r(aGetAllFile($path));

Docker 安装及应用

云主机可以选择操作系统镜像快速创建主机,这比虚拟机更便捷了,我们本地也可以这么做了,因为有了 Docker 这个东西。它依赖于 LXC(Linux Container),能从网络上获得配置好的 Linux 镜像,非常容易在隔离的系统中运行自己的应用。也因为它的底层核心是个 LXC,所以在 Mac OS X 下需要在 VirtualBox 中跑一个精小的 LXC(这里是一个 Tiny Core Linux,完全在内存中运行,个头只约 24MB,启动时间小于 5 秒的 boot2docker) 虚拟机,构建在 VirtualBox 中。以后的通信过程就是 docker --> boot2docker --> container,端口或磁盘映射也是遵照这一关系。

理解了上面的关系,开始说说 Docker 安装过程

1. 安装 VirtualBox, 不多讲, 因要在它当中创建一个 boot2docker-vm 虚拟机
2. 安装 boot2docker

brew install boot2docker
你也可以手工安装
curl https://raw.github.com/steeve/boot2docker/master/boot2docker > boot2docker; chmod +x boot2docker; sudo mv boot2docker /usr/local/bin

3. 安装 Docker

brew install docker
也可手工安装
curl -o docker http://get.docker.io/builds/Darwin/x86_64/docker-latest; chmod +x docker; sudo cp docker /usr/local/bin

4. 配置 Docker 客户端

export DOCKER_HOST=tcp://127.0.0.1:4243
把它写到 ~/.bash_profile 中,如果你是用的 bash 的话。我工作在 fish 下,所以在 ~/.config/fish/config.fish 中加了 set -x DOCKER_HOST tcp://127.0.0.1:4243

5. boot2docker 初始化与启动

boot2docker init
完成后就能在 VirtualBox 中看到一个叫做 boot2docker-vm的虚拟机,以后只需用 boot2docker 命令来控制这个虚拟机的行为,启动,停止等。
boot2docker up
启动,boot2docker-vm虚拟机,我们能在 VirtualBox 中看到该虚拟机变成 Running 状态
直接执行 boot2docker 可以看到可用的参数
Usage /usr/local/bin/boot2docker  {init|start|up|save|pause|stop|restart|status|info|delete|ssh|download}

6. 启动 Docker 守护进程

sudo docker -d
这时可执行
boot2docker ssh,输入密码  tcuser 进到该虚拟机的控制台下,如果要用户名的话请输入docker

test.jpg

上面看到 Mac 启动了 4243 端口,在 boot2docker 虚拟机中也有 4243 端口,并在 /var/run/docker.sock 上监听。借此回顾下 docker 的通信过程,dock 命令是与 Docker daemon 在 Mac 上开启的 4243 端口通信,该端口映射到 boot2docker 的 4243 端口上,进而通过 /var/run/docker.sock 与其中的容器进行通信。
所以在执行 docker version 时如果没有启动 Docker daemon 会提示
2014/05/16 06:52:48 Cannot connect to the Docker daemon. Is 'docker -d' running on this host?
如果没有启动 boot2docker 会得到提示
Get http:///var/run/docker.sock/v1.11/version: dial unix /var/run/docker.sock: no such file or directory
Mac OS X -- boot2docker -- container 三者之间的关系,这张图很好的说明了
docker-install-800x417.png

上面 boot2docker, docker 都准备就绪了, 现在开始进入 dock 的操作了,有关于 docker 的命令可以参看这里 http://blog.tankywoo.com/docker/2014/05/08/docker-4-summary.html。


1. 下载镜像,并加载启动容器

docker images    #现在没有一个镜像
docker pull ubuntu     #我们把这个拉下来试验,可用 docker search ubuntu 找到所有与 ubuntu 有关的镜像
docker run -i -t  ubuntu  #加载镜像 learn/tutorial 并进到 shell 下,这样就直接连接到该容器中,退出后容器也退了
docker ps     #在另一个终端中用这个命令,可以看到运行实例,即容器
现在我们在容器的控制台上 oot@95903c1a2bf7:/#,可以安装一个 apche2, curl 并启动 apache2,来测试下
root@d0889476e21e:/# apt-get update
root@d0889476e21e:/# apt-get install apache2 curl
root@d0889476e21e:/# apachectl start
root@d0889476e21e:/# curl http://localhost
<html><body><h1>It works!</h1>

Apache2 正常启动了,在容器内可访问。但现在还无法从 Mac OS X 上对该 apache 服务进行访问,这需要端口映射,有两种方式。不过在端口映射之前还需保存下镜像的修改。

2. 保存镜像

如果前面用 docker run -i -t learn/tutorial 运行的镜像
在运行该镜像的容器中安装了软件,需要把新的内容保存到该镜像中去,否则下次启动该镜像又恢复成原样
uqiu@localhost ~> docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
d0889476e21e        ubuntu        "/bin/bash"         About an hour ago   Up About an hour    0.0.0.0:8082->80/tcp   high_meitner
看到容器的 ID,然后执行
docker commit d0889476e21e ubuntu  #把当前容器的修改提交到镜像 ubuntu  中去
以后再次运行该镜像就有了最新安装的内容了。

3. 端口映射
比如我们现在要做的映射关系是 Mac OS X(9082) --> boot2docker(8082) --> container(80)

可以有两种办法

boot2docker ssh -L 9082:localhost:8082 #这条命令可以在 boot2docker-vm 运行时执行,建立多个不同的映射就是执行多次
docker run -i -t -p 8082:80 ubuntu
root@d0889476e21e:/# apachectl start
然后在 Mac 的浏览器中打开 http://localhost:9082

VBoxManage modifyvm "boot2docker-vm" --natpf1 "tcp-port_9082:80,tcp,,9082,,8082"
docker run -i -t -p 8082:80 ubuntu
root@c79b5070a972:/# apachectl start
这是直接修改了 boot2docker-vm 的配置,可以在 VirtualBox 中看到这条配置,配置 nat 命令见 http://www.virtualbox.org/manual/ch06.html#natforward. 也能建立许多的端口映射
boot2docker-vm-port-800x215.png

4. Docker 容器镜像删除

1.停止所有的container,这样才能够删除其中的images:
docker stop $(docker ps -a -q)

如果想要删除所有container的话再加一个指令:
docker rm $(docker ps -a -q)

2.查看当前有些什么images
docker images

3.删除images,通过image的id来指定删除谁
docker rmi <image id>

想要删除untagged images,也就是那些id为<None>的image的话可以用
docker rmi $(docker images | grep "^<none>" | awk "{print $3}")

要删除全部image的话
docker rmi $(docker images -q)

Docker 的世界很精彩,其他内容基本就是怎么用好 Docker 命令,如管理镜像,容器,创建自己的镜像; Docker 有三种运行命令的方式,短暂方式,交互方式,daemon方式; 使用 ssh 来管理容器等等。
在 Mac 下使用 Docker 除了可用 boot2docker 作为 LXC,还有个替代品 VAGRANT 。
参考:
1. 利用Docker构建开发环境
2. Docker学习笔记之一,搭建一个JAVA Tomcat运行环境
3. Installing Docker on Mac OS X
4. https://github.com/boot2docker/boot2docker
5. Docker 快速入门

php 多线程扩展 pthreads 安装 及 使用

1、扩展的编译安装php(Linux),编辑参数 --enable-maintainer-zts 是必选项:
2、下载 php7:
http://tw2.php.net/get/php-7.1.2.tar.gz/from/a/mirrorduoxc

3、解压并编译php
tar -zxf php-7.1.2.tar.gz
cd php-7.1.2
./configure --prefix=/usr/local/php712 --with-config-file-path=/usr/local/php712/etc --with-config-file-scan-dir=/usr/local/php712/etc/php.d --with-mcrypt=/usr/include --enable-mysqlnd --with-mysqli --with-pdo-mysql --enable-fpm --with-gd --with-iconv --with-zlib --enable-xml --enable-shmop --enable-sysvsem --enable-inline-optimization --enable-mbregex --enable-mbstring --enable-ftp --enable-gd-native-ttf --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --without-pear --enable-session --with-curl --with-jpeg-dir --enable-sqlite-utf8 --enable-sysvmsg --enable-sysvshm --enable-wddx --with-xsl --enable-opcache --enable-maintainer-zts

sudo make -j8 && sudo make install

4、php编译完之后开始编译安装 pthreads扩展
5、下载pthreads扩展
https://github.com/krakjoe/pthreads
6、解压并安装
tar -zxf pthreads-3.1.6.tgz
cd pthreads-3.1.6
./configure --with-php-config=/usr/local/php712/bin/php-config
sudo make -j8 && sudo make install

7、配置php.ini
sudo vim /usr/local/php712/etc/php.ini
在 php.ini 最后添加:
[pthreads]
extension=pthreads.so

8、测试pthreads扩展
Thread.php :

<?php
Class Thread {

    public $hooks = array();
    public $args = array();

    public function thread() {

    }

    public function addthread($func) {
        $args = array_slice(func_get_args(), 1);
        $this->hooks[] = $func;
        $this->args[] = $args;
        return true;
    }

    public function runthread() {
        if(isset($_GET['flag'])) {
            $flag = intval($_GET['flag']);
        }

        if($flag || $flag === 0) {
            call_user_func_array($this->hooks[$flag], $this->args[$flag]);
        } else {
            for($i = 0, $size = count($this->hooks); $i < $size; $i++) {
                $fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);

                if($fp) {
                    $out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1rn";
                    $out .= "Host: {$_SERVER['HTTP_HOST']}rn";
                    $out .= "Connection: Closernrn";
                    fputs($fp,$out);
                    fclose($fp);
                }
            }
        }
    }
}

test.php :

include('Thread.php');
Class AsyncOperation extends Thread {

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

    public function run(){
        if($this->arg){
            printf("Hello %s\n", $this->arg);
        }
    }
}
$thread = new AsyncOperation("World");
if($thread->start()){
    $thread->join();
}

PHP 加密 和 解密 算法

<?php
/**
 * $string: 明文 或 密文
 * $operation:DECODE表示解密,其它表示加密
 * $key: 密匙
 * $expiry:密文有效期
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙
    $ckey_length = 4;

    // 密匙
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    // 明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b),解密时会通过这个密匙验证数据完整性
    // 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法,打乱密匙簿,增加随机性,好像很复杂,实际上并不会增加密文的强度
    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或,再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if($operation == 'DECODE') {
        // substr($result, 0, 10) == 0 验证数据有效性
        // substr($result, 0, 10) - time() > 0 验证数据有效性
        // substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
        // 验证数据有效性,请看未加密明文的格式
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        // 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}
?>

调用实例:
<?php
$key = "e10adc3949ba59abbe56e057f20f883e";
$res = authcode("php是最好的语言","ENCODE",$key);
var_dump($res);
echo "
";
var_dump(authcode($res,"DECODE",$key));
string(67) "759880MngibY1yKLjCEtZDVd7ObzYJ39fTCcZkJGWoDovOaGlZeDaYRa5lx5jIXUt7k"
string(21) "php是最好的语言"

安装编译nginx1.9.7+php7.0.0服务器环境

nginx的编译安装
1、安装依赖扩展

$ yum -y install gcc gcc-c++ autoconf automake libtool make cmake
$ yum -y install zlib zlib-devel openssl openssl-devel pcre-devel

zlib: 为nginx提供gzip模块,需要zlib库支持
openssl: 为nginx提供ssl功能
pcre: 为支持地址重写rewrite功能

2、创建用来运行nginx的用户及组

$ groupadd nginx
$ useradd -g nginx -M nginx

-g参数为nginx用户指定了一个组。-M参数保证其不自动生成home目录。

但通过上面的用户创建之后,nginx用户可以通过设置一个密码登陆到服务器,这个不是我们想要的,我们禁用它的ssh登陆权限.禁止用户 登陆也很方便,只需要修改配置文件中有关用户和用户组的信息即可。

$ vi /etc/passwd

找到nginx,将后面的 /bin/bash 改为 /sbin/nologin 即可。
OK,用户处理完毕。
3、开始编译安装Nginx
configure配置如下:

$ ./configure --prefix=/usr/local/nginx \
--pid-path=/usr/local/nginx/run/nginx.pid \
--user=nginx \
--group=nginx \
--with-pcre \
--without-mail_pop3_module \
--without-mail_imap_module \
--without-mail_smtp_module

3.1、安装

$ make
$ make install

安装到这里就结束了,但是,安装完可没完事儿,nginx还没有运行起来,你可以先去看看安装的结果,并且运行nginx服务器:

$ cd /usr/local/nginx
$ sbin/nginx

这样就运行起来了,访问你的服务器ip,看看能否看到ngin的欢迎页面吧。(不要让其他软件占用80端口哦)默认情况下网页文件放在/usr/local/nginx/html下,不符合我们的使用习惯,这个需要修改nginx的配置文件来修改,不过即使不修改,我们也是可以正常使用的,我们就不详细解释nginx的配置了。

不过为了使用我们熟悉的service操作,这里提供一个 程序 ,放到/etc/ini.d/目录下,并执行:

$ chmod +x /etc/init.d/nginx 
$ chkconfig --add nginx
$ chkconfig nginx on
$ /usr/local/nginx/sbin/nginx -s reload #重新加载nginx服务
$ /usr/local/nginx/sbin/nginx -s quit  #退出nginx服务

PHP7的编译安装
1、先从官方网站下载php7,并且解压,由于上面这篇文章已经有了相关步骤,就不做过多详解:

$ wget http://am1.php.net/get/php-7.0.0.tar.gz/from/this/mirror
$ tar zvxf php-7.0.0.tar.gz
$ cd php-7.0.0

2、编译前的配置:

$ ./configure --prefix=/usr/local/php7 \
--with-config-file-path=/usr/local/php7/etc \
--with-config-file-scan-dir=/usr/local/php7/etc/php.d \
--with-mcrypt=/usr/include \
--enable-mysqlnd \
--with-mysqli \
--with-pdo-mysql \
--enable-fpm \
--with-fpm-user=nginx \
--with-fpm-group=nginx \
--with-gd \
--with-iconv \
--with-zlib \
--enable-xml \
--enable-shmop \
--enable-sysvsem \
--enable-inline-optimization \
--enable-mbregex \
--enable-mbstring \
--enable-ftp \
--enable-gd-native-ttf \
--with-openssl \
--enable-pcntl \
--enable-sockets \
--with-xmlrpc \
--enable-zip \
--enable-soap \
--without-pear \
--with-gettext \
--enable-session \
--with-curl \
--with-jpeg-dir \
--with-freetype-dir \
--enable-opcache

3、配置无误后执行:

$ make
$ make install

4、调整php配置

默认安装好之后,你会发现/usr/local/php7/etc下面没有php.ini文件,这个去哪里要呢?在php7的源码安装包都有。可以看到有两个php.ini-xxx文件,我们可以分别vi打开来看下,一个是产品模式,一个是开发模式。

$ cd /usr/src/php-7.0.0/
$ ls
$ cp php.ini-production /usr/local/php7/etc/php.ini
$ vi /usr/local/php7/etc/php.ini

5、启用php-fpm服务

$ cd /usr/local/php7/etc
$ mv php-fpm.conf.default php-fpm.conf
$ mv php-fpm.d/www.conf.defualt php-fpm.d/www.conf

6、搞定php-fpm的服务载入:
就像上面的nginx一样,我们希望使用service php-fpm start|stop|restart这些操作来实现服务的重启,但没有像nginx那么复杂,php编译好之后,给我们提供了一个php-fpm的程序,不需要我再编写分享了。这个文件放在php编译源码目录中:

 $ cd /usr/src/php-7.0.0/sapi/fpm
 $ ls
 $ cp init.d.php-fpm /etc/init.d/php-fpm
 $ chmod +x /etc/init.d/php-fpm
 $ chkconfig --add php-fpm
 $ chkconfig php-fpm on

通过上面这个操作,我们就可以使用 sevice php-fpm start 来启用php-fpm了。用 ps -ef | grep php-fpm 看看进程

7、nginx代理php实现访问:
通过上面的操作,nginx和php-fpm服务都被我们跑起来了,但是php-fpm走的是127.0.0.1:9000,外网是无法访问的,而且我们也不可能直接通过php-fpm给外网提供服务,我们用nginx去代理9000端口执行php。实际上这个过程只需要对nginx进行配置即可,fpm已经在后台运行了,我们需要在nginx的配置文件中增加代理的规则,即可让用户在访问80端口,请求php的时候,交由后端的fpm去执行,并返回结果。

$ vi /usr/local/nginx/conf/nginx.conf
找到以下代码并去掉注释
#location ~ \.php$ {
  #   root           html;
  #  fastcgi_pass   127.0.0.1:9000;
  #  fastcgi_index  index.php;
  #  fastcgi_param  SCRIPT_FILENAME  /script$fastcgi_script_name;
  #  include        fastcgi_params;
#}
修改后的代码
location ~ \.php$ {
    root           html;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /$document_root$fastcgi_script_name;
    include        fastcgi_params;
}
重启nginx
service nginx reload