PHP learning file processing and file Upload courseware

Source: Internet
Author: User
Tags dname filegroup flock php file upload rewind
It mainly includes php file processing, file processing, file pointer-related processing functions, file control functions, including PHP file processing, file processing, file pointer-related processing functions, and file control functions.

PHP file processing
In the application of PHP files on the server, the related scope is not only the various connection and access operations between the user and the server database, but also the file processing functions built in PHP, to process General files.

Basename -- returns the file name part of the path.
Syntax format: $ path = "/home/httpd/html/index. php ";
$ File = basename ($ path); // $ file is set to "index. php"
$ File = basename ($ path, ". php"); // $ file is set to "index"

Pathinfo (): current path of the analysis File
Syntax format: $ path_parts = pathinfo ("/www/htdocs/index.html ");
Echo $ path_parts ["dirname"]. "\ n";/www/htdocs file path
Echo $ path_parts ["basename"]. "\ n"; index.html file and extension
Echo $ path_parts ["extension"]. "\ n"; html file format

File type and related information
Filesize (): calculates the file size (byte)
Syntax format: $bytes=filesize(“a.txt ");
Echo $ bytes round ($ bytes/1024,2 );
Fileatime (): Last file access time (timestamp)
Syntax format: echo date ("Y-m-d g: I: sa", fileatime );
Filectime (): File creation time
Syntax format: echo date ("Y-m-d g: I: sa", filectime );
Filemtime (): Last file update time
Syntax format: echo date ("Y-m-d g: I: sa", filemtime );
Fileperms (): File attributes and 10-digit permission
Syntax format: echo substr(base_convert(fileperms(a.txt), 10, 8), 3 );
Fileowner (): uid of the file owner (available only in Linux)
Syntax format: echo fileowner()a.txt ");

File operations
'R' is opened in read-only mode. it directs the file pointer to the file header.
Open in 'R + 'read/write mode and point the file pointer to the file header.
Open in 'W' writing mode, point the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it.
Open in 'W + 'read/write mode, point the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it.
Open the 'A' write mode and point the file pointer to the end of the file. If the file does not exist, try to create it.
Open in 'A + 'read/write mode and point the file pointer to the end of the file. If the file does not exist, try to create it.

'X' is created and opened in writing mode. it directs the file pointer to the file header. If the file already exists, fopen () fails to be called, returns FALSE, and generates an E_WARNING-level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL | O_CREAT mark for the underlying open (2) system call. This option is supported by PHP 4.3.2 and later versions and can only be used for local files.
'X + 'is created and opened in read/write mode. the file pointer points to the file header. If the file already exists, fopen () fails to be called, returns FALSE, and generates an E_WARNING-level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL | O_CREAT mark for the underlying open (2) system call. This option is supported by PHP 4.3.2 and later versions and can only be used for local files.

Fopen () -- open a file or URL
Fclose () -- close an opened file pointer
Fread () -- read file content
Fwrite () -- write a file
Syntax format: if (! $ F = @ fopen ("file03.php", "x") {// open a file and write data using the x method
Die ("file read failed"); // read failed
}
Fwrite ($ f, "kkkkkkkkk"); // what to write to that file
Echo fread ($ f, 10); // read the content of this file
Fclose ($ f); close opening a file


File () -- read the entire file into an array
Syntax format: $ arr = file ("file03.php ");
Print_r ($ arr); // read the array returned by the file

Readfile () -- read a file and write it to the output buffer.
Syntax format: $ str = readfile ("file03.php ");
Echo $ str; output

Writing a file recorder:
$ F = fopen ("file03.php", "r ");
$ I = fread ($ f, 1000 );
Echo "this is your {$ I} access ";
Fclose ($ f );
$ F = fopen ("file03.php", "w ");
$ I ++;
Fwrite ($ f, $ I );
Fclose ($ f );
"""""""""""""'
File_get_contents ()-read the entire file into a string
Syntax format: file_get_contents (file name or URL)

File_put_contents ()-? Writing a string to a file is the same as calling the fopen (), fwrite (), and fclose () functions in turn.
File_put_contents (file name, write data)


Feof () -- test whether the file pointer is at the end of the file
Ftell () -- returns the read/write position of the file pointer.
Syntax format: ftell (file pointer)
Flock ()-Lightweight consultation file locking
Syntax format: flock (file pointer, control parameter)
File pointer: it is a file pointer control parameter that has been opened (fopen:
"LOCK_SH" indicates that the shared Lock (read program) is to be obtained (set 1 in PHP4.0.1 or earlier versions ).
"LOCK_EX" indicates to obtain an exclusive lock (write program) (set to 2 in PHP4.0.1 or earlier versions ).
"LOCK_UN" indicates to release the lock (whether shared or exclusive) (set to 3 in PHP4.0.1 or earlier versions ).
"LOCK_NB" indicates that if you do not want flock () to be blocked during the lock, add this parameter to the control parameter.

Fseek () -- Locate in file pointer
Syntax structure: fseek (file pointer, moving number of characters [, starting position constant])
File pointer: it cannot be used to open the returned file pointer in the format of "http: //" or "ftp: //" in fopen.
Number of characters to be moved: when the number is positive, move the object pointer forward to the specified number: when the number is negative, move the object pointer backward to the specified number:
Start position constant:
SEEK_CUR-set the current position.
SEEK_SET-the position is equal to the beginning of the file. (Default)
SEEK_END-set the position to the end of the file.


Rewind () -- returns the position of the file pointer, that is, moving the file pointer to the beginning of the file.
Syntax structure: rewind (file pointer)
Note: If you open the file in the append ("a" or "a +") mode, any data written to the file will always be appended, regardless of the file pointer location.

Chgrp () -- change the group to which the file belongs
Syntax structure: chgrp (file name, group name)

Filegroup () -- The Group for obtaining files
Syntax structure: filegroup (file name)

Chmod () -- change the file mode
Syntax structure: chmod (file name, permission constant) 755 666

Chown () -- change the file owner
Syntax structure: chown (file name, user)

Fileowner () -- get the file owner
Syntax structure: fileowner (file name)
Posix_getpwuid () to resolve it to the user name.



Copy () -- copy an object
Syntax structure: copy (source file, target file)
Return type: bool type. if it is successful, TRUE is returned. if it fails, FALSE is returned.
Parameter description: Future source files will be copied to the target file.
Unlink () -- delete an object
Syntax structure: unlink (target file)
Return type: bool type. if it is successful, TRUE is returned. if it fails, FALSE is returned.
Parameter description: deletes a specified target file.
Rename () -- rename a file or directory
Syntax structure: rename (old file name, new file name)
Return type: bool type. if it is successful, TRUE is returned. if it fails, FALSE is returned.
Parameter description: try to rename the old file name as the new file name.

File attribute processing
File_exists () -- check whether a file or directory exists
Syntax structure: file_exists (file name)
Return type: bool type. If yes, true is returned. otherwise, false is returned.
Filesize () -- get the file size
Syntax structure: filesize (file name)
Return type: number of file size bytes. If an error occurs, false is returned.
Filetype () -- get the file type
Syntax structure: filetype (file name)
Return type: type of the returned file. Possible values include fifo, char, dir, block, link, file, and unknown. If an error occurs, false is returned.
Is_dir () -- determines whether the specified file name is a directory.
Syntax structure: is_dir (name)
Return type: If the file name exists and is a directory, true is returned; otherwise, false is returned.
Is_executable () -- determines whether a given file name can be executed
Syntax structure: is_executable (name)
Return type: if the object exists and can be executed, TRUE is returned; otherwise, FALSE is returned.
Is_file () -- determine whether the given file name is a normal file
Syntax structure: is_file (name)
Return type: if the object exists and is a normal object, TRUE is returned.
Is_link () -- determines whether a given file name is a symbolic connection
Syntax structure: is_link (name)
Return type: true is returned if the object exists and is a symbolic connection.
Is_readable () -- determines whether the specified file name is readable.
Syntax structure: is_readable (file name)
Return type: Returns TRUE if the object exists and is readable.
Is_writable () -- determines whether a given file name can be written.
Syntax structure: is_writable (file name)
Return type: If the file exists and can be written, TRUE is returned.


Directory reading through the iterator interface
Standard Iterator interface method
Current (): returns the element values in the current list.
Next (): used to move a position down in a list.
Valid (): checks whether there is another element in the current list. If yes, true is returned; otherwise, false is returned.
Rewind (): You can access the list of elements of a specified feature. when you start to operate iterator, the pointer is set to the top.

DirectoryIterator custom class
GetATime (): Last object access time
GetCTime (): The last modification time of the object.
GetGroup (): group to which the object belongs (UNIX only)
GetInode (): File node (UNIX only)
GetOwner (): File host (UNIX only)
GetPerms (): permission to access the file
GetSize (): File Size
GetType (): Object Type
GetFileName (): file name
GetPath (): file path
IsDir (): whether it is a directory
IsExecutable (): whether it can be executed
IsFile (): whether it is a file
IsLink (): whether it is a soft link file
IsReadable (): whether it is readable
IsWritable (): whether to write
The isDot () method filters out the "." and "." directories respectively.


$ Dname = $ _ GET ["dname"]; // obtain the information of the from table
If (isset ($ dname )&&! Empty ($ dname) {// determines whether a variable is set to detect whether a variable is empty
$ Dir = new DirectoryIterator ("{$ dname}"); // A new Class
Echo $ dir-> getPath (). "// method of the class
} Else {
$ Dir = new DirectoryIterator ("D :\\"); // new d: // Directory
Echo $ dir-> getPath ();
}
$ Delname = $ _ GET ["del"];
If (isset ($ delname )&&! Empty ($ delname )){
If (unlink ("{$ dir-> getPath ()} \ $ delname "))
Echo "deleted successfully ";
}

While ($ dir-> valid ()){
If ($ dir-> isDir ())
Echo "getPath () }\\{$ dir-> current ()} '> ".
"{$ Dir-> current ()}
";
Else
Echo "{$ dir-> current ()} copy ".
"Current ()} '> Delete
";
$ Dir-> next ();
}

Example 2: function showdir ($ iter) {// set a function method and assign a value
For (; $ iter-> valid (); $ iter-> next () {// check whether the directory has another directory to move one bit down
If ($ iter-> isDir () & $ iter-> isDot () {// check whether it is a directory and filter out the directory location of the. and.
Echo "directory". $ iter-> current ()."
"; // Point to the value of the returned list element
} Else {
Echo $ iter-> current (). $ iter-> getSize (). "byte
"; Returns the value of the list and displays the file size.
}
}
}
Showdir (new DirectoryIterator ("C:/"); // transmits parameters to a new system default class
//////////////////////////////////////// //////////////////////////////////////// /////////////////////////////////////

Php file Upload
Interaction with file systems and servers
File upload 'use directory functions' interaction with the file system 'use program execution functions' interaction with environment variables


File Upload
In the B/S program, file Upload has become a common function. The purpose is to upload files to a specified directory on the Server through the Browser.
Basic knowledge of file upload in PHP
Form submit' operations on files

What is file upload?
To meet the needs of file information transmission: the HTTP protocol implements the file upload mechanism, so that the client files can be uploaded to a specified directory on the server through its own browser for storage.
The HTML specification specifies that a single table header must be used when a file is uploaded.

File Upload




Note the following features:
POST method:
The most common function of a form is to pass variables to the target page. when uploading a file, we set the corresponding attributes in the form to complete file transfer.
Enctype = "multipart/form-data"
In this way, the server will know that we want to pass a file so that the server can know that the uploaded file carries regular form information.
MAX_FILE_SIZE
This field must control the maximum transfer file size (in bytes) before the input field of the file. can this field be controlled?

Set the browser file input browse button

In php. ini on the server side, we can further judge the data passed in the form.
File_uploads = On/Off whether File upload is allowed
Upload_max_filesize = 2 M maximum size of the uploaded file
Post_max_size = maximum size allowed by 8 m post data
The data transmitted by the form. the file is only part of the file. Therefore, when setting the file, upload_max_filesize should be smaller than post_max_size.


Super Global Array $ _ FILES
In the PHP program, the uploaded data to be processed is saved in the global array $ _ FILES (Super Global array)
Save the elements in the $ _ FILES array and store the type = "file" tag name = "userfile" of the HTML form in the array.
The value stored in $ _ FILES ['userfile'] ['name'] is the file name of the client file system.
The value stored in $ _ FILES ['userfile'] ['type'] is the type of the file passed by the client.
The value stored in $ _ FILES ['userfile'] ['size'] is the size of the file's bytes.
Value stored in $ _ FILES ['userfile'] ['tmp _ name']: temporary full path stored on the server after the file is uploaded
""""""""""""""'
The value stored in $ _ FILES ['userfile'] ['error'] is the error code for file upload-a function added after php 4.2.
Value stored in $ _ FILES ['userfile'] ['error ']
0: indicates that no error has occurred.
1: The size of the uploaded file exceeds the agreed value. The maximum file size is specified in the PHP configuration file. the command is upload_max_filesize.
2: indicates that the size of the uploaded file exceeds the maximum value specified by the MAX_FILE_SIZE element of the hidden field attribute of the HTML form.
3: indicates that the object is only partially uploaded.
Value 4: indicates that no file is uploaded.
""""""""""""
Is_uploaded_file () check whether the file is uploaded
The move_uploaded_file (temporary PATH/temporary file name, destination path/destination file name) function copies the upload files stored in the temporary directory and stores them to the specified file name in the specified directory, if the target exists, it will be overwritten.
Example: print_r ($ _ FILES ["upfile"]); // Save the form submission system in this
Echo "file name". $ _ FILES ["upfile"] ["name"]; // file name
If ($ _ FILES ["upfile"] ["error"] <= 1) {// if the error code is smaller than 1, an error occurs.
Echo "select a file ";
}
If (is_uploaded_file ($ _ FILES ["upfile"] ["tmp_name"]) {// checks whether the file is a temporary path to the uploaded file.
Echo 'upload a file ';
Move_uploaded_file ($ _ FILES ["upfile"] ["tmp_name"], "./upload/". $ _ FILES ["upfile"] ["name"]);
// Transfer the temporary file to the upload directory with the original name
} Else {
Echo 'not Upload file ';
}
Temporary directory for storing uploaded files

The uploaded file is placed in the temporary directory on the server:/tmp directory and named as a unique, randomly generated temporary file name. Note: The file will be automatically deleted after the program is executed. Before deleting a file, you can perform the same operations as a local file.
The/tmp directory is the default location where temporary files are uploaded. if you need to change this directory, you can edit the upload_tmp_dir attribute value of the File Uploads segment in the/etc/php. ini File.
When the register_globals attribute of the configuration file php. ini is set to on

The global variable $ myfilename will be generated.

"""""""""""""""''
When multiple files need to be uploaded, there are two solutions:
Use different form elements


Use form elements in array format


""""""""""""""""'
Use directory functions
Opendir? --? Open Directory handle
Closedir? --? Close directory handle
Readdir? --? Read entries from the directory handle
Syntax format: $ d = opendir ("./upload"); // open the file directory
While ($ s = readdir ($ d) {// cyclically output read entries
Echo $ s ."
";
}
Closedir ($ d); // Close the handle

Create and modify directories
Mkdir? --? Create directory
Rmdir? --? Delete directory
Mkdir ("D: \ up"); // create a directory
Rmdir ("up"); // delete a directory

Disk operations
Disk_free_space (): calculates the remaining space of a disk.
Disk_total_space (): displays the capacity of the logical disk.
Echo disk_free_space ("D: \")/1024/1024/1024;
Echo disk_total_space ("D: \")/1024/1024/1024;
Getcwd (): return the path of the current script
Chdir (): similar to the DOS cd command, change the current path
Echo getcwd (); // view the current script path
Chdir ("D :\\"); // change

Execute functions using programs
The exec () function can use the command to be executed as a parameter.
The passthru () result is directly output to the browser.
System () is also directly output to the browser, but there is a return value

Related Article

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.