简易版php文件上传_超详细详解

 

1.php简化版的图片上传(没有各类验证)

1
2
3
4
<form action = "" enctype = "multipart/form-data" method = "post"  >
        请选择须要上传的文件: <input type = "file" name = "upfile"  /><br >
         <input type = "submit" value = "上传"  />
</form >

首先咱们须要在form表单中加入 enctype=”multipart/form-data”表示声明表单中会有图片发送, action=”” 表示当前页面提交,method=”post”传输方式为postphp

1
2
3
4
5
6
7
8
9
10
11
12
<?php
if ( is_uploaded_file ( $_FILES [ 'upfile' ] [ 'tmp_name' ] ) ) {
$upfile = $_FILES [ "upfile" ] ;
$name = $upfile [ 'name' ] ;
$tmp_name = $upfile [ "tmp_name" ] ; //上传文件的临时存放路径
move_uploaded_file ( $tmp_name , 'up/' . $name ) ;
echo  "上传成功" ;
}
else {
     echo  "您尚未上传文件" ;
}
?>

关键词总结
is_uploaded_file 表示验证文件是不是经过 HTTP POST 上传的,条件成立才能够正常上传
$_FILES[‘upfile’][‘tmp_name’]) 表示获取到当前传输图片的本地位置
move_uploaded_file($tmp_name,’up/’.$name); ,该方法有两个参数,第一个为上传的文件的文件名,第二个为移动文件到这个位置数组

2. 文件的写入与读取
首先介绍写入:函数

1
2
3
4
         $myfile  =  fopen ( "comment/"  . time ( ) . '-' .  rand ( 0 ,  1000 )  .  ".comment" ,  "a" ) or  die ( "Unable to open file!" ) ;
         $txt  =  time ( ) . '<br />' ;
         fwrite ( $myfile ,  $txt ) ;
         fclose ( $myfile ) ;

其中fopen函数的做用为写入数据,第一个参数为写入文件具体路径,第二个表示将读取到得数据放入该文件中,其中文件名采用时间戳加上随机数构成,后缀名为comment,a表示写入方式打开,将文件指针指向文件末尾。若是文件不存在则尝试建立它,or die表示执行失败,就执行Unable to open file!(没法打开文件)。
第二句表示数据,数据能够是post传输的,也能够是get,随意
第三句fwrite表示写入文件,第一个参数为写入文件的位置,第二个为要写入的数据
第四句表示关闭该文件,表示写入完毕,本次执行完毕post

1
2
3
4
5
6
7
8
9
10
$list  =  glob ( "comment/*.comment" ) ;
rsort ( $list ) ;
for  ( $i  =  0 ;  count ( $list )  >  $i ;  $i ++ )  {
     $file_path  =  $list [ $i ] ;
     if  ( file_exists ( $file_path ) )  {
         $fp  =  fopen ( $file_path ,  "r" ) ;
         $str  =  fread ( $fp ,  filesize ( $file_path ) ) ; //指定读取大小,这里把整个文件内容读取出来
         echo  $str  =  str_replace ( "\r\n" ,  "<br />" ,  $str ) ;
     }
}

在介绍读取:

关键语句为

第一句:首先使用(glob)先找到须要读取的文件,若是有不少符合条件的文件,那么他们将会使用数组进行保存,读取的时候使用遍历数组就能够了
第二句: rsort为降序排序,主要是为了知足特定条件下的排序,例如按照发布时间
第三句:由于能够经过var_dump,print等知道glob是以数组的形式保存路径的,因此咱们使用count算出总数,而后一条条遍历,即可以获得须要读取的文件路径
第四句:$file_path获取文件路径
第五句:file_exists判断文件是否存在
第六句:fopen读取该文件,而且以只读的方式打开
第七句:fread第一个参数表示读取的东西,第二个表示读取的文件的大小,这里也就表示有多少读多少
第八句:str_replace替换函数,表示将$str中的全部的\r\n都替换成br(表示换行,换成网页中的换行)spa

相关文章
相关标签/搜索