Chapter 1 File Upload

1.1 Client Upload Settings

File upload has become a common feature in B/S programs. The purpose is that the client can upload the file to a specified directory on the Server through the Browser.

Common web sites that support file uploading:

All kinds of network backup

Head portrait

Web albums

Real-name authentication

Email attachments

To put it simply, Web development requires that files that users pass to the server fall under the PHP upload category. And the server side can only accept the portion, unless do not do this function. Just like 10086 customer service, as long as you call, it will accept, do not accept only busy server.

PHP file upload basics:

1) Client form setting

2) The server operates and processes the uploaded files

Form items that must be set:

<html>
    <head><title>File upload</title></head>
    <body>
        <form action="./upload.php"  method="post" enctype="multipart/form-data"><! -- Must be written -->
            <! --typle write file, name must be written, name is optional -->Select file:<input type="file" name="myfile">
            <input type="submit" value="Upload file">
        </form>
    </body>
</html>

Copy the code

Note a few characteristic attributes:

1. Upload files in POST mode rather than GET mode.

Enctype =”multipart/form-data”.

3. The input form must have a name.

1.2 Upload through PHP on the server

The receiving and processing of uploaded files is handled by PHP scripts, which require the following three aspects of information:

1) Set the instructions in the PH profile: used to fine-tune PHP’s file upload functionality.

2)_POST acquisition.

3) PHP file upload processing function: used for the subsequent processing of uploaded files.

1) Options related to file uploads in the PHP configuration file.

Instruction of The default value Functional description
file_uploads ON Whether to enable file uploading
upload_max_filesize 2M Limits the maximum size of uploaded files that PHP can process. This value must be smaller than post_max_size
post_max_size 8M Limits the maximum amount of information that can be accepted through the POST method, which is the submit value of the entire POST request. This value must be greater than upload_max_filesize
upload_tmp_dir NULL Temporary path for storing uploaded files. The value can be an absolute path. Default NULL uses the system’s temporary directory.
max_file_uploads 20 Maximum number of files that can be uploaded simultaneously

2) $_FILES multidimensional array.

Super global array $_FILES

	1, $_FILES ["myfile"] ["name"] is the name of the file in the client file system.2, $FILES ["myfile"] ["type"] is the type of file passed by the client.3, $_FILES ["myfile"] ["size"] is the size of the file in bytes.4, $_FILES ["myfile"] ["tmp_name"] is the temporary full path stored on the server after the file is uploaded.5, $_FILES ["myfile"] ["error"] is: error code for file upload -php4.2Features added later.Copy the code

Error file upload error code:

UPLOAD_ERR_OK its value is0No error occurred and the file was successfully uploaded. UPLOAD_ERR_INI_SIZE its value is1The uploaded file exceeded the limit of upload_max_filesize in php.ini. UPLOAD_ERR_FORM_SIZE its value is2The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form. UPLOAD_ERR_PARTIAL its value is3Only part of the file is uploaded. UPLOAD_ERR_NO_FILE its value is4No files have been uploaded. UPLOAD_ERR_NO_TMP_DIR its value is6Cannot find temporary folder. PHP4.310.And PHP5.03.Introduction. UPLOAD_ERR_CANT_WRITE its value is7Failed to write the file. PHP5.1. 0Introduction. Note: The above values are in PHP4.3. 0Then it becomes a PHP constant.Copy the code

Common Data Formats (MIME)

The file type The MIME type
Image files Image/GIF, image/ JPG, image/ JPEG, image/ PNG, image/x-png
Plain text and HTML Text/TXT, text/plain, text/ HTML
Binary file application/octet-stream
Audio formats audio/basic
Video format video/mpeg

3) PHP file upload processing function

The uploaded file is stored in a temporary directory on the server. The file name is randomly generated.

Note: this file will be deleted automatically after the execution of the program. You can operate as a local file before deleting it.

File upload processing function:

Is_uploaded_file – Determines whether the file was uploaded via HTTP POST.

Bool is_uploaded_file (string $filename)

Move_uploaded_file – Moves the uploaded file to a new location.

Format: bool MOVE_UPLOaded_file (string)destination )

Note: If the target file already exists, it will be overwritten.

Parameter Description: Temporary directory for files to be moved to

Case study:

1) Set the front-end upload interface


      
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<form action="doup.php" method="post" enctype="multipart/form-data">
		<input type="file" name="pic">
		<input type="submit" value="Upload">
	</form>
</body>
</html>
Copy the code

2) Doup.php processes files uploaded to temporary directories

	// Professional handling tools
	//move_uploaded_file()
	// Parameter 1: temporary directory for files Parameter 2: location to move to

	//is_uploaded_file() checks whether the file was submitted by HTTP post
	// Parameter 1: temporary directory for files
	


	//1. The path we save is created by time
	//var_dump($_GET);

	//1.1 Save path
	$dir='./biran/'.date('Y/m/d/');
	//echo $dir; exit;

	1.2 Check whether the file upload path exists. If not, create a file
	if(! file_exists($dir)){ mkdir($dir,777.true);
	}

	//2. Have a good filename unique filename
	//2.1 Obtain file name extensions
	//2.jpg jpg
	$suffix = pathinfo($_FILES['pic'] ['name'],PATHINFO_EXTENSION);
	//echo $suffix;

	//2.2 Rename
	$filename = date('Ymd').uniqid().mt_rand(0.9999).'. '.$suffix;
	//echo $filename;

	// Start moving
	// Check whether the file is HTTP post
	if(! is_uploaded_file($_FILES['pic'] ['tmp_name'])){
		// Not HTTP post upload file
		echo 'Don't be useless!! ';exit;
	}

	// Start the real move
	if(move_uploaded_file($_FILES['pic'] ['tmp_name'],$dir.$filename)){
		echo '11111111111';
	}else{
		echo '22222222222';
	}
