本文汇总了php文件上传代码,包括最简单的PHP文件上传代码、上传文件后自动重命名、根据日期分目录上传文件代码、一次上传多个文件、限制上传文件大小等。
最简单的PHP文件上传代码
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
<?php if (($_FILES["file"]["size"] < 20000) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?>
php上传文件后自动重命名
if (file_exists("./upload/" . $_FILES["file"]["name"])) { do{ $suffix =""; $suffix_length = 4; $str = "0123456789abcdefghijklmnopqrstuvwxyz"; $len = strlen($str)-1; //文件名后追加4个随机字符 for($i=0 ; $i<$suffix_length; $i++){ $suffix .= $str[rand(0,$len)]; } $upload_filename = $_FILES['file']['name']; $filename = substr($upload_filename,0,strrpos($upload_filename,".")).$suffix.".".substr($upload_filename,strrpos($_FILES["file"]["name"],".")+1); }while(file_exists("./upload/".$filename)); move_uploaded_file($_FILES["file"]["tmp_name"],"./upload/" . $filename); }else{ move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); }
PHP根据日期分目录上传文件代码
$structure = './'.date("Y").'/'.date("m").'/'.date("d").'/'; if (!mkdir($structure, 0777, true)) { die('Failed to create folders...'); } move_uploaded_file($_FILES["file"]["tmp_name"],$structure . $_FILES["file"]["name"]);
PHP一次上传多个文件
<form action="" method="post" enctype="multipart/form-data"> <p>Pictures: <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="submit" value="Send" /> </p> </form>
<?php foreach ($_FILES["pictures"]["error"] as $key => $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; $name = $_FILES["pictures"]["name"][$key]; move_uploaded_file($tmp_name, "data/$name"); } } ?>
限制上传文件大小
<input type="hidden" name="MAX_FILE_SIZE" value="字节" />
可以限制上传文件大小(可以被绕过)。
然后在服务器上调整一下配置php.ini:
max_execution_time = 30 每个脚本运行的最长时间,单位秒 max_input_time = 60,每个脚本可以消耗的时间,单位也是秒 memory_limit = 128M,这个是脚本运行最大消耗的内存 post_max_size = 8M,表单提交最大数据为 8M,此项不是限制上传单个文件的大小,而是针对整个表单的提交数据进行限制的。 upload_max_filesize = 2M ,上载文件的最大许可大小
nginx:
location / { root html; index index.html index.htm; client_max_body_size 1000m; }
声明:如需转载,请注明来源于www.webym.net并保留原文链接:http://www.webym.net/jiaocheng/905.html