用PHP从本地提取视频并向浏览器输出的方法

有时,在一些特殊场景中,我们需要访问视频时,需要预先通过PHP做一些校验,校验通过后,才允许将视频数据输出给浏览器。

下面这段代码实现了用PHP从本地提取视频文件,并通过header函数以字节的方式向浏览器输出视频数据流。

<?php

//需要下载的文件
$file_name = 'test.mp4';

//下载文件必须先要将文件打开,写入内存
$fp = fopen($file_name, 'r+');

//判断文件是否存在
if (!file_exists($file_name)) {
    echo "文件不存在";
    exit();
}

//判断文件大小
$file_size = filesize($file_name);

//返回的文件
header('Content-type: application/octet-stream');

//按照字节格式返回
header('Accept-Ranges: bytes');

//返回文件大小
header('Accept-Length: ' . $file_size);

//弹出客户端对话框,对应的文件名
header('Content-Disposition: attachment; filename=' . $file_name);

//防止服务器瞬时压力增大,分段读取
$buffer = 4096;

while(!feof($fp)) {
    $file_data = fread($fp, $buffer);
    echo $file_data;
}

//关闭文件
fclose($fp);

?>

PHP利用FFmpeg读取视频播放时长和码率等信息

代码如下:

<?php
define('FFMPEG_PATH', '/usr/local/ffmpeg2/bin/ffmpeg -i "%s" 2>&1');

function getVideoInfo($file) {
    
    $command = sprintf(FFMPEG_PATH, $file);
    
    ob_start();
    passthru($command);
    $info = ob_get_contents();
    ob_end_clean();
    
    $data = array();
    if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $info, $match)) {
        $data['duration'] = $match[1]; //播放时间
        $arr_duration = explode(':', $match[1]);
        $data['seconds'] = $arr_duration[0] * 3600 + $arr_duration[1] * 60 + $arr_duration[2]; //转换播放时间为秒数
        $data['start'] = $match[2]; //开始时间
        $data['bitrate'] = $match[3]; //码率(kb)
    }
    if (preg_match("/Video: (.*?), (.*?), (.*?)[,\s]/", $info, $match)) {
        $data['vcodec'] = $match[1]; //视频编码格式
        $data['vformat'] = $match[2]; //视频格式
        $data['resolution'] = $match[3]; //视频分辨率
        $arr_resolution = explode('x', $match[3]);
        $data['width'] = $arr_resolution[0];
        $data['height'] = $arr_resolution[1];
    }
    if (preg_match("/Audio: (\w*), (\d*) Hz/", $info, $match)) {
        $data['acodec'] = $match[1]; //音频编码
        $data['asamplerate'] = $match[2]; //音频采样频率
    }
    if (isset($data['seconds']) && isset($data['start'])) {
        $data['play_time'] = $data['seconds'] + $data['start']; //实际播放时间
    }
    $data['size'] = filesize($file); //文件大小
    return $data;
}

//用法
$video_info = getVideoInfo('video.mp4');
print_r($video_info);
?>

本例中,会用到passthru,可能部分虚拟主机会将此命令禁用。

用PHP实现URL转换短网址的算法

短网址(Short URL) ,顾名思义就是在形式上比较短的网址。在Web 2.0的今天,不得不说,这是一个潮流。目前已经有许多类似服务,借助短网址您可以用简短的网址替代原来冗长的网址,让使用者可以更容易的分享链接。

下面是用PHP实现短网址转换的算法,代码如下:

<?php
//短网址生成算法
class ShortUrl {
    
    //字符表
    public static $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static function encode($url)
    {
        $key = 'abc'; //加盐
        $urlhash = md5($key . $url);
        $len = strlen($urlhash);

        //将加密后的串分成4段,每段4字节,对每段进行计算,一共可以生成四组短连接
        for ($i = 0; $i < 4; $i++) {
            $urlhash_piece = substr($urlhash, $i * $len / 4, $len / 4);
            
            //将分段的位与0x3fffffff做位与,0x3fffffff表示二进制数的30个1,即30位以后的加密串都归零
            //此处需要用到hexdec()将16进制字符串转为10进制数值型,否则运算会不正常
            $hex = hexdec($urlhash_piece) & 0x3fffffff;

            //域名根据需求填写
            $short_url = "http://t.cn/";
            
            //生成6位短网址
            for ($j = 0; $j < 6; $j++) {
                
                //将得到的值与0x0000003d,3d为61,即charset的坐标最大值
                $short_url .= self::$charset[$hex & 0x0000003d];
                
                //循环完以后将hex右移5位
                $hex = $hex >> 5;
            }

            $short_url_list[] = $short_url;
        }

        return $short_url_list;
    }
}

