A simple PHP File Upload example Program

Source: Internet
Author: User
Tags php file upload

This article introduces a simple PHP File Upload sample code for beginners. If you need to learn it, you can refer to it.

The Code is as follows: Copy code

<? Php

// Define the prompt Function

Function alert ($ msg ){

Return '<script type = "text/javascript"> alert ("'. $ msg. '"); window. history. back (-1); </script> ';

}


// Define the allowed file types

$ AllowType = array ('image/jpeg ', 'image/gif', 'image/jpg ');


// Define the path, either absolute or relative.

$ FilePath = './uploadFileDir /';

 

// Receives the form information. The file value written in the form is the name value in the form of the Static Page.

$ File = $ _ FILES ['file'];

 

// Step 1: Determine whether the uploaded file is incorrect

If ($ file ['error']! = 0 ){

Exit (alert ('file upload error '));

}

 

// Step 2: Determine the file size. Here, 102400 is the byte, and the conversion to kb is kb.

If ($ file ['SIZE']> 102400 ){

Exit (alert ('file oversized '));

}

 

// Step 3: Determine the file type

If (! In_array (mime_content_type ($ file ['tmp _ name']), $ allowType )){

Exit (alert ('file type error '));

}

 

// Step 4: Determine whether the path exists. If not, create

If (! File_exists ($ filePath )&&! Mkdir ($ filePath, 0777, true )){

Exit (alert ('Directory creation error '));

}

 

// Step 5: Define the uploaded name and Path

$ Filename = time (). '_'. $ file ['name'];

 

// Step 6: copy the file

If (! Copy ($ file ['tmp _ name'], $ filePath. $ filename )){

Exit (alert ('file upload error, please try again later '));

}

 

// Step 7: delete a temporary file

Unlink ($ file ['tmp _ name']);

 

// Prompt that the upload is successful

Echo alert ('Congratulations, the file ['. $ filename.'] is uploaded successfully! ');
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.