标签 php 下的文章

nginx和php-fpm环境记录php错误日志

转载自 http://www.jb51.net/article/49645.htm
nginx与apache不一样,在apache中可以直接指定php的错误日志,那样在php执行中的错误信息就直接输入到php的错误日志中,可以方便查询。
在nginx中事情就变成了这样:nginx只对页面的访问做access记录日志。不会有php的error log 信息。或者记录如下的很模糊的错误信息

2016/10/18 15:12:53 [error] 3232#0: *4688 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 121.121.121.121, server: dz.snsnb.com, request: "GET /admin.php?m=content&c=create_html&a=public_index&pc_hash=46yC97 HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "xxx.xxx.xxx", referrer: "http://xxx.xxx.xxx/admin.php?m=admin"

nginx把对php的请求发给php-fpm fastcgi进程来处理,默认的php-fpm只会输出php-fpm的错误信息,在php-fpm的errors log里也看不到php的errorlog。
原因是php-fpm的配置文件php-fpm.conf中默认是关闭worker进程的错误输出,直接把他们重定向到/dev/null,所以我们在nginx的error log 和php-fpm的errorlog都看不到php的错误日志。
所以我们要进行如下的设置就能查看到nginx下php-fpm不记录php错误日志的方法:

1,修改php-fpm.conf中的配置,如果没有请增加:(这一步做完,php的错误记录就会记录在php-fpm的日志中)

[global]
; Note: the default prefix is /usr/local/php/var
error_log = log/php_error_log
[www]
catch_workers_output = yes

2.修改php.ini中配置,没有则增加:(这一步无效,可能是与我的环境有关,不纠结了,第二步就已经可以看错误日志了)

log_errors = On
error_log = "/usr/local/php/var/log/error_log"
error_reporting=E_ALL&~E_NOTICE

3.重启php-fpm

当PHP执行错误时就能看到错误日志在”/usr/local/lnmp/php/var/log/php_error_log”中了
如果出现:

[root@localhost etc]# service php-fpm restart
Gracefully shutting down php-fpm . done
Starting php-fpm [17-Apr-2014 18:40:52] ERROR: [/usr/local/php/etc/php-fpm.conf:5] unknown entry 'catch_workers_
[17-Apr-2014 18:40:52] ERROR: failed to load configuration file '/usr/local/php/etc/php-fpm.conf'
[17-Apr-2014 18:40:52] ERROR: FPM initialization failed
 failed

那请在第一步的时候,认真将配置写入相对应的组中,不然就出现上面的:

ERROR: [/usr/local/php/etc/php-fpm.conf:5] unknown entry ‘catch_workers_output'

编译安装nginx,php

安装nginx

安装pcre

为了支持rewrite功能,我们需要安装pcre

yum install -y pcre* //如过你已经装了,请跳过这一步

需要ssl的支持,如果不需要ssl支持,请跳过这一步

yum install -y openssl*

编译安装

./configure --prefix=/usr/local/nginx-1.8.1 \
--with-http_spdy_module \
--with-http_stub_status_module \
--with-pcre

--with-http_stub_status_module:支持nginx状态查询
--with-http_spdy_module:支持google的spdy,想了解请百度spdy,这个必须有ssl的支持
--with-pcre:为了支持rewrite重写功能,必须制定pcre

报错

checking for OS
 + Linux 2.6.32-642.4.2.el6.x86_64 x86_64
checking for C compiler ... not found

./configure: error: C compiler cc is not found

安装所需的软件

yum -y install gcc gcc-c++

再 configure

报错

./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib=<path> option.

安装所需软件

yum install -y zlib-devel

再 configure

Configuration summary
  + using system PCRE library
  + OpenSSL library is not used
  + using builtin md5 code
  + sha1 library is not found
  + using system zlib library

  nginx path prefix: "/usr/local/nginx-1.8.1"
  nginx binary file: "/usr/local/nginx-1.8.1/sbin/nginx"
  nginx configuration prefix: "/usr/local/nginx-1.8.1/conf"
  nginx configuration file: "/usr/local/nginx-1.8.1/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx-1.8.1/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx-1.8.1/logs/error.log"
  nginx http access log file: "/usr/local/nginx-1.8.1/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