$url = "http://www.sunbloger.com/";
$short = ShortUrl::encode($url);
print_r($short);
?>

通常我们用四组网址中的第一组即可。

这里需要注意的是,这个算法是不可逆的,因此,通常的做法是将短网址和对应的原网址存入数据库,当访问时,从数据库中取出匹配的原网址,通过301或header进行跳转。

PHP通过反射方法调用执行类中的私有方法

PHP 5 具有完整的反射 API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。

下面我们演示一下如何通过反射,来调用执行一个类中的私有方法:

<?php

//MyClass这个类中包含了一个名为myFun的私有方法
class MyClass {
    
    private $tmp = 'hello';
    
    private function myFun()
    {
        echo $this->tmp . ' ' . 'world!';
    }
}

//通过类名MyClass进行反射
$ref_class = new ReflectionClass('MyClass');

//通过反射类进行实例化
$instance  = $ref_class->newInstance();

//通过方法名myFun获取指定方法
$method = $ref_class->getmethod('myFun');

//设置可访问性
$method->setAccessible(true);

//执行方法
$method->invoke($instance);
?>

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

在PHP中将图片转换为base64编码的方法

Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。

这里我们分享一个将图片转换为base64编码格式的方法:

<?php
$img = 'test.jpg';
$base64_img = base64EncodeImage($img);

echo '<img src="' . $base64_img . '" />';

function base64EncodeImage ($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}
?>

通过上面的方法转换后得到的base64编码字符串,可以存放到数据库中,需要时可以直接从数据库中读取,减少访问图片时的请求数量。

另:这个方法已经包含进MiniFramework的全局函数库中了。

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

采用单例模式编写PHP的PDO类

下面的代码是用此前一个名为MyPDO的类改写的,引入了单例模式来保证在全局调用中不会重复实例化这个类,降低系统资源的浪费。

代码如下:

<?php
/**
 * MyPDO
 * @author Jason.Wei <jasonwei06@hotmail.com>
 * @license http://www.sunbloger.com/
 * @version 5.0 utf8
 */
class MyPDO
{
    protected static $_instance = null;
    protected $dbName = '';
    protected $dsn;
    protected $dbh;
    
