分类 技术 下的文章

PHP 5.3.22在windows7中安装 imagick 扩展。

开发机上win7因为依赖扩展等的原因停留在5.3.22上,最近在处理缩小 PNG 和 GIF 图片时,发现 GD 对图片大小不但没有减少,而且还巨大无比,这是无法接受的。

记一下如何安装 PHP-imagick 扩展:

1、下载对应版本的php_imagick.dll,解压至PHP扩展目录,例如C:\php\ext\

下载地址:http://windows.php.net/downloads/pecl/releases/imagick/

(博主用的版本是3.1.2)

2、安装重启server后,打开 页面,发现:

ImageMagick number of supported formats: 0
ImageMagick supported formats : no value

这时,说明你本机没有安装 ImageMagick。

那你的机器适合 ImageMagick 哪个版本呢?

还是 phpinfo 页面:

imagick.jpg

这里提示你应该安装哪个版本:

ImageMagick version ImageMagick 6.8.8-4 Q16 x86 2014-01-29 http://www.imagemagick.org

这个版本年代太比较久远,我只在CSDN上找到下载:http://download.csdn.net/detail/lqt0307/5184966

下载,安装路径选个:c:\imagick\ 一路下一步,安装结束

3、计算机->右键->属性->高级系统设置->高级->环境变量,添加「系统变量」:
变量名:MAGICK_HOME
变量值:C:\ImageMagick\ (你的安装路径)

path.jpg

4、将C:\ImageMagick\modules\coders\ 和C:\ImageMagick\modules\filters\ 里的文件拷至C:\ImageMagick\目录。

5、重启你的 webserver。

再次打开phpinfo页面,你能看到:

phpinfo.jpg

恭喜,安装成功!

后续

centos 安装 imagick 扩展顺带如下:

yum install php-pear php-devel gcc
yum install ImageMagick ImageMagick-devel
pecl install imagick
echo "extension=imagick.so" > /etc/php.d/imagick.ini

JS 禁止用户返回上一页。

要求,禁止返回上一页:

history.pushState({ page: 1 }, "pageTitle", "#jump"); 
window.onhashchange = function (event) {window.location.hash = "jump"; }; 

利用七牛自带的 qshell 定期清理过期文件~

新项目需要上传临时图片在七牛中,七牛对存储空间有收费,于是乎,我们需要定期删除(仅保存半天内内)的文件,附上代码:

#!/bin/bash 
#要删除的bucket 
bucket="text"
currentTime=`date "+%Y-%m-%d %H:%M:%S"`
timestamp=`date -d "$currentTime" +%s`
# 保存多久的文件
let starttime=($timestamp-43200)
#配置您的账号信息,具体请参考:https://github.com/qiniu/qshell
qshell account xxx xxx
#取出bucket中的有文件
qshell listbucket $bucket ${bucket}_file.org
#取出key和创建时间
cat ${bucket}_file.org | awk '{print $1,$4}' > ${bucket}_file.list
let count=0
while read line
do
   time=${line#* }
   key=${line%% *}
   let time=time/10000000
   # 对比时间戳
   if [ $time -le $starttime ]; then
      res=`qshell delete ${bucket} ${key}`
      let count+=1
      echo $count, $key, $res
   fi
done < ${bucket}_file.list
# 清除产生的临时
rm -rf ${bucket}_*

每个小时清理一次的crontab:

    0 * * * * cd /home/www/ && sh clear_qiniu.sh > /home/www/clear_qiniu.log

用PHP实现 HTTP断点续传、分块下载文件(Socket)

最近尝试使用 PHP 在做一些后台的定时任务,包括大文件的下载。

想看看网上是否有满足需求的代码,找了半天无果,于是撸撸袖子自己写了一枚,

废话不说,上代码:

<?php

/**
 * User: djunny
 * Date: 2016-04-29
 * Time: 17:18
 * Mail: 199962760@qq.com
 * 支持断点下载的类
 */
class downloader {

    /**
     * download file to local path
     *
     * @param       $url
     * @param       $save_file
     * @param int   $speed
     * @param array $headers
     * @param int   $timeout
     * @return bool
     * @throws Exception
     */
    static function get($url, $save_file, $speed = 10240, $headers = array(), $timeout = 10) {
        $url_info = self::parse_url($url);
        if (!$url_info['host']) {
            throw new Exception('Url is Invalid');
        }

        // default header
        $def_headers = array(
            'Accept'          => '*/*',
            'User-Agent'      => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
            'Accept-Encoding' => 'gzip, deflate',
            'Host'            => $url_info['host'],
            'Connection'      => 'Close',
            'Accept-Language' => 'zh-cn',
        );

        // merge heade
        $headers = array_merge($def_headers, $headers);
        // get content length
        $content_length = self::get_content_size($url_info['host'], $url_info['port'], $url_info['request'], $headers, $timeout);

        // content length not exist
        if (!$content_length) {
            throw new Exception('Content-Length is Not Exists');
        }
        // get exists length
        $exists_length = is_file($save_file) ? filesize($save_file) : 0;
        // get tmp data file
        $data_file = $save_file . '.data';
        // get tmp data
        $exists_data = is_file($data_file) ? json_decode(file_get_contents($data_file), 1) : array();
        // check file is valid
        if ($exists_length == $content_length) {
            $exists_data && @unlink($data_file);
            return true;
        }
        // check file is expire
        if ($exists_data['length'] != $content_length || $exists_length > $content_length) {
            $exists_data = array(
                'length' => $content_length,
            );
        }
        // write exists data
        file_put_contents($data_file, json_encode($exists_data));

        try {
            $download_status = self::download_content($url_info['host'], $url_info['port'], $url_info['request'], $save_file, $content_length, $exists_length, $speed, $headers, $timeout);
            if ($download_status) {
                @unlink($data_file);
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        return true;
    }

    /**
     * parse url
     *
     * @param $url
     * @return bool|mixed
     */
    static function parse_url($url) {
        $url_info = parse_url($url);
        if (!$url_info['host']) {
            return false;
        }
        $url_info['port']    = $url_info['port'] ? $url_info['host'] : 80;
        $url_info['request'] = $url_info['path'] . ($url_info['query'] ? '?' . $url_info['query'] : '');
        return $url_info;
    }

    /**
     * download content by chunk
     *
     * @param $host
     * @param $port
     * @param $url_path
     * @param $headers
     * @param $timeout
     */
    static function download_content($host, $port, $url_path, $save_file, $content_length, $range_start, $speed, &$headers, $timeout) {
        $request = self::build_header('GET', $url_path, $headers, $range_start);
        $fsocket = @fsockopen($host, $port, $errno, $errstr, $timeout);
        stream_set_blocking($fsocket, TRUE);
        stream_set_timeout($fsocket, $timeout);
        fwrite($fsocket, $request);
        $status = stream_get_meta_data($fsocket);
        if ($status['timed_out']) {
            throw new Exception('Socket Connect Timeout');
        }
        $is_header_end = 0;
        $total_size    = $range_start;
        $file_fp       = fopen($save_file, 'a+');
        while (!feof($fsocket)) {
            if (!$is_header_end) {
                $line = @fgets($fsocket);
                if (in_array($line, array("\n", "\r\n"))) {
                    $is_header_end = 1;
                }
                continue;
            }
            $resp        = fread($fsocket, $speed);
            $read_length = strlen($resp);
            if ($resp === false || $content_length < $total_size + $read_length) {
                fclose($fsocket);
                fclose($file_fp);
                throw new Exception('Socket I/O Error Or File Was Changed');
            }
            $total_size += $read_length;
            fputs($file_fp, $resp);
            // check file end
            if ($content_length == $total_size) {
                break;
            }
            sleep(1);
            // for test
            //break;
        }
        fclose($fsocket);
        fclose($file_fp);
        return true;

    }

    /**
     * get content length
     *
     * @param $host
     * @param $port
     * @param $url_path
     * @param $headers
     * @param $timeout
     * @return int
     */
    static function get_content_size($host, $port, $url_path, &$headers, $timeout) {
        $request = self::build_header('HEAD', $url_path, $headers);
        $fsocket = @fsockopen($host, $port, $errno, $errstr, $timeout);
        stream_set_blocking($fsocket, TRUE);
        stream_set_timeout($fsocket, $timeout);
        fwrite($fsocket, $request);
        $status = stream_get_meta_data($fsocket);
        $length = 0;
        if ($status['timed_out']) {
            return 0;
        }
        while (!feof($fsocket)) {
            $line = @fgets($fsocket);
            if (in_array($line, array("\n", "\r\n"))) {
                break;
            }
            $line = strtolower($line);
            // get location
            if (substr($line, 0, 9) == 'location:') {
                $location = trim(substr($line, 9));
                $url_info = self::parse_url($location);
                if (!$url_info['host']) {
                    return 0;
                }
                fclose($fsocket);
                return self::get_content_size($url_info['host'], $url_info['port'], $url_info['request'], $headers, $timeout);
            }
            // get content length
            if (strpos($line, 'content-length:') !== false) {
                list(, $length) = explode('content-length:', $line);
                $length = (int)trim($length);
            }
        }
        fclose($fsocket);
        return $length;

    }

    /**
     * build header for socket
     *
     * @param     $action
     * @param     $url_path
     * @param     $headers
     * @param int $range_start
     * @return string
     */
    static function build_header($action, $url_path, &$headers, $range_start = -1) {
        $out = $action . " {$url_path} HTTP/1.0\r\n";
        foreach ($headers as $hkey => $hval) {
            $out .= $hkey . ': ' . $hval . "\r\n";
        }
        if ($range_start > -1) {
            $out .= "Accept-Ranges: bytes\r\n";
            $out .= "Range: bytes={$range_start}-\r\n";
        }
        $out .= "\r\n";

        return $out;
    }
}

?>

用法很简单:

try {
if (downloader::get('http://dzs.aqtxt.com/files/11/23636/201604230358308081.rar', 'test.rar')) {
//todo
echo 'Download Succ';
}
} catch (Exception $e) {
echo 'Download Failed';
}

Centos使用yum安装PHP7、PHP-MEMCACHE和PHP-RAR扩展

PHP7的性能表现的确让人眼前一亮,近来新开了一台Centos服务器,于是折腾起来。

首先,我们安装一下 RPM 包(根据你的系统版本安装):

#安装RPM源 CentOS/RHEL 7.x

rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

#安装RPM源 CentOS/RHEL 6.x

rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el6/latest.rpm

#安装php7和常用扩展

yum install -y php70w php70w-devel php70w-fpm php70w-opcache php70w-mysqlnd php70w-pdo php70w-gd php70w-mbstring

#安装php-memcache扩展

wget https://github.com/websupport-sk/pecl-memcache/archive/php7.zip -O pecl-php-memcached.zip
unzip pecl-php-memcached.zip
cd pecl-memcache*
phpize
./configure
make
make install
echo "[memcache]
extension=memcache.so" >/etc/php.d/memcache.ini

#检测 MEMCACHE 扩展是否正常

php -m | grep memcache

#安装PHP-RAR扩展

wget https://github.com/Jan-E/php_pecl_rar7/archive/master.zip -O pecl-php-rar.zip
unzip pecl-php-rar.zip
phpize
./configure
make 
make install
# 写入rar配置
echo "[rar]
extension=rar.so" >/etc/php.d/rar.ini

#检测 RAR 扩展是否正常

php -m | grep rar

安装完毕,再设置一下基础参数(请视需求自行修改):

sed -i "s#;pid = run/php-fpm.pid#pid = run/php-fpm.pid#g" /etc/php-fpm.d/www.conf
sed -i "s#;error_log#error_log#g" /etc/php-fpm.d/www.conf
sed -i "s#;log_level = notice#log_level = warning#g" /etc/php-fpm.d/www.conf
sed -i "s#; process.max = 128#process.max = 128#g" /etc/php-fpm.d/www.conf
sed -i "s#;slowlog#slowlog#g" /etc/php-fpm.d/www.conf
sed -i "s#; events.mechanism = epoll#events.mechanism = epoll#g" /etc/php-fpm.d/www.conf
sed -i "s#pm.max_children = 5#pm.max_children = 10#g" /etc/php-fpm.d/www.conf
sed -i "s#pm.start_servers = 2#pm.start_servers = 4#g" /etc/php-fpm.d/www.conf
sed -i "s#pm.min_spare_servers = 1#pm.min_spare_servers = 2#g" /etc/php-fpm.d/www.conf
sed -i "s#pm.max_spare_servers = 3#pm.max_spare_servers = 5#g" /etc/php-fpm.d/www.conf
sed -i "s#;pm.max_requests = 500#pm.max_requests = 500#g" /etc/php-fpm.d/www.conf
sed -i "s#;listen.allowed_clients#listen.allowed_clients#g" /etc/php-fpm.d/www.conf
sed -i "s#;listen.owner = nobody#listen.owner = www#g" /etc/php-fpm.d/www.conf
sed -i "s#;listen.group = nobody#listen.group = www#g" /etc/php-fpm.d/www.conf
sed -i "s#user = apache#user = www#g" /etc/php-fpm.d/www.conf
sed -i "s#group = apache#group = www#g" /etc/php-fpm.d/www.conf
#sed -i "s#listen = 127.0.0.1:9000#;listen = 127.0.0.1:9000\nlisten = /tmp/php-cgi.sock#g" /etc/php-fpm.d/www.conf
sed -i "s#;listen.mode = 0666#listen.mode = 0666#g" /etc/php-fpm.d/www.conf
sed -i "s#;slowlog#slowlog#g" /etc/php-fpm.d/www.conf

sed -i "s#;access.format#access.format#g" /etc/php-fpm.d/www.conf
sed -i "s#;access.log = log/$pool.access.log#access.log = /usr/local/php/var/log/$pool.access.log#g" /etc/php-fpm.d/www.conf

sed -i 's@expose_php = On@expose_php = Off@g' /etc/php.ini
sed -i 's@short_open_tag = Off@short_open_tag = On@g' /etc/php.ini
sed -i 's@max_execution_time = 30@max_execution_time = 60@g' /etc/php.ini
sed -i 's@post_max_size = 8M@post_max_size = 50M@g' /etc/php.ini
sed -i 's@upload_max_filesize = 2M@upload_max_filesize = 50M@g' /etc/php.ini

最后,启动服务:

service php-fpm restart