Home >Backend Development >PHP Tutorial >How to upload files to a specified location in php (code attached)

How to upload files to a specified location in php (code attached)

不言
不言Original
2018-09-01 09:55:368548browse

The content of this article is about how to upload files to the specified location in PHP (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

test.php (front-end code)

<!DOCTYPE html>
<html>
<head>
	<title>文件上传测试</title>
	<meta charset="utf-8">
</head>
<body>
<form action="do.php" method="post" enctype="multipart/form-data">
	<input type="file" name="img">
	<input type="submit" value="上传文件">
</form>
</body>
</html>

Explanation:

  • methodmust# under the from tag ##For post

  • To add enctype="multipart/from-data"

do. php (from form processing file)

<?php
print_r($_FILES);
 ?>

Explanation:

print_r() Output the data passed by the form into an array

The output is:

Array ( 
    [img] => Array (
         [name] => 1.jpg 
         [type] => image/jpeg
         [tmp_name] => C:\Windows\Temp\phpFF07.tmp
         [error] => 0
         [size] => 17164 
    ) 
)

  • name: The name of the uploaded file

  • type: The MIME type of the uploaded file

  • tmp_name: The name of the temporary file uploaded to the server (or local)

  • size: The size of the uploaded file

  • error: Error number for uploading files

do.php (Successfully uploaded files to the specified folder)

Method 1:

<?php
print_r($_FILES);

$filename=$_FILES[&#39;img&#39;][&#39;name&#39;];
$type=$_FILES[&#39;img&#39;][&#39;type&#39;];
$tmp_name=$_FILES[&#39;img&#39;][&#39;tmp_name&#39;];
$size=$_FILES[&#39;img&#39;][&#39;size&#39;];
$error=$_FILES[&#39;img&#39;][&#39;error&#39;];

//将服务器上的临时文件移动到指定目录下
move_uploaded_file($tmp_name, "img/".$filename);

$_FILES is the file upload variable, which stores the file upload data

move_uploaded_file($tmp_name,"specified folder name".$filename);

Move the temporary files on the server to the specified directory, return true if successful, false if failed

Method 2:

copy($tmp_name, "img/".$filename);

Related recommendations:

How to correctly formulate PHP Upload large file settings

# Implement php to upload pictures to the specified location and save the path to the database

The above is the detailed content of How to upload files to a specified location in php (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn