使用图片的二进制信息,获取图片的类型

php中,如果只能获取图片的二进制内容,如何获取图片的类型呢? 当然,除非必不得以,我不会选择通过内容的部分字节来判断类型. 能使用的函数是 getimagesize

getimagesize 只接收图片地址, 没有地址只有数据, 如果有文件的写权限, 可以通过先写一个临时文件, 然后使用 getimagesize 函数获取图片类型信息.

还有一种方法, 使用 stream wrapper, 给出我的测试代码, 供大家参考:

class getimagesizeStream
{

    private static $position = 0;
    public static $blob = '';

    public static function stream_open($path, $mode, $options, &$opened_path)
    {
        self::$position = 0;

        return true;
    }

    public static function stream_read($count)
    {
        $ret = substr(self::$blob, self::$position, $count);
        self::$position += strlen($ret);
        return $ret;
    }

    public static function stream_eof()
    {
        return self::$position >= strlen(self::$blob);
    }
}

stream_wrapper_register("getimagesize", "getimagesizeStream");

getimagesizeStream::$blob = file_get_contents('./1.png'); 
// 只是模拟获取图片数据,实际上,数据可能是存在数据库里,并没有实际的文件地址

print_r(getimagesize('getimagesize://'));
Xuan Yan · 29 December 2011

php根据SplSubject及SplObserver接口实现观察者设计模式

看到Spl中有这两个Interface, 自己尝试写了一下, 只实现了接口方法. 个人感觉, 适合做消息提醒及日志记录, 或类似于hook机制的插件.

class Subject implements SplSubject
{
    private $storage = null;

    function __construct()
    {
        $this->storage = new SplObjectStorage();
    }

    public function attach(SplObserver $observer)
    {
        $this->storage->attach($observer);
    }

    public function detach(SplObserver $observer)
    {
        $this->storage->detach($observer);
    }

    public function notify()
    {
        foreach ($this->storage as $obj) {
            $obj->update($this);
        }
    }
}

class Observer implements SplObserver
{
    public function update(SplSubject $subject)
    {
        echo "The subject is updating me\n";
    }
}

$subject = new Subject();
$observer = new Observer();
$subject->attach($observer);
$subject->notify();
Xuan Yan · 6 December 2011

彻底删除git库中的文件

代码如下:

git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch path/to/your/file' HEAD
git push origin master --force
rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --prune=now
git gc --aggressive --prune=now

具体可以查看这篇文章 : http://help.github.com/remove-sensitive-data/

另外注意在多人协同工作时,防止其他人又将文件提交上来(如某些文件之前没有加入到.gitignore文件中,然后这个文件更改了),需要每个人执行上面除push外的其它代码,或者重新clone.

Xuan Yan · 4 December 2011