    /**
     * 构造
     * 
     * @return MyPDO
     */
    private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        try {
            $this->dsn = 'mysql:host='.$dbHost.';dbname='.$dbName;
            $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
            $this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');
        } catch (PDOException $e) {
            $this->outputError($e->getMessage());
        }
    }
    
    /**
     * 防止克隆
     * 
     */
    private function __clone() {}
    
    /**
     * Singleton instance
     * 
     * @return Object
     */
    public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        if (self::$_instance === null) {
            self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
        }
        return self::$_instance;
    }
    
    /**
     * Query 查询
     *
     * @param String $strSql SQL语句
     * @param String $queryMode 查询方式(All or Row)
     * @param Boolean $debug
     * @return Array
     */
    public function query($strSql, $queryMode = 'All', $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $recordset = $this->dbh->query($strSql);
        $this->getPDOError();
        if ($recordset) {
            $recordset->setFetchMode(PDO::FETCH_ASSOC);
            if ($queryMode == 'All') {
                $result = $recordset->fetchAll();
            } elseif ($queryMode == 'Row') {
                $result = $recordset->fetch();
            }
        } else {
            $result = null;
        }
        return $result;
    }
    
    /**
     * Update 更新
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param String $where 条件
     * @param Boolean $debug
     * @return Int
     */
    public function update($table, $arrayDataValue, $where = '', $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        if ($where) {
            $strSql = '';
            foreach ($arrayDataValue as $key => $value) {
                $strSql .= ", `$key`='$value'";
            }
            $strSql = substr($strSql, 1);
            $strSql = "UPDATE `$table` SET $strSql WHERE $where";
        } else {
            $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        }
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Insert 插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param Boolean $debug
     * @return Int
     */
    public function insert($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Replace 覆盖方式插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param Boolean $debug
     * @return Int
     */
    public function replace($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Delete 删除
     *
     * @param String $table 表名
     * @param String $where 条件
     * @param Boolean $debug
     * @return Int
     */
    public function delete($table, $where = '', $debug = false)
    {
        if ($where == '') {
            $this->outputError("'WHERE' is Null");
        } else {
            $strSql = "DELETE FROM `$table` WHERE $where";
            if ($debug === true) $this->debug($strSql);
            $result = $this->dbh->exec($strSql);
            $this->getPDOError();
            return $result;
        }
    }
    
    /**
     * execSql 执行SQL语句
     *
     * @param String $strSql
     * @param Boolean $debug
     * @return Int
     */
    public function execSql($strSql, $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * 获取字段最大值
     * 
     * @param string $table 表名
     * @param string $field_name 字段名
     * @param string $where 条件
     */
    public function getMaxValue($table, $field_name, $where = '', $debug = false)
    {
        $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
        if ($where != '') $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, 'Row');
        $maxValue = $arrTemp["MAX_VALUE"];
        if ($maxValue == "" || $maxValue == null) {
            $maxValue = 0;
        }
        return $maxValue;
    }
    
    /**
     * 获取指定列的数量
     * 
     * @param string $table
     * @param string $field_name
     * @param string $where
     * @param bool $debug
     * @return int
     */
    public function getCount($table, $field_name, $where = '', $debug = false)
    {
        $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
        if ($where != '') $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, 'Row');
        return $arrTemp['NUM'];
    }
    
    /**
     * 获取表引擎
     * 
     * @param String $dbName 库名
     * @param String $tableName 表名
     * @param Boolean $debug
     * @return String
     */
    public function getTableEngine($dbName, $tableName)
    {
        $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='".$tableName."'";
        $arrayTableInfo = $this->query($strSql);
        $this->getPDOError();
        return $arrayTableInfo[0]['Engine'];
    }
    
    /**
     * beginTransaction 事务开始
     */
    private function beginTransaction()
    {
        $this->dbh->beginTransaction();
    }
    
    /**
     * commit 事务提交
     */
    private function commit()
    {
        $this->dbh->commit();
    }
    
    /**
     * rollback 事务回滚
     */
    private function rollback()
    {
        $this->dbh->rollback();
    }
    
    /**
     * transaction 通过事务处理多条SQL语句
     * 调用前需通过getTableEngine判断表引擎是否支持事务
     *
     * @param array $arraySql
     * @return Boolean
     */
    public function execTransaction($arraySql)
    {
        $retval = 1;
        $this->beginTransaction();
        foreach ($arraySql as $strSql) {
            if ($this->execSql($strSql) == 0) $retval = 0;
        }
        if ($retval == 0) {
            $this->rollback();
            return false;
        } else {
            $this->commit();
            return true;
        }
    }

    /**
     * checkFields 检查指定字段是否在指定数据表中存在
     *
     * @param String $table
     * @param array $arrayField
     */
    private function checkFields($table, $arrayFields)
    {
        $fields = $this->getFields($table);
        foreach ($arrayFields as $key => $value) {
            if (!in_array($key, $fields)) {
                $this->outputError("Unknown column `$key` in field list.");
            }
        }
    }
    
    /**
     * getFields 获取指定数据表中的全部字段名
     *
     * @param String $table 表名
     * @return array
     */
    private function getFields($table)
    {
        $fields = array();
        $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
        $this->getPDOError();
        $recordset->setFetchMode(PDO::FETCH_ASSOC);
        $result = $recordset->fetchAll();
        foreach ($result as $rows) {
            $fields[] = $rows['Field'];
        }
        return $fields;
    }
    
    /**
     * getPDOError 捕获PDO错误信息
     */
    private function getPDOError()
    {
        if ($this->dbh->errorCode() != '00000') {
            $arrayError = $this->dbh->errorInfo();
            $this->outputError($arrayError[2]);
        }
    }
    
    /**
     * debug
     * 
     * @param mixed $debuginfo
     */
    private function debug($debuginfo)
    {
        var_dump($debuginfo);
        exit();
    }
    
    /**
     * 输出错误信息
     * 
     * @param String $strErrMsg
     */
    private function outputError($strErrMsg)
    {
        throw new Exception('MySQL Error: '.$strErrMsg);
    }
    
    /**
     * destruct 关闭数据库连接
     */
    public function destruct()
    {
        $this->dbh = null;
    }
}
?>

 

调用方法:

<?php
require 'MyPDO.class.php';
$db = MyPDO::getInstance('localhost', 'root', '123456', 'test', 'utf8');

//do something...

$db->destruct();
?>

阳光部落原创,更多内容请访问 http://www.sunbloger.com/

苹果APNS推送效率研究总结

年底这段时间一直在研究苹果的APNS(英文全称:Apple Push Notification Service)服务,进行了很多尝试,积累了一些经验。写出来总结一下,有不对的地方欢迎指正。

关于推送效率,苹果官方给出的建议是当建立一个Socket通道后,尽可能将需要推送消息和接受的devicetoken连续发送至APNS服务器端。

但是,这里需要注意如果消息队列中存在不正确的devicetoken时,苹果会在接受到这个devicetoken时,强制中断当前的Socket通道,这样会造成后面的消息无法正常发送给APNS服务器。

怎么办?

可能会有人建议每推送一条消息就断开Socket通道重新连接一次,来保证推送成功率。这样做成功率的确可以保证,但效率实在太低。

那怎么办?

很简单,我的做法是在一个消息队列中,每发送一条消息,就去read当前的Socket通道,苹果会在遇到错误的devicetoken后进行标记,我们可以read到这个数据,从而将错误的devicetoken从队列中剔除,并尝试重新建立一个Socket通道,然后从错误的devicetoken后面继续推送。

这样,我们就可以放心大胆的去连续推送一个消息队列,而不用担心由于错误的devicetoken造成推送半途中断。

还有什么办法可以提升推送效率?

最简单的办法就是多线程或多进程处理消息队列,我们团队的做法是多进程,通过HASH将一个消息队列平均分布到多个服务器端的进程上,从而进一步加快推送的速度。

采用多进程还有一个考虑,那就是担心若采用多线程万一遇到某些未知的异常,结果很可能是全军覆没,所有线程一起挂掉。而多进程的状态下,一个进程出现问题,其他的进程还可以继续工作,尽可能将影响降至最低。

速度还能再快吗?

没问题,速度还想进一步提升,就要从网络带宽和服务器方面下功夫了。用n台服务器组成一个消息推送阵列,通过某种策略来分担一定量级的推送任务,每台服务器中再通过前面提到的多进程方式运作,相信效率能够提升的非常明显。

关于feedback

APNS的feedback是一个非常贴心的服务,他会告诉你近期推送的消息,有哪些设备由于卸载了应用而无法在通知中显示消息。

那么,我们通过定期从feedback中获得这些devicetoken后,在数据库中进行标记,在下次的推送中,从消息队列中剔除这些devicetoken,这样减少了无用功,推送一次会完成的更快。

其他建议

本着不重复发明轮子的思想,推荐一下ApnsPHP这个开源项目,这里就不放链接了,github上搜吧:)

