//获取网上的一个文件
function getUrlImage($url, $file = '', $maxExe = 0, $safe = false){
$urlExt = explode('.', $url);
$fileExt = array('txt','jpg','gif','png');
if(!in_array(end($urlExt), $fileExt, true)) return false;
$file = ($file)? $file.$urlExt : basename($url);
$file = rand(1,1000).$file;
ob_start(); //开启输出缓冲
set_time_limit($maxExe); //开启最大运行时间
readfile($url);//读入一个文件并写入到输出缓冲
$data = ob_get_contents();
ob_end_clean();
file_put_contents($file,$data);
if($safe && is_executable($file)){//为安全起见,判定一下文件是否可执行
unlink($file);
return false;
}
return $file;
}

getUrlImage('http://www.test.com/3675.jpg','newName');

//批量生成cookie
function mySetCookie($data, $name){
if(empty($data) || empty($name))return;
$args = func_get_args();
$time = empty($args[2])? time() + 3600 : time() + $args[2];
$path = empty($args[3])? '' : $args[3];
$domain = empty($args[4])? '' : $args[4];
$secure = empty($args[5])? '' : $args[5];
if(is_array($data)){
foreach($data as $key => $val){
$full = "{$name}[$key]";
setcookie($full, $val, $time, $path, $domain, $secure);
}
}else{
setcookie($name, $data, $time, $path, $domain, $secure);
}

}

$data = array('name' => '李四', 'age' => 15);
mySetCookie($data,'userInfo');
print_r($_COOKIE);

//冒泡排序
function arrSort(&$arr, $asc = ''){
$times = count($arr) - 1;
for($i = 0; $i < $times; $i++){
for($j = 0; $j < $times - $i; $j++){
if($arr[$j] > $arr[$j + 1]){
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
}
}
}
if('' != $asc) $arr = array_reverse($arr, false);//反转数组元素
}

//选择排序
function seleSort(&$arr){
$times = count($arr) - 1;
$jMax = count($arr);
for($i = 0; $i < $times; $i++){
$min = $arr[$i];
$minId = $i;
for($j = $i + 1; $j < $jMax; $j++){
if($min > $arr[$j]){
$min = $arr[$j];
$minId = $j;
}
}
$temp = $arr[$i];
$arr[$i] = $arr[$minId];
$arr[$minId] = $temp;
}
}

//插入排序
function inserSort(&$arr){
$times = count($arr);
for($i = 1; $i < $times; $i++){
$insert = $arr[$i];
$insertId = $i - 1;
while($insertId >= 0 && $insert < $arr[$insertId]){
$arr[$insertId + 1] = $arr[$insertId];
$insertId--;
}
$arr[$insertId + 1] = $insert;
}
}

//计算两个文件的相对路径。
function relative_dir($fileA, $fileB){//A相当于B,所在目录
$aPath = explode('/',dirname($fileA));
$bPath = explode('/',dirname($fileB));
$bLen = count($bPath);
$j = 1;
for($i = 1; $i < $bLen; $i++){
if(isset($bPath) && isset($aPath)){
if($aPath[$i] == $bPath[$i]){$j++;}//累计相同路径部分
if($aPath[$i] != $bPath[$i]){$path .= '../';}//不同的,则增加退回上级
}
}
$path .= implode('/',array_slice($aPath, $j)).'/'.basename($fileA);
return $path;
}

$a = 'a/b/c/test/5/8/aaa.php';
$b = 'a/b/c/check/1/2/3/4/bbb.php';
echo relative_dir($a,$b);

//以附件方式实现文件下载:
$file = 'e:/个人简历.doc';
$file = iconv('utf-8', 'gb2312',$file);
if(file_exists($file)){
$fname = basename($file);
$fsize = filesize($file);
header("Content-type:application/octet-stream");//二进制数据
header("Content-Disposition:attachment;filename={$fname}");//附件形式
header("Accept-ranges:bytes");
header("Accept-length:".$fsize);
readfile($file);
}else{
exit('flie not found!');
}

遍历一个目录,及其子目录:
function recurDir($pathName){
$result = array();
$temp = array();
if(!is_dir($pathName) || !is_readable($pathName)) return null;
$allFiles = scandir($pathName);
foreach($allFiles as $fileName){
if(in_array($fileName, array('.','..')))continue;
$fullName = $pathName . '/' . $fileName;
if(is_dir($fullName)){
$result[$fileName] = recurdir($fullName);
}else{
$temp[] = $fileName;
}
}
foreach($temp as $f){
$result[] = $f;
}
return $result;
}
$pathName = 'D:\AppServ\www\zbseoag\\';
print_r(recurDir($pathName));

