How to upload a file using PHP's move_uploaded_file function

Table of contents:

How to upload a file using PHP's move_uploaded_file function
How to upload a file using PHP's move_uploaded_file function
Anonim

At some point in your career, you will want to build true dynamic web applications. Maybe decide to write your social network. As a developer, you will try to interest users, give them the opportunity to upload photos, music, share files. In this case, you need to know and be able to work with the PHP function move uploaded file.

php move_uploaded_file() function
php move_uploaded_file() function

Data collection form

PHP supports uploading any files using the POST method. Therefore, to transfer data to the server, or save it to the local machine, an HTML form is needed. Use markup to highlight a separate place where the user can select a file. The scripts need to be set up so that the data is sent without failure. Let's look at this process using the example of uploading a profile photo.


First Name: Last Name: Image upload:

Note the enctype="multipart/form-data" attribute. It is thanks to him that the form is configured to receive data. To prevent users from thinking of uploading 25 MB cats, it is necessary to set a limit on the size of pictures in the hidden field. For2 MB profile picture is enough, as in this example.

PHP function move_uploaded_file
PHP function move_uploaded_file

Submit image

In the above form, the action attribute contains, which means that the image will be received and processed in the same document. If this confuses you and you want to have a separate script for each action, insert the script name in place of the construct, for example, create_profile.php. Now write all your code, including the PHP move uploaded file function, in this file.


'Max. file size specified in php.ini', 2=> 'Exceeded max. file size specified in HTML form', 3=> 'Only part of the file was sent', 4=> 'No file was selected to send.'); //check file upload error ($_FILES[$image_fieldname]['error']==0) or die("An error occurred while uploading file". $php_errors[$_FILES[$image_fieldname]['error']]); //check if the file is being uploaded normally or if it's a hack @is_uploaded_file($_FILES[$image_fieldname]['tmp_name']) or die('You will commit an immoral act, shame on you!'."File name: "."'{$ _FILES[$image_fieldname]['tmp_name']}'"); //is the file being sent an image @getimagesize($_FILES[$image_fieldname]['tmp_name']) or die("Error! The file you selected is not an image". "File name {$_FILES[$image_fieldname]['tmp_name']}"); //assigning a unique name to the uploaded file $now=time(); while(file_exists($upload_filename=$uploads_dir.$now.'-'.$_FILES[$image_fieldname]['name'])){ $now++; } ?>

There are auxiliary variables in the code:

  • $upload_dir contains the path to the upload directory. Instead of HOSW_WWW_ROOT, write the absolute path to the working directory on the server or on your computer.
  • The $image_fieldname variable is the field name for the image in the HTML form.

As you can see, before the move uploaded file call, there are lines that check the uploaded image. Of course, secure PHP applications are a myth, but there should be at least minimal protection.

The $php_errors error checking array does not start from zero, but from one. Index [0] is $_FILES[$image_fieldname]['error'], which returns the number 0 if the upload was successful. In PHP, $_FILES is a special array containing all the information about a file. To access this data, an index is used with the name of the input field, which we previously displayed in a separate variable $image_fieldname:


//check file upload error ($_FILES[$image_fieldname]['error']==0) or die("An error occurred while uploading file". $php_errors[$_FILES[$image_fieldname]['error']]);

When move uploaded file PHP doesn't work

Do you think you did everything right, but the interpreter throws an error? The file refuses to be uploaded to the assigned directory and appears in completely unexpected places? First of all check php.ini for allowed size in upload_max_filesize parameter. Most often, this error occurs with Denver. That's whyopen php.ini (usually located in the php folder) and just set the size you need:


;;;;;;;;;;;;;;;;;; File Uploads;;;;;;;;;;;;;;;;;; Whether to allow HTTP file uploads.; http://php.net/file-uploads file_uploads=On; Temporary directory for HTTP uploaded files (will use system default if not; specified).; http://php.net/upload-tmp-dir upload_tmp_dir=""; Maximum allowed size for uploaded files.; http://php.net/upload-max-filesize upload_max_filesize=5M; Maximum number of files that can be uploaded via a single request max_file_uploads=50

If you work on a server, ask your ISP what size files are allowed to be uploaded. On free hosting, the maximum size is usually 2 MB. The second reason code can fail is an incorrectly assigned directory. Check the second argument of the move_uploaded_file function, it must include the path and the name is required.

Popular topic

Editor's choice

  • The PHP mail function: description, application features
    The PHP mail function: description, application features

    E-mail is an integral part of any modern project or business. Nowadays, speed and responsiveness are of great value, especially when it comes to customer feedback. This is a decisive factor that users consider when making purchases

  • Shareware - what is it List of programs, description of programming principles
    Shareware - what is it List of programs, description of programming principles

    Shareware has battled the stigma of misunderstanding for decades. While enterprise software giants can no longer ignore the marketing potential of a trial, small startups still struggle with new software challenges and costs

  • What is var in Pascal
    What is var in Pascal

    Variable var is a name that the user assigns to computer memory cells and uses to store values in a computer program. It defines the type of information stored, describes the format of the value of the occupied memory and methods for manipulating the content

  • Java library: creating, processing, working with files
    Java library: creating, processing, working with files

    Experienced Java developer has extensive knowledge of APIs including JDK, libraries for everyday projects including Log4j, JSON parsing, Jackson. The problem is that not all Java library designers think about their users, how the API will be used in practice, and how the code will look and be tested

  • Compression algorithms: description, basic techniques, characteristics
    Compression algorithms: description, basic techniques, characteristics

    Currently, processor processing power is increasing faster than storage capacity and network bandwidth. Therefore, in order to compensate for the increase in the amount of data, they compress them. The compressor uses an optimization algorithm of the appropriate type. For subsequent recovery, a decompressor with the opposite direction of the process is required