[笔记] php常见简单功能及函数

获取远程文件(图片等)

有三种方式

  1. file_get_contents($url);
    使用file_get_contents()函数获取文件,在用file_put_contents()函数把文件写到本地。

  2. 使用curl

//获取到文件
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,60);
$file=curl_exec($ch);
curl_close($ch);
//写入本地
$fp=fopen($save_dir.$filename,'a');
fwrite($fp,$file);
fclose($fp);

3 . 使用ob_start()

//获取文件
ob_start();    //打开缓冲区
readfile($url);
$file=ob_get_contents();
ob_end_clean();
//写入本地
$fp=fopen($save_dir.$filename,'a');
fwrite($fp,$file);
fclose($fp);

多个进程写入同一个文件(加锁)
$fp = fopen("lock.txt","w+");
if(flock($fp,LOCK_EX)){
    //获得写锁,写数据
    fwrite($fp,"write something");
    //解除锁定
    flock($fp,LOCK_UN);
}else{
    echo "file is locking";
}
fclose($fp);

跳转的方法
header('Location:http://www.baidu.com');        //立刻跳转
header('refresh:3;url=http://www.baidu.com');    //三秒后跳转
//php函数跳转缺点:执行前不能有输出

//meta跳转
echo "<meta http-equiv='refresh' content='5;url=http://www.baidu.com' >";
创建多级目录
function create_dir($path,$mode=0777){
    if(is_dir($path)){
        return true;
    }else{
        if(mkdir($path,$mode,true)){
            return true;
        }else{
            return false;
        }
    }
}

无限极分类
function getCat($data,$pid=0,$level=0){
    static $res;
    foreach($data as $k=>$v){
        if($v['pid']=$pid){
            $v['level'] = $level;
            $res[] = $v;
            getCat($data,$v['id'],$level+1);
        }
    }
    return $res;
}

取出url中的扩展名
function getExt($url){
    $arr = parse_url($url);  //解析url,返回数组
    $file = basename($arr['path']);  //取文件名部分
    $ext = explode('.',$file);
    return $ext[count($ext)-1];
}
function getExt($url){
    $url = basename($url);
    $pos1 = strpos($url,'.');
    $pos2 = strpos($url,'?');
    if(strstr($url,'?')){
        return substr($url,$pos1+1,$pos2-$pos1-1);
    }else{
        return substr($url,$pos1+1);
    }
}

读取文件夹下的所有子目录和子文件夹
function my_scandir($dir){
    $files = array();
    if(is_dir($dir)){
        if($handle = opendir($dir)){
            while(($file = readdir($handle)) != false){
                if($file!='.' && $file!='..' ){
                    if(is_dir($dir.'/'.$file)){
                        $files[$file] = my_scandir($dir.'/'.$file);
                    }else{
                        $files[] = $dir.'/'.$file;
                    }
                }
            }
            closedir($handle);
            return $files;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

待续……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值