阳光部落原创,更多内容请访问http://www.sunbloger.com/

再次深入研究苹果消息推送服务(APNS) 完善PHP版服务器端公共类

前段时间开发的一套APNS推送平台效率很差,通过再次深入研究苹果的消息推送服务,总结了不少经验。同时也参考了网上一些技术blog的博文,重新完善了此前写过的一个PHP类,代码如下:

<?php
/**
 * ApplePush 苹果消息推送公共类
 * @author www.sunbloger.com
 */
class ApplePush
{
    
    const STATUS_CODE_INTERNAL_ERROR = 999;
    const ERROR_RESPONSE_SIZE = 6;
    const ERROR_RESPONSE_COMMAND = 8;
    
    protected $_errorResponseMessages = array(
        0 => 'No errors encountered',
        1 => 'Processing error',
        2 => 'Missing device token',
        3 => 'Missing topic',
        4 => 'Missing payload',
        5 => 'Invalid token size',
        6 => 'Invalid topic size',
        7 => 'Invalid payload size',
        8 => 'Invalid token',
        self::STATUS_CODE_INTERNAL_ERROR => 'Internal error'
    );
    
    /**
     * APNS server url
     * 
     * @var string
     */
    protected $apns_url = 'ssl://gateway.push.apple.com:2195'; //沙盒地址:ssl://gateway.sandbox.push.apple.com:2195
    
