Simple interaction between PHP and the server file system _ php instance

Source: Internet
Author: User
This article mainly introduces the simple interaction between PHP and the server file system. it is very good and has reference value. if you are interested, let's take a look. 1. setting commands for file upload in php. ini

2. file upload process

(1) html code of the form for file upload and submission:

     
  Adminstration-upoload new files  Upload new files 

(2) php processes the uploaded file code

① In the php script, the data to be processed is stored in the Super variable array $ _ FILES. enabling the register_globals command can directly access this information through the variable name;

② If the form variable is named "username", there are:

$ _ FILES ['userfile'] ['tmp _ name']: the temporary storage location of the stored FILES on the Web server;
$ _ FILES ['userfile'] ['name']: stores the name of a file in the user's system;
$ _ FILES ['userfile'] ['size']: size of the stored file;
$ _ FILES ['userfile'] ['type']: type of the stored file;
$ _ FILES ['userfile'] ['error]: stores any error code related to file upload;

Error Type description:

UPLOAD_ERR_INI_SIZE: 1. the uploaded file exceeds the limit of the upload_max_filesize option in php. ini.
UPLOAD_ERR_FORM_SIZE: 2. the size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form.
UPLOAD_ERR_PARTIAL: 3. only part of the file is uploaded.
UPLOAD_ERR_NO_FILE: 4. no file is uploaded.
UPLOAD_ERR_NO_TMP_DIR: 6. the temporary folder cannot be found. PHP 4.3.10 and PHP 5.0.3 are introduced.
UPLOAD_ERR_CANT_WRITE: 7. file writing failed. PHP 5.1.0 is introduced.

③ Php code

<? Php // verify if ($ _ FILES ['userfile'] ['error']> 0) {echo 'problem '; switch ($ _ FILES ['userfile'] ['error']) {case 1: echo 'file exceeded upload_max_filesize '; break; case 2: echo 'file exceeded max_file_size '; break; case 3: echo 'file only partially upload'; break; case 4: echo 'No File uploaded'; break; case 6: echo 'cannot upload file: no temp directory specified '; break; case 7: echo 'upload failed: Cann Ot write to disk'; break;} exit;} // check whether the transmitted file is a text file if ($ _ FILES ['userfile'] ['type']! = 'Text/plain ') {echo 'problem: file is not plain text'; exit ;} // include the uploaded file in the/uploads/directory on the server (this directory must be independent of the Web document tree) $ upfile = '/uploads /'. $ _ FILES ['userfile'] ['name']; // create a new file if (is_uploaded_file ($ _ FILES ['userfile'] ['tmp _ name']) with the file name of the transfer file in the specified directory) {if (! Move_uploaded_file ($ _ FILES ['userfile'] ['tmp _ name'], $ upfile) {// Move the temporary file for transfer to the created file echo 'problem: cocould not move file to destination directory '; exit;} else {echo 'problem: Possible file upload attack. filename: '; echo $ _ FILES ['username'] ['name']; exit;} echo "File uploaded seuucessfully

"; // Mark html and php for the transfer file $ contents = file_get_contents ($ upfile); // extract the file content into a string; $ contents = strip_tags ($ contents ); // erase the html and tags of the string; file_put_contents ($ _ FILES ['userfile'] ['name'], $ contents ); // re-write the string to the file; // display the transmitted text file content in the browser echo"

Preview of uploaded file contents:
> "; Echo nl2br ($ contents); echo"
";

3. use directory functions

(1) read the file name from the Directory

① Use the opendir (), readdir (), closedir () functions;

<? Php $ current_dir = '/uploads/'; // Create a Directory url object $ dir = opendir ($ current_dir); // open the directory and return a directory object echo"

Upload directory is $ current_dir

"; Echo"

Directory Listing:

    "; While ($ file = readdir ($ dir ))! = False) {// read the directory object if ($ file! = "." & $ File! = "..") {// Filter the current directory and the upper-level directory echo"
  • $ File
  • "; Echo" ". $ file ."
    ";}} Echo"
"; Closedir ($ dir); // Close the directory;?>

② Use php's dir class

<? Php $ current_dir = '/uploads/'; // Create a Directory url object $ dir = dir ($ current_dir); // create the dir object echo"

Handle is $ dir-> handle

"; Echo"

Upload directory is $ current_dir

"; Echo"

Directory Listing:

    "; While ($ file = $ dir-> read ())! = False) {// read the file name in the directory through the dir object if ($ file! = "." & $ File! = "...") {Echo"
  • $ File
  • ";}} Echo"
"; $ Dir-> close (); // close the directory?>

(2) use the scandir () function to sort text names alphabetically

<? Php $ current_dir = '/uploads/'; // Create a Directory url object $ files1 = scandir ($ current_dir); // Save the file name in the specified directory as an array, by default, $ files2 = scandir ($ current_dir, 1) is sorted in ascending alphabetical order. // Save the file names in the specified directory as an array and sort them in descending alphabetical order. echo"

Upload directory is $ current_dir

"; Echo"

Directory Listing in alphabetical order, ascending:

    "; Foreach ($ files1 as $ file1) {if ($ file1! = "." & $ File1! = "...") Echo"
  • $ File1
  • ";} Echo"
";?>

(3) obtain other information about the current directory

Dirname ($ path): returns the directory part of the path;

Basename ($ path): return the name of the path;

Disk_free_space ($ path): the disk where the returned path is located can store the size of uploaded files;

(4) create and delete directories

① Mkdir (): create a directory;

Code:

$ Oldumask = umask (0); // reset the current permission code mkdir ("/tmp/testing", 0777); // create the directory umask ($ oldumask ); // restore the current permission code

② Rmdir (): delete the directory;

Code:

Rmdir ("/temp/testing"); or rmdir ("c: \ tmp \ testing ');

※The directory to be deleted must be empty;

4. interaction with the file system

(1) Get file information:

While ($ file = readdir ($ dir ))! = False) {echo "". $ file ."
";}<? Php $ current_dir = '/uploads/'; $ file = basename ($ file); // Obtain the file name echo "Details of File"; echo "file data "; echo 'file last accessed :'. date ('j f y h: I ', fileatime ($ file ))."
"; // Return the recent access timestamp echo 'file last modifixed: '. date ('j f y h: I', filemtime ($ File ))."
"; // Return the last modified timestamp $ user = posix_getpwuid (fileowner ($ file); // return the uid echo 'file owner :'. $ user ['name']."
"; $ Group = posix_getgrgid (filegroup ($ file); // return the organization ID gid echo 'file group: '. $ group ['name']."
"; Echo 'file permissions: '. decoct (fileperms ($ File ))."
"; // Return the 8-bit permission code echo 'file type'. filetype ($ File )."
"; // Return the File type echo 'file size'. filesize ($ file )."
"; // Number of returned File bytes echo" File Tests "; echo 'is _ dir? '. (Is_dir ($ file )? 'True': 'false ')."
"; Echo 'is _ executable? '. (Is_executable ($ file )? 'True': 'false ')."
"; // Determine whether the file is executable; echo 'is _ file? '. (Is_file ($ file )? 'True': 'false ')."
"; Echo 'is _ link? '. (Is_link ($ file )? 'True': 'false ')."
"; Echo 'is _ readable? '. (Is_readable ($ file )? 'True': 'false ')."
"; Echo 'is _ writable? '. (Is_writable ($ file )? 'True': 'false ')."
";?>

(2) modifying file properties

Chgrp (file, group): modifies the file group;

Chmod (file, permissions): modify the object ACL;

Chown (file, user): modifies the object owner;

(3) creating, deleting, and moving files

Bool touch ($ filename, [int time, [int atime]): creates a file (time specifies the creation timestamp, and atime specifies the optional timestamp)

Unlink ($ filename): deletes an object.

Copy ($ source_path, $ destination_path): copy an object

Rename ($ oldfile, $ newfile): rename an object;

(4) use a program to execute functions

① String exec (String command [, array result [, int result_value])

Return the last row of the naming result. The result variable can return the number of character groups. these strings represent each row of the output. result_value gets the return code;

② Void passthru (String command [, int result_value])

The result is directly output to the browser;

③ String system (string command [, int return_value])

Output the result to the browser and return the last line or false of the command result;

※The data submitted by the user includes part of the command execution, which should be packaged as follows:

System (escapeshellcmd ($ command ));

5. interaction with environment variables

Phpinfo () function: obtains the list of all php variables;

Getenv ("$ key_name "):

Setenv ("$ key_name = $ value ");

The above is a simple interaction between PHP and the server file system introduced by Xiaobian. I hope it will help you. if you have any questions, please leave a message and I will reply to you in a timely manner. I would like to thank you for your support for the script home website!

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.