安装

make //确定你的服务器有安装make,如果没有安装请执行yum install make
make install

添加启动脚本

这个网页可以 https://www.nginx.com/resources/wiki/start/topics/examples/redhatnginxinit/ 下载启动脚本

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/etc/nginx/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:.*--user=" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -n "$user" ]; then
      if [ -z "`grep $user /etc/passwd`" ]; then
         useradd -M -s /bin/nologin $user
      fi
      options=`$nginx -V 2>&1 | grep 'configure arguments:'`
      for opt in $options; do
          if [ `echo $opt | grep '.*-temp-path'` ]; then
              value=`echo $opt | cut -d "=" -f 2`
              if [ ! -d "$value" ]; then
                  # echo "creating" $value
                  mkdir -p $value && chown -R $user $value
              fi
          fi
       done
    fi
}

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    sleep 1
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

修改下面脚本中两项为实际的路径

#nginx="/usr/sbin/nginx"
nginx="/usr/local/nginx-1.8.1/sbin/nginx"
#NGINX_CONF_FILE="/etc/nginx/nginx.conf"
NGINX_CONF_FILE="/usr/local/nginx-1.8.1/conf/nginx.conf"

把文件写入到 /etc/init.d/nginx

给权限,开启服务器

chmod +x /etc/init.d/nginx
service nginx start

php 编译安装,版本 php-7.0.11

取官方下载程序包

安装依赖包

yum install gcc make gd-devel libjpeg-devel libpng-devel libxml2-devel bzip2-devel libcurl-devel -y

configure: error: Please reinstall the libzip distribution

7.3需要安装高版本的libzip

# 先安装高版本的cmake,不然无法安装libzip
wget https://gitlab.kitware.com/cmake/cmake/-/archive/v3.0.2/cmake-v3.0.2.tar.gz
tar -zxvf cmake-v3.0.2.tar.gz 
cd cmake-v3.0.2
./bootstrap 
gmake && gmake install

# 安装libzip
先删除老的版本
yum remove libzip

wget https://nih.at/libzip/libzip-1.5.1.tar.gz
tar -zxvf libzip-1.5.1.tar.gz
cd libzip-1.5.1
mkdir build
cd build
cmake ..
make
make test
make install

编译安装(64位系统需要加上最后一个 --with-libdir=lib64)

./configure --prefix=/usr/local/php-7.0.11 \
--with-config-file-path=/usr/local/php-7.0.11/etc \
--with-bz2 \
--with-curl \
--enable-ftp \
--enable-sockets \
--disable-ipv6 \
--with-gd \
--with-jpeg-dir=/usr/local \
--with-png-dir=/usr/local \
--with-freetype-dir=/usr/local \
--enable-gd-native-ttf \
--with-iconv-dir=/usr/local \
--enable-mbstring \
--enable-calendar \
--with-gettext \
--with-libxml-dir=/usr/local \
--with-zlib \
--with-pdo-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-mysql=mysqlnd \
--enable-dom \
--enable-xml \
--enable-fpm \
--with-libdir=lib64

安装

make 
make test 
make install

复制 php 配置文件

cp php.ini-production /usr/local/php-7.0.11/etc/php.ini

复制 php-fpm 配置文件

cp /usr/local/php-7.0.11/etc/php-fpm.d/www.conf.default /usr/local/php-7.0.11/etc/php-fpm.d/www.conf

加入 service 管理脚本,修改到实际的路径即可

vim /etc/init.d/php7.0.11-fpm
#!/bin/bash
#
# Startup script for the PHP-FPM server.
#
# chkconfig: 345 85 15
# description: PHP is an HTML-embedded scripting language
# processname: php-7.0.11-fpm
# config: /usr/local/php/etc/php.ini
# config: /usr/local/php-7.0.11/etc/php.ini

