Getting started with php

Source: Internet
Author: User
Tags flock fread getting started with php

(1) file creation and opening;
(2) file operations;
(3) close the file;

In PHP, a series of functions are used to perform file operations. Common functions and their brief descriptions are listed as follows:

// Open the file to open the file (you can create a file when the file does not exist). Operations vary depending on the mode in the file.
Resource fopen (string $ filename, string $ mode [, bool $ use_include_path = false [, resource $ context])
// $ Filename indicates the path and file name of the file to be opened or created. It is better to use a backslash (/) for ease of transplantation.
// $ Mode is the file opening mode. There are many modes, which are commonly used, such as r, w, and a. To facilitate transplantation, we recommend that you add B (binary) to the mode)
// Normally, the read file is rb, and the write file is AB, indicating that the file is read in binary format and the content is appended to the file in binary format.
// When an error occurs during the file opening operation, first check the permission settings for the file path.
 

The code is as follows: Copy code
// File operation functions
 
// Write related functions
// Write $ string to the file pointer $ handle
Int fwrite (resource $ handle, string $ string [, int $ length])
// The function is the alias function of fwrite.
Fputs ()
 
// Write operations can also be completed. The difference is that fopen (), fwrite (), and fclose () are integrated. You do not need to open or close the file again when using this function.
Int file_put_contents (string $ filename, mixed $ data [, int $ flags = 0 [, resource $ context])
 
// Read operation related functions
// Read data row by row
String fgets (resource $ handle [, int $ length])
// Read row by row to filter tags
String fgetss (resource $ handle [, int $ length [, string $ allowable_tags])
// Read row by row, which can be output to the array according to the delimiters
Array fgetcsv (resource $ handle [, int $ length = 0 [, string $ delimiter = ',' [, string $ enclosure = '"'[, string $ escape = '\'])
// Read a file at a time and send the file content to the standard output, including opening and closing the file
Int readfile (string $ filename [, bool $ use_include_path = false [, resource $ context])
// Open the file first, and then send the file content pointed to by the file pointer to the standard output
Int fpassthru (resource $ handle)
// Send the result to an array
Array file (string $ filename [, int $ flags = 0 [, resource $ context])
// Read one character at a time
String fgetc (resource $ handle)
// Read any length of bytes
String fread (resource $ handle, int $ length)
 
// Close the file
Bool fclose (resource $ handle)
 
// Common functions in file operations
// Check whether the file or directory exists
Bool file_exists (string $ filename)
// Get the file size, returns the number of bytes of the file size
Int filesize (string $ filename)
// Delete an object
Bool unlink (string $ filename [, resource $ context])
// Reset the file pointer position
Bool rewind (resource $ handle)
// Locate in the file pointer
Int fseek (resource $ handle, int $ offset [, int $ whence = SEEK_SET])


The detailed description of the function can be found in php.net. The following describes how to perform the operations in the file. The exercise name is "simple Diary". The requirements are as follows:

(1)the content of the Daily Record is saved in the data directory from year to month to day;
(2) keep a diary on the homepage and display previous records;
(3) display the single-page record content;

 

The code is as follows:

Home page (index. php)

The code is as follows: Copy code
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "utf-8">
<Title> Simple Diary-php file operation exercises </title>
<Style>
H1 {
Font-size: 24px;
Border-bottom: 1px solid #000;
Line-height: 40px;
      }
. Active {
Line-height: 22px;
Font-size: 14px;
Background: # 2cf;
Padding: 8px;
Text-decoration: none;
      }
. Btn {
Width: 100px;
Height: 40px;
      }
</Style>
</Head>
<Body>
<H1> my notebook <P> <span class = "active"> write diary </span> </p>
<Form name = "writediary" method = "POST" action = "diaryprocessed. php">
<P> diary topic </p>
<Input type = "text" name = "diarytopic" size = "60" maxlength = "100"/>
<P> diary content </p>
<Textarea name = "diarycontents" rows = "10" cols = "53"> </textarea>
<P> <input class = "btn" type = "submit" name = "save" value = "save"/> </p>
</Form>
<Hr>
<P> <span class = "active"> diary list </span> </p>
<Hr>
<? Php
$ Handler = opendir ($ _ SERVER ['document _ root']. '/phpcodes/diarydatas /');
While ($ diaryname = readdir ($ handler ))! = False ){
If ($ diaryname! = "." & $ Diaryname! = ".."){
$ Files [] = $ diaryname;
        }
      }
Closedir ($ handler );
Foreach ($ files as $ value ){
Echo "<a href = viewdiary. php? Id = ". substr ($ value, 0, (strlen ($ value)-4)."> $ value </a> "." | ";
      }
?>
</Body>
</Html>


Save the processing page (diaryprocessed. php)

The code is as follows: Copy code
<? Php
Header ('content-Type: text/html; charset = utf-8 ');
 
$ Date = gmdate ('Y-m-D', time () + 3600*8 );
 
$ Diarytopic =$ _ POST ['diarytopic '];
 
$ Diarycontents =$ _ POST ['diarycontents'];
 
$ DOCUMENT_ROOT = $ _ SERVER ['document _ root'];
 
$ Output = $ diarytopic. "n". $ diarycontents. "n ";
 
$ Fp = fopen ($ DOCUMENT_ROOT. '/phpcodes/diarydatas/'. $ date. '.txt ',' AB ');
 
Flock ($ fp, LOCK_EX );
 
If (! $ Fp ){
Echo "<p> <strong> logs submitted by you cannot be processed currently. Please try again later! </Strong> </p> ";
Echo "<a href =" index.htm "> Return </a> ";
}
 
Fwrite ($ fp, $ output );
 
Flock ($ fp, LOCK_UN );
 
Fclose ($ fp );
 
Echo 'Diary submitted successfully! ';
Echo "<a href =" index.htm "> Return </a> ";


View the content page (viewdiary. php)

The code is as follows: Copy code

<? Php
$ DOCUMENT_ROOT = $ _ SERVER ['document _ root'];
?>
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "utf-8">
<Title> simple diary </title>
<Style>
* {Line-height: 32px ;}
</Style>
</Head>
<Body>
<A href = "index. php"> write a diary </a>
<Hr>
<? Php
$ Diaryname = $ _ GET ['id'];
$ Filepath = $ DOCUMENT_ROOT. '/phpcodes/diarydatas/'. $ diaryname. '.txt ';
If (file_exists ($ filepath )){
$ Fp = fopen ($ filepath, 'RB ');
Echo nl2br (fread ($ fp, filesize ($ filepath )));
Fclose ($ fp );
      }
?>
</Body>
</Html>

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.