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.
<?php$file = fopen("test.txt","r");//some code to be executedfclose($file);?>
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:
<?php$file = fopen("welcome.txt", "r") or exit("Unable to open file!");//Output a line of the file until the end is reachedwhile(!feof($file)) { echo fgets($file). "<br />"; }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:
<?php$file=fopen("welcome.txt","r") or exit("Unable to open file!");while (!feof($file)) { echo fgetc($file); }fclose($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:
<Form> the enctype attribute of a tag specifies the content type to be used when submitting a form.
When a form requires binary data, such as file content, use multipart/form-data ".
<Input> the type = "file" attribute of the tag specifies that the input should be processed as a file.
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:
<?phpif ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; }else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; 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:
<?phpif ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/pjpeg"))&& ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; 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:
<?phpif ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/pjpeg"))&& ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; 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.