# Source function library.
. /etc/rc.d/init.d/functions
# php 编译安装的目录
PHP_DIRECTORY=php-7.0.11
PHP_PATH=/usr/local/
DESC="php7.0.11-fpm daemon"
NAME=php-fpm
# php-fpm路径
DAEMON=$PHP_PATH/$PHP_DIRECTORY/sbin/$NAME
# 配置文件路径
CONFIGFILE=$PHP_PATH$PHP_DIRECTORY/etc/php-fpm.d/www.conf
# PID文件路径(在php-fpm.conf设置)
PIDFILE=$PHP_PATH/$PHP_DIRECTORY/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$PHP_DIRECORY

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

rh_start() {
  $DAEMON -y $CONFIGFILE || echo -n " already running"
}
rh_stop() {
  kill -QUIT `cat $PIDFILE` || echo -n " not running"
}

rh_reload() {
  kill -HUP `cat $PIDFILE` || echo -n " can't reload"
}

case "$1" in
  start)
        echo -n "Starting $DESC: $NAME"
        rh_start
        echo "."
        ;;
  stop)
        echo -n "Stopping $DESC: $NAME"
        rh_stop
        echo "."
        ;;
  reload)
        echo -n "Reloading $DESC configuration..."
        rh_reload
        echo "reloaded."
  ;;
  restart)
        echo -n "Restarting $DESC: $NAME"
        rh_stop
        sleep 1
        rh_start
        echo "."
        ;;
  *)
         echo "Usage: $SCRIPTNAME {start|stop|restart|reload}" >&2
         exit 3
        ;;
esac
exit 0

给执行权限
chmod +x php-7.0.11-fpm

设置 php-fpm pid 文件
在 php-fpm 配置文件的 [global] 部分加入 pid 设置项

vim /usr/local/php-7.0.11/etc/php-fpm.d/www.conf
#添加
[global]
pid = run/php-fpm.pid

nginx 配置

server {
        server_name www.jintest1.com;
        root /www/www.jintest1.com;
        index index.html index.php;
        location ~ .*\.(php)?$
        {
                expires -1s;
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_param PATH_INFO $fastcgi_path_info;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_pass 127.0.0.1:9000;

        }
}

ok

利用余弦值计算字串的相似性

之前用字符串匹配的方式做过一次,感觉这个很厉害,竟然可以用余弦来做,准不准不知道,之前做过php的东西都没记录下来,现在开始记录下
参考网址:http://www.ruanyifeng.com/blog/2013/03/cosine_similarity.html

    public function test($value='')
    {
        $textB = "我喜欢看电视,不喜欢看电影。";
        $textA = "我不喜欢看电视,也不喜欢看电影。";
        // 1.分词
        $scws = scws_new();
        $scws->set_charset("utf8");
        $scws->send_text($textA);

        $wordAList = $scws->get_words('~un');
        $scws->send_text($textB);
        $wordBList = $scws->get_words('~un');
        /**
        *   分词完成之后的格式
        *   [0] => array(4) {
        *       ["word"] => string(9) "我喜欢"
        *       ["times"] => int(1)
        *       ["weight"] => float(4.8200001716614)
        *       ["attr"] => string(1) "n"
        *   }
        */
        // 2.列出所有的词
        // 提取多维数组的值
        $allWord = array_unique(array_merge(array_column($wordAList, 'word'),array_column($wordBList, 'word')));
        /**
        *   字符串数组
        *   [0] => string(9) "我喜欢"
        *   [1] => string(3) "看"
        *   [2] => string(6) "电视"
        *   [3] => string(3) "不"
        *   [4] => string(6) "喜欢"
        *   [5] => string(9) "看电影"
        *   [6] => string(3) "我"
        *   [11] => string(3) "也"
        */
        // 3.计算词频向量
        $textATimes = array();// 整型数组
        $textBTimes = array();
        foreach ($allWord as $key => $value) {
            // 提取多维数组的值
            $a = array_filter($wordAList, function($arr) use ($value) {
                if($value == $arr['word'])
                {
                    return $arr['times'];
                }
                return 0; 
            });
            $textATimes[] = (Int)(current($a)['times']);
            $b = array_filter($wordBList, function($arr) use ($value) {
                if($value == $arr['word'])
                {
                    return $arr['times'];
                }
                return 0; 
            });
            $textBTimes[] = (Int)(current($b)['times']);
        }

        // 使用余弦计算
        $topNumber = 0;
        $bottomNumberA = 0;
        $bottomNumberB = 0;
        foreach ($textATimes as $key => $value) {
            $topNumber +=  $value * $textBTimes[$key];
            $bottomNumberA += $value * $value;
            $bottomNumberB += $textBTimes[$key] * $textBTimes[$key];
        }
        $res = $topNumber / (sqrt($bottomNumberA) * sqrt($bottomNumberB));
        // 余弦值越接近1,就表明夹角越接近0度,也就是两个向量越相似,这就叫"余弦相似性"
        // float(0.79259392390122)
        dump($res);
    }