//从URL中获取文件扩展名:
function getExt($url){
$arr = parse_url($url);//把URL解析成数组
$file = basename($arr['path']);
$ext = explode('.',$file);
return end($ext);
}

//PHP验证email格式
function checkEmail($email){
$pattern = "/([a-z0-9]*[-_/.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[/.][a-z]{2,3}([/.][a-z]{2})?/i";
return preg_match($pattern,$email);
}

//文件上传
<script>
function addUpload(){
document.getElementById("upfiles").innerHTML += '<li>文件:<input type="file" name="files[]" /></li>';
}
function resetUpload(){
document.getElementById("upfiles").innerHTML = '<li>文件:<input type="file" name="files[]" /></li>';
}
</script>
<form action="" method="post" enctype="multipart/form-data" >
<ul id="upfiles">
<li>文件:<input type="file" name="files[]" /></li>
</ul>
<input type="submit" value="提交" />
<input type="button" value="增加上传框" onClick="addUpload()" />
<input type="button" value="重设上传框" onClick="resetUpload()" />
</form>

$files = 'files';//files是$_FILES中的一个元素数组,并所上传文件信息进行了归类
$upDir = './upImg/';
$fTypes = 'jpg|gif|txt|chm';

function upFilse($files, $upDir, $fTypes){
if(isset($_FILES[$files]['name'])){
if(!is_dir($upDir)) mkdir($upDir, 0777, true) or exit('上传目录创建失败!');
$ftypeArr = explode('|',$fTypes);
foreach($_FILES[$files]['name'] as $i => $value){
$fType = strtolower(end(explode(".",$_FILES[$files]['name'][$i])));
if(in_array($fType, $ftypeArr)){
$path = $upDir.time().$_FILES[$files]['name'][$i];//指定目录,且包含有文件名
move_uploaded_file($_FILES[$files]['tmp_name'][$i], $path);//移到指定目录
if($_FILES[$files]['error'][$i] == 0){
$file[$_FILES[$files]['name'][$i]] = $path;
list($name, $path) = each($file);//each(数组)返回当前由键名与键值所构成的数组;list(变量1, 变量n 【或数组】) = 数字索引的数组,将值赋给变量。
$sql = "INSERT INTO `database`.`table`(name, path) VALUES ('$name', '$path')";
$msg[] = $value.'文件上传成功';
}else
$msg[] = $value.'文件上传失败!';
}else
$msg[] = $value.'文件格式不正确!';
}
return $msg;
}
}
print_r(upFilse($files, $upDir, $fTypes));