    /**
     * 推送数据
     * 
     * @var string
     */
    private $payload_json;
    
    /**
     * 数据流对象
     * 
     * @var mixed
     */
    private $fp;
    
    /**
     * 设置APNS地址
     * 
     * @param string $url
     */
     
    public function setApnsUrl($url)
    {
        if (empty($url)) {
            return false;
        } else {
            $this->apns_url = $url;
        }
        return true;
    }
    
    /**
     * 设置推送的消息
     * 
     * @param string $body
     */
    public function setBody($body)
    {
        if (empty($body)) {
            return false;
        } else {
            $this->payload_json = json_encode($body);
        }
        return true;
    }
    
    /**
     * Open 打开APNS服务器连接
     * 
     * @param string $pem 证书
     * @param string $passphrase 证书密钥
     */
    public function open($pem, $passphrase)
    {
        if (empty($pem)) {
            return false;
        }
        if (empty($passphrase)) {
            return false;
        }
        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', $pem);
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
        $fp = stream_socket_client($this->apns_url, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        if (!$fp) {
            return false;
        }
        $this->fp = $fp;
        return true;
    }
    
    /**
     * Send 推送
     * 
     * @param string $token
     */
    public function send($token, $id)
    {
        $msg = pack('CNNnH*', 1, $id, 864000, 32, $token) . pack('n', strlen($this->payload_json)) . $this->payload_json;
        // Send it to the server
        $result = fwrite($this->fp, $msg, strlen($msg));
        return $result;
    }
    
    public function readErrMsg()
    {
        $errInfo = @fread($this->fp, self::ERROR_RESPONSE_SIZE);
        if ($errInfo === false || strlen($errInfo) != self::ERROR_RESPONSE_SIZE) {
            return true;
        }
        $errInfo = $this->parseErrMsg($errInfo);
        if (!is_array($errInfo) || empty($errInfo)) {
            return true;
        }
        if (!isset($errInfo['command'], $errInfo['statusCode'], $errInfo['identifier'])) {
            return true;
        }
        if ($errInfo['command'] != self::ERROR_RESPONSE_COMMAND) {
            return true;
        }
        $errInfo['timeline'] = time();
        $errInfo['statusMessage'] = 'None (unknown)';
        $errInfo['errorIdentifier'] = $errInfo['identifier'];
        if (isset($this->_aErrorResponseMessages[$errInfo['statusCode']])) {
            $errInfo['statusMessage'] = $this->_errorResponseMessages[$errInfo['statusCode']];
        }
        return $errInfo;
    }

    protected function parseErrMsg($errorMessage)
    {
        return unpack('Ccommand/CstatusCode/Nidentifier', $errorMessage);
    }
    
    /**
     * Close APNS server 关闭APNS服务器连接
     * 
     */
    public function close()
    {
        // Close the connection to the server
        fclose($this->fp);
        return true;
    }
}
?>

阳光部落原创,更多内容请访问http://www.sunbloger.com/

用Python提取网页中的超链接

最近正在学习Python,打算用作爬虫开发。既然要做爬虫,首先就要抓取网页,并且从网页中提取出超链接地址。

下面是最简单的实现方法,先将目标网页抓回来,然后通过正则匹配a标签中的href属性来获得超链接,代码如下:

import urllib2
import re

url = 'http://www.sunbloger.com/'

req = urllib2.Request(url)
con = urllib2.urlopen(req)
doc = con.read()
con.close()

links = re.findall(r'href\=\"(http\:\/\/[a-zA-Z0-9\.\/]+)\"', doc)
for a in links:
    print a

阳光部落原创,更多内容请访问http://www.sunbloger.com/

PHPCMS V9无法正常通过QQ登录的解决方案

这个故障的原因是PHPCMS V9的QQ登录功能代码中,使用了file_get_contents函数来获取腾讯的https网址,这类网址是通过ssl加密传输的。虽然,我们可以通过为PHP安装openssl扩展,让file_get_contents函数可以获取到内容,但获取到的内容还是加密的,无法正常的解密。

我的解决思路是自己编写一个通过curl读取数据的方法,替换掉PHPCMS原有的方法,具体如下:

阅读更多