自己执行指定控制器的action

$whereWithForum = array(
                        'fid' =>  $tempForumInfo['board_id'],
                        'page' => 1,
                        'pageSize' => 5,
                        'sort' => 'new',
                        'filterType' => '',
                        'filterId' => 0,
                        'isImageList' => 0,
                        'topOrder' => 0
                    );
$newsForumList = Yii::app()->getController("forum/topiclist")->createAction('topiclist')->getResult($whereWithForum);

centos7安装nginx和php碰到的一些问题

nginx安装,参考网址:https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-centos-7

rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

yum install nginx

安装php和php-fpm

yum install --enablerepo=remi --enablerepo=remi-php56 php  php-fpm

因为我的php安装的是5.6的,所以的指定这个源里面安装php-fpm,不然一直报错

修改配置文件

vi /etc/php.ini

修改成0(这个配置值说是不安全的设置,参考网址:http://www.laruence.com/2010/05/20/1495.html)

cgi.fix_pathinfo=0

修改配置文件

vim /etc/nginx/conf.d/default.conf

server {
    listen       80;
    server_name  www.scchary.com;
    root /home/samba1/public_html;
    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        #root   /usr/share/nginx/html;
        #root /home/samba1/public_html;
        index  index.php index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        #root           /home/samba1/public_html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

修改上面配置文件的时候,运行php文件的时候,老是显示没有找到,后来在这里找到了答案,参考网址http://www.nginx.cn/562.html

server {
    listen   [::]:80;
    server_name  example.com www.example.com;
    access_log  /var/www/logs/example.com.access.log;  

    location / {
        root   /var/www/example.com;
        index  index.html index.htm index.pl;
    }

    location /images {
        autoindex on;
    }

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/example.com$fastcgi_script_name;
        include fastcgi_params;
    }
}

这个配置中有很多不合理的地方,其中一个明显的问题就是root指令被放到了location / 块。如果root指令被定义在location块中那么该root指令只能对其所在的location生效。其它locaiont中没有root指令,像location /images块不会匹配任何请求,需要在每个请求中重复配置root指令来解决这个问题。因此我们需要把root指令放在server块,这样各个location就会继承父server块定义的\$document_root,如果某个location需要定义一个不同的\$document_root,则可以在location单独定义一个root指令。

另一个问题就是fastCGI参数SCRIPT_FILENAME 是写死的。如果修改了root指令的值或者移动文件到别的目录,php-fpm会返回“No input file specified”错误,因为SCRIPT_FILENAME在配置中是写死的并没有随着$doucument_root变化而变化,我们可以修改SCRIPT_FILENAME配置如下:

fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;

所以我们不能忘记在server块中配置root指令,不然\$document_root的值为空,只会传\$fastcgi_script_name到php-fpm,这样就会导致“No input file specified”错误。

最后在测试php文件里面输出phpinfo的时候,出现了一个未定义时区的错误,修改了配置文件还是报错,最后重启了下php-fpm就好了