//求今天是星期几:
$time = getdate();//获取当前时间戳中的时间信息
$weekday = array('星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
$wday = $time['wday'];//当前是一个星期中的第几天
echo date("今天是:Y年m月d日H:i:s $weekday[$wday]");

//求下周一是几月几日:
$time = time();//当前时间戳
$weekday = date('w');//当天的数字星期
switch($weekday){
case 0: $nextMonday = $time+86400;break;//星期天则加一天
case 1: $nextMonday = $time+7*86400;break;//星期一,则加七天
case 2: $nextMonday = $time+6*86400;break;
case 3: $nextMonday = $time+5*86400;break;
case 4: $nextMonday = $time+4*86400;break;
case 5: $nextMonday = $time+3*86400;break;
case 6: $nextMonday = $time+2*86400;break;
}
echo date('Y-m-d',$nextMonday);

//逐行读取文件指定行数的内容:
function getRowData($file, $row = 0, mark = false){
$fhandle = fopen($file,'rb');
$row = ($row == 0)? filesize($file) : $row;
while($row >0 && !feof($fhandle)){
$data[] = (mark)? fgets($fhandle) : fgetss($fhandle);
$row--;
}
fclose($fhandle);
}

//读取文件指定字符长度
function getLetterData($file, $num = 0, mark = false){
$fhandle = fopen($file,'rb');
$row = ($num)? filesize($file) : $num;
$data = fread($fhandle, $num);
fclose($fhandle);
}
//删除目录中在数据库中没有记录的图片
public function delImg($data, $dir = '.'){
$files = scandir($dir);
$delFiles = array_diff($allFiles,$data);
foreach($delFiles as $name){
$file = rtrim($dir,'/').'/'.$name;
unlink($file);
echo $file.'<br/>';
}
}

PHP 小代码的更多相关文章

  1. 【processing】小代码

    今天无意间发现的processing 很有兴趣 实现很简洁 void setup(){ } void draw(){ background(); && mouseY > heig ...

  2. 小代码编写神器:LINQPad 使用入门

    原文:小代码编写神器:LINQPad 使用入门 一:概述 1:想查看程序运行结果,又不想启动 VS 怎么办? 2:想测试下自己的 C# 能力,不使用 VS 的智能感知,怎么办? 那么,我们有一个选择, ...

  3. Python小代码_2_格式化输出

    Python小代码_2_格式化输出 name = input("name:") age = input("age:") job = input("jo ...

  4. Python小代码_1_九九乘法表

    Python小代码_1_九九乘法表 max_num = 9 row = 1 while row <= max_num: col = 1 while col <= row: print(st ...

  5. 简单的Java逻辑小代码(打擂台,冒泡排序,水仙花数,回文数,递归)

    1.打擂台 简单的小代码,打擂台.纪念下过去,祝福下新人. public static void main(String[] args){ int[] ld = {1,4,2,10,8,9,5}; i ...

  6. python的mysql小代码

    我因为懒,就想写个批量insert数据的小代码 这里是代码 # _*_ encoding:utf-8 _*_ import os import MySQLdb import numpy as np d ...

  7. 一段小代码秒懂C++右值引用和RVO(返回值优化)的误区

    关于C++右值引用的参考文档里面有明确提到,右值引用可以延长临时变量的周期.如: std::string&& r3 = s1 + s1; // okay: rvalue referen ...

  8. 【processing】小代码4

    translate(x,y);  移动坐标原点到x,y处 rotate(angle); 坐标沿原点顺时针转动angle度 scale(n); 绘制图像放大n倍 pushMatrix() 将当前坐标压入 ...

  9. Android版微信小代码(转)

    以下代码仅适用于Android版微信: //switchtabpos:让微信tab更贴合Android Design 如果你并不喜欢微信Android版和iOS端同用一套UI,现在有一个小方法可以实现 ...

  10. printf 小代码 大问题

    技术 对于我来说 是我前进的动力 虽然有时候感觉会枯燥乏味 不过没关系 放松一下紧张的心态 做一些你能够是你进步的事情  这样 你才会觉得  每天都过得很充实  学海无涯  坚持追求你所想要实现的梦想 ...

随机推荐

  1. hibernate - 何时关闭数据库

    ref: http://www.coderanch.com/t/637103/ORM/databases/close-database-connection-hibernate 我上这个问题, 原因是 ...

  2. SQL学习:查询的用法(1)

    在SQL servre的使用中,查询的用法是最多的.最重要的,也是最难学习的,因此掌握查询的用法很重要. 先将表的示例上图 员工表: 部门表:                             ...

  3. 在mipsel-linux平台上的编译应用SQLite-3.5.9

    sqlite 第一个Alpha版本诞生于2000年5月,是实现了SQL 92标准的一个大子集的嵌入式数据库,其以在一个库中组合了数据库引擎和接口,能将所有数据存储于单个文件中.官方测试表明sqlite ...

  4. 【基础】Oracle 表空间和数据文件

    多个表空间的优势:1.能够将数据字典与用户数据分离出来,避免由于字典对象和用户对象保存在同一个数据文件中而产生的I/O冲突2.能够将回退数据与用户数据分离出来,避免由于硬盘损坏而导致永久性的数据丢失3 ...

  5. troubleshooting ORA-600[6302] & ORA-600 [6200] corrupted index block

    今天同事的一套数据库遇到了alert 日志 一堆的ora-600,这是一套10.2.0.5 db 2nodes RAC on AIX , 找我帮着看看, 最终确认为一个索引出现了block corru ...

  6. oracle 消除块竞争(hot blocks)

    上篇日志提到了,那么高的负载,是存在数据块读竞争,下面介绍几个方法来消除块竟争 查找块竟争 SELECT p1 "file#", p2 "block#", p3 ...

  7. iOS8上本地通知接收不到的问题

    需要手动加上这句话  if ([UIApplicationinstancesRespondToSelector:@selector(registerUserNotificationSettings:) ...

  8. C语言的指针

    指针是C语言中非常重要的数据类型,那么什么是指针呢? 指针类型就是用来用来存放变量地址的变量,指向某个变量. 指针的一般形式:*指针变量名 int *p; float *p1; “*”是用来说明这个变 ...

  9. 简单学c——前言

      1.学C语言需要什么基础吗? 零基础. 2.什么是C语言? C语言是一种编程语言. 3.什么是编程语言? 编程语言是用来定义计算机程序的形式语言,是一种被标准化的交流技巧,用来向计算机发出指令. ...

  10. Noah的学习笔记之Python篇:装饰器

    Noah的学习笔记之Python篇: 1.装饰器 2.函数“可变长参数” 3.命令行解析 注:本文全原创,作者:Noah Zhang  (http://www.cnblogs.com/noahzn/) ...