[PHP] advanced tutorial: Case study on opening, closing, and uploading files in PHP

Source: Internet
Author: User
The fopen () function is used to open a file in PHP. The first parameter of this function contains the name of the file to be opened. The second parameter specifies which mode is used to open the file: htmlbody? Php?filefopen(welcome.txt, r );? The bodyhtml file may be opened in the following mode: r: read-only. Start at the beginning of the file. R:

The fopen () function is used to open a file in PHP. The first parameter of this function contains the name of the file to be opened. The second parameter specifies which mode is used to open the file: htmlbody? Php?file=fopen(welcome.txt, r );? The/body/html file may be opened in the following mode: r: read-only. Start at the beginning of the file. R:

Open a file
The fopen () function is used to open a file in PHP.
The first parameter of this function contains the name of the file to be opened, and the second parameter specifies the mode used to open the file:
 

The file may be opened in the following mode:
R: read-only. Start at the beginning of the file.
R +: read/write. Start at the beginning of the file.
W: Write only. Open and clear the file content. If the file does not exist, create a new file.
W +: read/write. Open and clear the file content. If the file does not exist, create a new file.
A: append. Open and write to the end of the file. If the file does not exist, create a new file.
A +: Read/append. Write content to the end of the file to keep the file content.
X: Write-only. Create a new file. If the file already exists, FALSE is returned.
X +: read/write. Create a new file. If the file already exists, FALSE and an error are returned.

NOTE: If fopen () cannot open the specified file, 0 (false) is returned ).


Example

If fopen () cannot open the specified file, the following example generates a message:
 

Close file
The fclose () function is used to close open files.
 


Detect End-of-file
The feof () function checks whether it has reached the end of the file (EOF ).
The feof () function is useful when data with unknown length is traversed cyclically.
Note: In w, a, and x modes, you cannot read open files!
if (feof($file)) echo "End of file";

Read files row by row
The fgets () function is used to read objects row by row from objects.
Note: After the function is called, the file pointer is moved to the next row.
Example
The following example reads the file row by row until the end of the file:
 ";  }fclose($file);?>



Read files by character

The fgetc () function is used to read files from a file character by character.
Note: After the function is called, the file pointer is moved to the next character.
Example
The following example reads the file one by one until the end of the file:
 

Upload files in the following steps:

1. Create a file upload form

It is very useful to allow users to upload files from forms.
See the following HTML form for uploading files:
 

When a form requires binary data, such as file content, use multipart/form-data ".

For example, when previewing in a browser, a browser button is displayed next to the input box.

Note: allowing users to upload files is a huge security risk. Only trusted users are allowed to upload files.

Effect:




2. Create an upload script
The "upload_file.php" file contains the code for uploading files:
  0)  {  echo "Error: " . $_FILES["file"]["error"] . "
"; }else { echo "Upload: " . $_FILES["file"]["name"] . "
"; echo "Type: " . $_FILES["file"]["type"] . "
"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; }?>

Effect:


By using the Global Array $ _ FILES of PHP, you can upload FILES from the client computer to a remote server.

The first parameter is the input name of the form, and the second subscript can be "name", "type", "size", "tmp_name" or "error ". Like this:

  • $ _ FILES ["file"] ["name"]-name of the uploaded file
  • $ _ FILES ["file"] ["type"]-type of the file to be uploaded
  • $ _ FILES ["file"] ["size"]-size of the uploaded file, in bytes
  • $ _ FILES ["file"] ["tmp_name"]-name of the temporary copy of the file stored on the server
  • $ _ FILES ["file"] ["error"]-error code caused by file Upload

This is a very simple File Upload method. Based on security considerations, you should add restrictions on which users have the right to upload files.

$ _ FILES is a multi-dimensional array. The first dimension is the array of files, because the input name (not id or other) in the form is file. The second dimension is the data of each file, including the attributes listed above.



Upload restrictions

In this script, we have added restrictions on file upload. You can only upload. gif or. jpeg files. The file size must be smaller than 20 kb:
  0)    {    echo "Error: " . $_FILES["file"]["error"] . "
"; } else { echo "Upload: " . $_FILES["file"]["name"] . "
"; echo "Type: " . $_FILES["file"]["type"] . "
"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } }else { echo "Invalid file"; }?>
Note: For IE, the jpg file type must be pjpeg and for FireFox, it must be jpeg.



Save the uploaded file

In the above example, a temporary copy of the uploaded file is created in the PHP temporary folder on the server.
The temporary copy file will disappear at the end of the script. To save the uploaded file, we need to copy it to another location:
  0)    {    echo "Return Code: " . $_FILES["file"]["error"] . "
"; } else { echo "Upload: " . $_FILES["file"]["name"] . "
"; echo "Type: " . $_FILES["file"]["type"] . "
"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } }else { echo "Invalid file"; }?>
The above script checks whether the file already exists. If it does not exist, copy the file to the specified folder.

Note: In this example, the file is saved to a new folder named "upload". The folder must exist if it is not required to be created.

The move_uploaded_file (file, newloc) function moves the uploaded file to a new location.

If yes, true is returned. Otherwise, false is returned.

File required-specifies the file to be moved. Newloc required-specifies the new location of the file.

When using the move_uploaded_file () function, the following error may occur:
Warning: move_uploaded_file (/dest/inat/ion. ext) [function. move-uploaded-file]: failed to open stream: No such file or directory in/upload/handler. php on line X
Warning: move_uploaded_file () [function. move-uploaded-file]: Unable to move '/temp/file/name' to'/dest/inat/ion. ext 'in/upload/handler. php on line X
It is generally not '/temp/file/name '... the path '/dest/inat' does not exist. if so, the problem is solved by creating the path.

In this case, the path is correct, but the access path is used, rather than the internal file operation path, leading to the failure of file writing.

In addition, do not add "\" to the part at the beginning of the written path, for example, "uploads \'. $ _ FILES ['userfile'] ['name'] "is written as" '\ uploads \'. $ _ FILES ['userfile'] ['name'] ".

In short, the first check is the path to be written, and the problem is likely to be found here.

But even so, an error is reported:
Warning: move_uploaded_file (upload/12.jpg) [function. move-uploaded-file]: failed to open stream: Permission denied inupload_file.php on line24

Warning: move_uploaded_file () [function. move-uploaded-file]: Unable to move '/saetmp/928/xquer/logs/phppSXyZ6' to 'upload/12.jpg 'inupload_file.php on line24

This is generally because you do not have the permission to read and write folders.

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.