Copy the code

Encapsulate as a function:

Ideas:

	function upload(a){
		//1. Check whether the file is uploaded incorrectly

		//2. Determine if the type of file you upload is what you want
		
		/ / 3. The name
		
		//4. Check whether the save path exists
		
		//5. Check whether the file is uploaded through HTTP POST
		
		//6
		
		//7. Return the name of the image that was moved successfully
	}
Copy the code

To begin wrapping functions: create new function.php


      
	/* File upload function@paramString $name Indicates the name value of the uploaded file domain@paramString $dir File saving path@paramArray $allow file upload type return string $filename filename false */ is returned on failure

	function upload($name,$dir='./upload/',$allow=array('jpg'.'gif'.'jpeg'.'png')){
		//echo $name; exit;
		//var_dump($_FILES); exit;
		//1. Check whether the file is uploaded incorrectly
		if($_FILES[$name]['error'] >0) {//echo 'upload error ';
			switch($_FILES[$name]['error']) {case 1:
					echo 'The uploaded file exceeded the limit for the upload_max_filesize option in php.ini.';
					break;
				case 2:
					echo 'Uploaded file size exceeds the value specified by the MAX_FILE_SIZE option in the HTML form';
					break;
				case 3:
					echo 'Only part of the file was uploaded.';
					break;
				case 4:
					echo 'No files uploaded.';
					break;
				case 6:
					echo 'Cannot find temporary folder.';
					break;
				case 7:
					echo 'File write failed.';
					break;
			}
			return false;
		}

		//2. Determine if the type of file you upload is what you want
		//2.1 Types of uploads allowed
		
		//2.2 Obtaining the suffix name
		$suffix = pathinfo($_FILES[$name]['name'],PATHINFO_EXTENSION);
		//echo $suffix; exit;
		//2.3 Check whether it is the type of upload we allow
		//var_dump(in_array($suffix,$allow)); exit;
		if(! in_array($suffix,$allow)){// Type of upload not allowed
			echo  'Your upload type does not match';
			return false;
		}
		/ / 3. The name
		$filename = date('Ymd').uniqid().mt_rand(0.9999).'. '.$suffix;
		//echo $filename; exit;
		
		//4. Check whether the save path exists
		4.1 Get the save path
		
		//4.2 Handle the save path and the trailing slash
		$save_path = rtrim($dir,'/');
		$save_path .='/';
    
		//4.3 Save time folder processing in path
		$save_path .=date('Y/m/d/');
    
		//4.4 Check whether the save path exists
		if(! file_exists($save_path)){ mkdir($save_path,777.true);
		}
    
		//4.5 Splice a complete save path
		$path = $save_path.$filename;
		//echo $path; exit;

		
		//5. Check whether the file is uploaded in HttpPost mode
		if(! is_uploaded_file($_FILES[$name]['tmp_name'])){
			echo 'fuck off! ';
			return false;
		}
		
		//6
		if(! move_uploaded_file($_FILES[$name]['tmp_name'],$path)){
			echo 'Move failed';
			return false;
		}
		
		//7. Return the name of the image that was moved successfully
		return $filename;

	}
Copy the code

Call the function to start uploading:


      
	include './function.php';
	//var_dump($_FILES); exit;

	echo upload('file'.'./leiding'.array('jpg'.'png'));
Copy the code

Chapter 2 multi-file upload

2.1 Uploading Multiple Files with Different Names

When multiple files need to be uploaded, there are two implementation solutions:

1) Use different form elements.

<input type="file" name="file_a">
<input type="file" name="file_b">
<input type="file" name="file_c">
Copy the code
  1. Use form elements in array format.
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
Copy the code

Chapter 3 File download

  1. If the browser does not know other files, you can download them directly using the A connection.
	<! -- Because the three browsers don't recognize this type -->
	<a href="./downlist/1.rar">1.rar</a>
	<a href="./downlist/1.exe">1.exe</a>
	<a href="./downlist/1.avi">1.avi</a>

Copy the code
  1. For browsers that don’t know anything else, you can use the readfile function.
	<! The browser recognizes such a type and parses it.
	<a href="./action.php? name=1.html">1.html</a>
	<a href="./action.php? name=1.php">1.php</a>
	<a href="./action.php? name=1.txt">1.txt</a>
	<a href="./action.php? name=1.jpg">1.jpg</a>
Copy the code
// Accept the name value.
$name = $_GET['name'];

// Implement the download function
// Forces the browser to pop up the Save as dialog box
header('content-Disposition:attachment; filename="'.$name.'"');

// You can download an empty file and use readfile to read all contents. Can be downloaded.
$path = './downlist/'.$name;
readfile($path);
Copy the code