Three-Step FTP implementation PHP file upload code analysis

Source: Internet
Author: User
Tags http file upload php file upload ftp client ftp protocol

If you want to know the detailed steps for uploading a file, I will take you through the detailed analysis below. With PHP, you can always complete a specific task in multiple ways. Let's take file upload as an example. Of course, you can use the traditional method to upload HTTP files and directly transfer the files to the Web server disk. You can also upload files in a more exotic way, using the FTP protocol in two steps: from your local hard disk to the Web server, and then to the FTP server.

PHP supports both FTP and HTTP uploads on the local machine, so you can make the best choice according to your application design needs. Using the FTP function of PHP for file transfer is almost the same as using the traditional FTP client-you will see that the name of the function is similar to the standard FTP command. There are already many articles about HTTP File Upload, which is why it is necessary to focus on FTP-based file upload (but in the example below, ). Note that this tutorial assumes that you have installed PHP/Apache and the HTTP File Upload and FTP functions are activated. This article can be downloaded from here. All source code is listed in a separate text format.

Step 1: Make sure you have the permission to connect to/upload to the FTP server

Php ftp functions require client-server connection, so you need to log on to the target server before uploading files. Your first task is to make sure that you have the trust book to complete this task. This step may seem to be taken for granted, but you will be surprised to find how many developers have forgotten to do so. As a result, they will waste a lot of time to solve the problem. You can log on to the target server by using the FTP client of the command line to check the connection status and try to upload a fake file.

PHP File Upload Code List

 
 
  1. $ftp  
  2. ftp>opensome.host.com  
  3. Connectedtosome.host.com.  
  4. 220WelcometoleonFTPServer!  
  5. User:upload  
  6. 331Useruploadokay,needpassword.  
  7. Password:***  
  8. 230Restricteduserloggedin.  
  9. ftp>bin  
  10. 200Typeokay.  
  11. ftp>hash  
  12. HashmarkprintingOn?ftp:(2048bytes/hashmark).  
  13. ftp>putfile.bin  
  14. 200PORTcommandsuccessful.  
  15. 150OpeningBINARYmodedataconnection.  
  16. ##  
  17. 226Transfercompleted.  
  18. ftp:4289bytessentin0.00Seconds4289000.00Kbytes/sec.  
  19. ftp>bye  
  20. 221Goodbye. 

Once you confirm that you have the relevant access permissions, you can log in.

Step 2: Create an upload form

Then, create a simple HTML form and ask the user about the access information of the FTP server, the directory uploaded by the server, the complete directory and the name of the uploaded file. The following example shows the form style.

PHP file upload code list B

 
 
  1. <html> 
  2. <head></head> 
  3. <body> 
  4. <h2>Pleaseprovidethefollowinginformation:</h2> 
  5.  
  6. <formenctypeformenctype="multipart/form-data"method="post"action="upload.php"> 
  7. <inputtypeinputtype="hidden"name="MAX_FILE_SIZE"value="5000000"/> 
  8. Host<br/> 
  9. <inputtypeinputtype="text"name="host"/><p/> 
  10. Username<br/> 
  11. <inputtypeinputtype="text"name="user"/><p/> 
  12. Password<br/> 
  13. <inputtypeinputtype="password"name="pass"/><p/> 
  14. Destinationdirectory<br/> 
  15. <inputtypeinputtype="text"name="dir"/><p/> 
  16. File<br/> 
  17. <inputtypeinputtype="file"name="file"/><p/> 
  18. <inputtypeinputtype="submit"name="submit"value="UploadFile"/> 
  19. </form> 
  20. </body> 
  21. </html> 

Here, the <inputtype = file...> element is used to generate the file selection dialog box. You can use it to select the file to be uploaded. <Formenctype =...> the Element then encodes the form data into multiple parts for submission, which makes it easier for PHP to identify submitted file components.

Step 3: Create a PHP Upload Handler

Once the form is submitted to the Web server, the next step (and the last step) is to use the FTP function of PHP to transmit it to the target server according to the user-provided access trust book. The following is the script (upload. php) That completes all the above work ).

PHP file upload code list C

 
 
  1. <?php 
  2. //getFTPaccessparameters  
  3. $host=$_POST['host'];  
  4. $user=$_POST['user'];$pass=$_POST['pass'];  
  5. $destDir=$_POST['dir'];  
  6. $workDir="/usr/local/temp";//definethisasperlocalsystem  
  7. //gettemporaryfilenamefortheuploadedfile  
  8. $tmpName=basename($_FILES['file']['tmp_name']);  
  9. //copyuploadedfileintocurrentdirectory  
  10. move_uploaded_file($_FILES['file']['tmp_name'],$workDir."/".$tmpName)ordie("Cannotmoveuploadedfiletoworkingdirectory");  
  11. //openconnection  
  12. $conn=ftp_connect($host)ordie("Cannotinitiateconnectiontohost");  
  13. //sendaccessparameters  
  14. ftp_login($conn,$user,$pass)ordie("Cannotlogin");  
  15. //performfileupload  
  16. $upload=ftp_put($conn,$destDir."/".$_FILES['file']['name'],$workDir."/".$tmpName,FTP_BINARY);  
  17. //checkuploadstatus  
  18. //displaymessage  
  19. if(!$upload){  
  20. echo"Cannotupload";  
  21. }else{  
  22. echo"Uploadcomplete";  
  23. }  
  24. //closetheFTPstream  
  25. ftp_close($conn);  
  26. //deletelocalcopyofuploadedfile  
  27. unlink($workDir."/".$tmpName)ordie("Cannotdeleteuploadedfilefromworkingdirectory--manualdeletionrecommended");  
  28. ?> 

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.