当前位置: 首页 > 后端技术 > PHP

【注】PHP常用简单函数和函数

时间:2023-03-29 20:58:41 PHP

获取远程文件(图片等)的三种方式使用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,$文件);fclose($fp);3.使用ob_start()//获取文件ob_start();//打开缓冲区readfile($url);$file=ob_get_contents();ob_end_clean();//写入本地$fp=fopen($save_dir.$filename,'a');fwrite($fp,$文件);fclose($fp);多个进程写入同一个文件(锁)$fp=fopen("lock.txt","w+");if(flock($fp,LOCK_EX)){//获取写锁,写入数据fwrite($fp,“写一些东西”);//解锁flock($fp,LOCK_UN);}else{echo"fileislocking";}fclose($fp);跳转方法header('位置:http://www.baidu.com');//立即跳转header('refresh:3;url=http://www.baidu.com');//三秒后跳转//PHP函数跳转缺点:执行前无输出//metajumpecho"";创建多级目录函数create_dir($path,$mode=0777){if(is_dir($path)){返回真;}else{if(mkdir($path,$mode,true)){返回真;}else{返回错误;}}}无限极分类函数getCat($data,$pid=0,$level=0){static$res;foreach($dataas$k=>$v){if($v['pid']=$pid){$v['level']=$level;$res[]=$v;getCat($data,$v['id'],$level+1);}}return$res;}取出url函数getExt($url){$arr=parse_url($url);中的扩展//解析url并返回一个数组$file=basename($arr['path']);//取文件名部分$ext=explode('.',$file);返回$ext[count($ext)-1];}functiongetExt($url){$url=basename($url);$pos1=strpos($url,'.');$pos2=strpos($url,'?');if(strstr($url,'?')){returnsubstr($url,$pos1+1,$pos2-$pos1-1);}else{returnsubstr($url,$pos1+1);}}读取文件夹下的所有子目录和子文件夹functionmy_scandir($dir){$files=array();如果(is_dir($dir)){如果($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);返回$文件;}else{返回错误;}}else{返回错误;}}等待……