Contacts

Php read file into variable. Php file creation, reading and writing. Non-linear file processing: moving through a file

downloads $_ (8)

I need to load a PHP file into a variable. For example include();

I loaded a simple HTML file like this:

$Vdata = file_get_contents("textfile.txt");

But now I need to load the PHP file.

Answers

If your file has a return statement:

"Afeganistão", "ZA" => "África do Sul", ... "ZW" => "Zimbabué");

You can get this variable like this:

$data = include $filePath;

Alternatively, you can start output buffering, do include/require, and then stop buffering. With ob_get_contents() you can simply get the stuff that was output by another PHP file into a variable.

If you want to download a file without running it through a web server, the following should work.

$string = eval(file_get_contents("file.php"));

The contents of the file will then be downloaded. The PHP file must be fully formed with tagsFor eval to evaluate it.

I'm guessing you want to get PHP generated content, if it is true:

$Vdata = file_get_contents("http://YOUR_HOST/YOUR/FILE.php");

Otherwise, if you want to get source PHP file , this is the same as the .txt file:

$Vdata = file_get_contents("path/to/YOUR/FILE.php");

In theory you could just use fopen and then use stream_get_contents.

$stream = fopen("file.php","r"); $string = stream_get_contents($stream); fclose($stream);

If you are using http:// as suggested by eyel, you will only be able to read the output of the PHP script. You can only read PHP script, if it's on the same server as your script. Then you can use something like

$Vdata = file_get_contents("/path/to/your/file.php");

Here's how I do it (there are many ways):

  1. Converting data to JSON
  2. Call AJAX to receive the file JSON
  3. Conversion JSON to object Javascript

STEP 1

connect_error) ( die("Connection failed: " . $conn->connect_error); ) $sql = "SELECT id, name ,image FROM phone";

$result = $conn->query($sql);

Function showUser(fnc) ( var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() ( if (this.readyState == 4 && this.status == 200) ( // STEP 3 var p=JSON.parse( this.responseText);) ) )

Before attempting to work with a file, it is advisable to ensure that it exists. To solve this problem, two functions are usually used:

file_exists() and is_file().

The file_exists() function checks whether a given file exists. If the file exists, the function returns TRUE, otherwise it returns FALSE. The file_exists() function syntax is:

bool file_exists(string file)

An example of checking the existence of a file:

if (!file_exists($filename)) :

print "File $filename does not exist!";

is_file()

The is_file() function checks the existence of a given file and whether it can be read/written. Essentially, is_file() is a more robust version of file_exists() that checks not only whether a file exists, but also whether it can read and write data:

bool is_file(string file)

The following example shows how to verify that a file exists and that operations can be performed on it:

$file = "somefile.txt";

if (is_file($file)) :

print "The file $file is valid and exists!";

print "The file $file does not exist or it is not a valid file!";

After making sure that required file exists and you can perform various read/write operations with it, you can proceed to the next step - opening the file.

The filesize() function returns the size (in bytes) of the file with the given name, or FALSE on error. Filesize() function syntax:

int filesize(string filename)

Let's say you want to determine the size of the pastry.txt file. For getting necessary information you can use the filesize() function:

$fs = filesize("pastry.txt"); print "Pastry.txt is $fs bytes.";

The following result is displayed:

Pastry.txt is 179 bytes.

Before you can perform operations on a file, you must open it and associate it with a file handler, and after you are done working with the file, you must close it. These topics are covered in the next section.

Opening and closing files

Before you can perform I/O on a file, you must open it using fopen().

The fopen() function opens a file (if it exists) and returns an integer -- called file manipulator(file handle). fopen() function syntax:

int fopen (string file, string mode [, int enable_path])

The file being opened can be on the local file system, exist as a standard input/output stream, or represent a file on a remote system accepted via HTTP or FTP.

The file parameter can be specified in several forms, listed below:

If the parameter contains the name of a local file, fopen() opens that file and returns a handle.

If the parameter is specified as php://stdin, php://stdout, or php://stderr, the corresponding standard input/output stream is opened.

If the parameter begins with the http:// prefix, the function opens an HTTP connection to the server and returns a handle for the specified file.

If the parameter begins with the ftp:// prefix, the function opens an FTP connection to the server and returns a handle for the specified file. There are two things to pay special attention to in this case: If the server does not support passive FTP mode, the fopen() call will fail. Moreover, FTP files are opened either for reading or writing.

When operating in passive mode, the YAR server waits for connections from clients. When operating in active mode, the server itself establishes a connection with the client. The default is usually active mode.

The mode parameter determines the ability to read and write to the file. In table 7.1 lists some values ​​that determine the file opening mode.

Table 7.1. File opening modes

Mode Description
Only reading. The current position pointer is set to the beginning of the file
r+ Read and write. The current position pointer is set to the beginning of the file
w Recording only. The current position pointer is set to the beginning of the file, and the entire contents of the file are destroyed. If the file does not exist, the function tries to create it
w+ Read and write. The current position pointer is set to the beginning of the file, and the entire contents of the file are destroyed. If the file does not exist, the function tries to create it
a Recording only. The current position pointer is set to the end of the file. If the file does not exist, the function tries to create it
a+ Read and write. The current position pointer is set to the end of the file. If the file does not exist, the function tries to create it

If the optional third parameter include_path is 1, then the file path is relative to the include directory specified in the php.ini file (see Chapter 1).

Below is an example of opening a file using the fopen() function. The die() call, used in combination with fopen(), provides an error message if the file cannot be opened:

$file = "userdata.txt"; // Some file

$fh = fopen($file, "a+") or die("File ($file) does not exist!");

The following snippet opens a connection to the PHP site (http://www.php.net):

$site = "http://www.php.net": // Server accessible via HTTP

$sh = fopen($site., "r"); //Associate the manipulator with the Php.net index page

After finishing work, the file should always be closed using fclose().

The fclose() function closes a file with the given manipulator. If closing is successful, TRUE is returned; if closing is unsuccessful, FALSE is returned. fclose() function syntax:

int fclose(int manipulator)

The fclose() function successfully closes only those files that were previously opened by the fopen() or fsockopen() functions. Example of closing a file:

$file = "userdata.txt";

if (file_exists($file)) :

$fh = fopen($file, "r");

// Perform file operations

print "File Sfile does not exist!";

Write to file

There are two main operations performed on open files: reading and writing.

The is_writeable() function verifies that a file exists and is writeable. Writeability is checked for both the file and the directory. The is_writeable() function syntax is:

bool is_writeable (string file)

One important thing to note is that PHP will most likely run under the user ID used by the web server (usually "nobody"). An example of using is_writeable() is given in the description of the fwrite() function.

The fwrite() function writes the contents of a string variable to the file specified by the file handler. fwrite() function syntax:

int fwrite(int manipulator, string variable [, int length])

If the optional length parameter is passed when calling the function, writing stops either after writing the specified number of characters or when the end of the line is reached. Checking whether a file can be written to is demonstrated in the following example:

// Information about traffic on the user site

$data = "08:13:00|12:37:12|208.247.106.187|Win98";

$filename = "somefile.txt";

// If the file exists and can be written to

if (is_writeable($filename)) :

$fh = fopen($filename, "a+");

// Write the contents of $data to a file

$ success - fwrite($fh, $data);

// Close file

fclose($fh); else:

print "Could not open Sfilename for writing";

The fputs() function is an alias to fwrite() and can be used anywhere fwrite() is used.

The fputs() function is an alias to fwrite() and has exactly the same syntax. fputs() function syntax:

int fputs(int manipulator, string variable [, int length])

Personally I prefer to use fputs(). It should be remembered that this is just a matter of style and has nothing to do with any differences between the two functions.

Reading from a file

Undoubtedly, reading is the most important operation performed on files. Below are some features that make reading from a file more efficient. The syntax of these functions almost exactly copies the syntax of similar recording functions.

The i s_readable() function allows you to verify that the file exists and is readable. Readability is checked for both the file and the directory. The is_readable() function syntax is:

boo! is_readable(string file]

Most likely, PHP will run under the user ID used by the web server (usually "nobody"), so for the is_readable() function to return TRUE, the file must be allowed to be read by everyone. The following example shows how to verify that a file exists and is readable:

if (is_readable($filename)) :

// Open the file and set the current position pointer to the end of the file

$fh = fopen($filename, "r");

print "$filename is not readable!";

The fread() function reads the specified number of bytes from a file specified by the file manipulator. fwrite() function syntax:

int fread(int manipulator, int length)

The manipulator must refer to an open file that is readable (see the description of the is_readable() function). Reading stops after a specified number of bytes have been read or when the end of the file is reached. Consider the text file pastry.txt shown in Listing 7.1. Reading and output of this file in the browser is carried out by the following fragment:

$fh = fopen("pastry.txt", "r") or die("Can"t open file!");

$file = fread($fh, filesize($fh));

By using the fllesize() function to determine the size of pastry.txt in bytes, you ensure that the fread() function reads the entire contents of the file.

Listing 7.1. Text file pastry.txt

Recipe: Pastry Dough

1 1/4 cups all-purpose flour

3/4 stick (6 tablespoons) unsalted butter, chopped

2 tablespoons vegetable shortening 1/4 teaspoon salt

3 tablespoons water

The fgetc() function returns a string containing one character from the file at the current pointer position, or FALSE when the end of the file is reached. fgetc() function syntax:

string fgetc (int manipulator)

The manipulator must reference an open file that is readable (see the description of the is_readable() function earlier in this chapter). The following example demonstrates character-by-character reading and output of a file using the fgetc() function:

$fh = fopen("pastry.txt", "r"); while (!feof($fh)) :

$char = fgetc($fh):

print $char; endwhile;

The fgets() function returns a string read from the current pointer position in the file specified by the file handler. The file pointer must point to an open file that is readable (see the description of the is_readable() function earlier in this chapter). fgets() function syntax:

string fgets (int manipulator, int length)

Reading stops when one of the following conditions is met:

  • read from file length -- 1 byte;
  • a character was read from a file new line(included in the returned string);
  • The end of file (EOF) flag has been read from the file.

If you want to organize line-by-line reading of a file, pass in the second parameter a value that is obviously greater than the number of bytes in the line. Example of line-by-line reading and output of a file:

$fh = fopen("pastry.txt", "r");

while (!feof($fh));

$line = fgets($fh, 4096);

print $line. "
";

The fgetss() function is completely similar to fgets() with one exception - it attempts to remove all HTML tags and PHP:

string fgetss (Int manipulator, int length [, string allowed_tags])

Before moving on to the examples, review the contents of Listing 7.2—this file is used in Listings 7.3 and 7.4.

Listing 7.2. File science.html

Breaking News - Science

Alien lifeform discovered


August 20. 2000

Early this morning, a strange new form of fungus was found growing in the closet of W. J. Gilmore's old apartment refrigerator. It is not known if powerful radiation emanating from the tenant's computer monitor aided in this evolution.

Listing 7.3. Removing tags from an HTML file before displaying in the browser

$fh = fopen("science.html", "r");

while (!feof($fh)) :

print fgetss($fh, 2048);

The result is shown below. As you can see, all HTML tags have been removed from the science.html file, causing formatting to be lost:

In some situations, all but a few tags are removed from a file - for example, line break tags
. Listing 7.4 shows how this is done.

Listing 7.4. Selectively removing tags from an HTML file

$fh = fopenC"science.html", "r");

$allowable = "
";

while (!feof($fh)) :

print fgetss($fh. 2048, $allowable);

Result:

Breaking News - Science Alien lifeform discovered August 20. 2000 Early this morning, a strange new form of fungus was found growing in the closet of W. J. Gilmore's old apartment refrigerator. It is not known if powerful radiation emanating from the tenant's computer monitor aided in this evolution.

As you can see, the fgetss() function makes it easy to convert files, especially if you have a large number of HTML files, formatted in a similar way.

Reading a file into an array

The file() function loads the entire contents of a file into an indexable array. Each element of the array corresponds to one line of the file. File() function syntax:

array file (string file [, int include_path])

If the optional third parameter include_path is 1, then the file path is relative to the include directory specified in the php.ini file (see Chapter 1). Listing 7.5 uses the file() function to load the pastry.txt file (see Listing 7.1).

$file_array = file("pastry.txt");

while (list($line_num. $line) = eacht($file_array)):

print " Line $line_num:", htmlspecialchars($line), "
\n"

Each row of the array is printed along with a number:

Line 0: Recipe: Pastry Dough

Line 1: 1 1/4 cups all-purpose flour

Line 2: 3/4 stick (6 tablespoons) unsalted butter, chopped

Line 3: 2 tablespoons vegetable shortening

Line 4: 1/4 teaspoon salt

Line 5: 3 tablespoons water

Redirecting a file to standard output

The readfile() function reads the contents of a file and writes it to standard output (in most cases, to the browser). readfile() function syntax:

int readfile (string file [, int include_path])

The function returns the number of bytes read. The file can reside on the local file system, exist as standard input/output, or represent the file on a remote system accepted via HTTP or FTP. The file parameter is set according to the same rules as in the fopen() function.

Let's say you have a file latorre.txt, the contents of which you want to display in the browser:

Restaurant "La Torre." located in Nettuno, Italy, offers an eclectic blend of style. history, and fine seafood cuisine. Within the walls of the medieval borgo surrounding the city, one can dine while watching the passersby shop in the village boutiques. Comfort coupled with only the freshest seafare make La Torre one of Italy's finest restaurants.

When the following snippet is executed, the entire contents of latorre.txt are sent to standard output:

$restaurant_file = "latorre.txt";

// Send the entire file to standard output

readfile($restaurant_file);

Opening a process file handler

Along with regular files, you can open file manipulators to interact with processes on the server. The problem is solved by the popen() function, which has the following syntax:

int popen (string command, string mode)

The command parameter specifies the system command to be executed, and the mode parameter describes the access mode:

// Open the file "spices.txt" for writing

$fh = fopen("spices.txt","w");

// Add some lines of text

fputs($fh, "Parsley, sage, rosemary\n");

fputs($fh, "Paprika, salt, pepper\n");

fputs($fh, "Basil, sage, ginger\n");

// Close the manipulator

// Open a UNIX grep process to search for the word Basil in the spices.txt file

$fh - popen("grep Basil< spices.txt", "r");

// Print the result of grep

The result looks like this:

Basil, sage, ginger

The fpassthru() function is similar to the passthru() function discussed in the “Running External Programs” section of this chapter.

After completing all operations, the file or process must be closed. The pclose() function closes the connection to the process specified by the manipulator, similar to the way the fclose() function closes a file opened by the fopen() function. pclose() function syntax:

int pclose (int manipulator)

In the parameter manipulator the manipulator received earlier with a successful call to popen() is transmitted.

Opening a socket connection

PHP isn't limited to interacting with files and processes—you can also make connections via sockets. Socket A socket is a software abstraction that allows you to communicate with various services on another computer.

The fsockopen() function establishes a socket connection to a server on the Internet

via TCP or UDP protocol. fsockopen() function syntax:

int fsockopen (string node, int port [, int error_code [, string error_text [, int timeout]]])

The optional parameters error_code and error_text contain information that will be displayed if the connection to the server fails. Both parameters must be passed by reference. The third optional parameter, timeout, specifies the length of time to wait for a response from the server (in seconds). Listing 7.6 demonstrates using the fsockopen() function to obtain server information. However, before looking at Listing 7.6, there is one more function that you need to become familiar with: socket_set_blocking().

UDP (User Datagram Protocol) is a connectionless communication protocol.

socket_set_blocking()

The socket_set_b1ocki ng() function allows you to set timeout control for server operations:

socket_set_blocking(int manipulator, boolean mode)

The manipulator parameter specifies the previously opened socket, and the mode parameter selects the mode the socket is switched to (TRUE for blocking mode, FALSE for non-blocking mode). An example of using the fsockopen() and socket_set_blocking() functions is shown in Listing 7.6.

Listing 7.6. Using fsockopen() to get server information

function getthehost($host.$path) (

// Open connection to node

$fp - fsockopen($host, 80, &$errno, &$errstr, 30);

// Go to blocking mode

socket_set_blocking($fp, 1),

// Send headers

fputs($fp,"GET $path HTTP/1.1\r\n");

fputs($fp, "Host: $host\r\n\r\n"); $x = 1;

// Get headers

while($x< 10) :

$headers = fgets($fp, 4096);

// Close the manipulator

getthehost("www. apress.com", "/");

Running Listing 7.6 produces the following output:

HTTP/1.1 200 OK Server: Microsoft-IIS/4.0 Content-location:

2000 20:25:06 GMT ETag: "f0a61666dbff1bf1:34a5" Content-Length: 1311

The pfsockopen() function is a persistent version of fsockopen(). This means that the connection will not be automatically closed when the script in which the function was called ends. The pfsockopen() function syntax is:

int pfsockopen (string node, int port [, int error_code [, string error_text [, int timeout]]])

Depending on the specific goals of your application, you may find it more convenient to use pfsockopen() instead of fsockopen().

Launching external programs

PHP scripts can also execute programs located on the server. This feature is especially often used when administering the system via a web browser, as well as for more conveniently obtaining summary information about the system.

The exec() function runs given program and returns the last line of its output. Syntax of the exec() function:

string exec (string command [, string array [, int return]])

Please note that the exec() function only executes the command and does not print its results. All command output can be stored in an optional array parameter. Additionally, if a return variable is also specified when the array parameter is specified, the latter is assigned the return code of the executed command.

Listing 7.7 shows how to use the exec() function to execute the UNIX ping system function.

Listing 7.7. Checking connection with the server using the exec() function

exec("ping -from 5 www.php.net", $ping);

// On Windows - exec("ping -n 5 www.php.net. $ping);

for ($i=0; $i< count($ping);$i++) :

print "
$ping[$i]";

Result:

PING www.php.net (208.247.106.187): 56 data bytes

64 bytes from 208.247.106.187: icmp_seq=0 ttl=243 time=66.602 ms

64 bytes from 208.247.106.187: icmp_seq=1 ttl=243 time=55.723 ms

64 bytes from 208.247.106.187: icmp_seq=2 ttl=243 time=70.779 ms

64 bytes from 208.247.106.187: icmp_seq=3 ttl=243 time=55.339 ms

64 bytes from 208.247.106.187: icmp_seq=4 ttl=243 time=69.865 ms

www.php.net ping statistics --

5 packets transmitted. 5 packets received. 0% packet loss

round-trip min/avg/max/stddev - 55.339/63.662/70.779/6.783 ms

Back apostrophes

There is another way to execute system commands that does not require calling functions - the command being executed is enclosed in backticks (` `), and the results of its operation are displayed in the browser. Example:

print "

$output
";

This snippet displays the contents of the directory where the script is located in the browser.

Internal ping parameter -c 5 (-p 5 in Windows system) specifies the number of server polls.

If you just want to return the unformatted results of a command, use the passthru() function described below.

The passthru() function works much the same as exec(), with one exception - it automatically prints the results of the command. Passthru() function syntax:

void passthru(string command [, int return])

If an optional return parameter is passed when calling passthru(), this variable is set to the return code of the executed command.

escapeshellcmd()

The escapeshellcmd() function escapes any potentially dangerous characters that might be entered by the user (for example, HTML form), to execute the exec(), passthru(), system(), or popen() commands. Syntax:

string escapeshellcmd (string command)

User input should always be treated with some caution, but even so, users can enter commands that will be executed by system command functions. Consider the following snippet:

$user_input = `rm -rf *`; // Delete the parent directory and all its subdirectories

exec($user_input); // Execute $user_input !!!

If no precautions are taken, such a command will lead to disaster. However, you can use the escapeshellcmd() functions to escape user input:

$user_input = `rm - rf *`; // Delete the parent directory and all its subdirectories

ex(escapeshellcmd($user_input)); // Escape dangerous characters

The escapeshellcmd() function escapes the * character, preventing the command from having catastrophic consequences.

Security is one of the most important aspects of Web programming, so I devoted an entire chapter to this topic and how it relates to PHP programming. See Chapter 16 for more information.

Working with the file system

PHP has functions for viewing and performing various operations on files on the server. Information about server file attributes (location, owner, and privileges) is often useful.

The basename() function extracts the file name from the passed full name. Basename() function syntax:

string basename(string full_name)

Extracting the base file name from the full name is done as follows:

$path = "/usr/local/phppower/htdocs/index.php"; $file = basename($path); // $file = "index.php"

In effect, this function removes the path from the full name and leaves only the file name.

The getlastmod() function returns the date and time of the last modification of the page from which the function is called. getlastmod() function syntax:

int getlastmod(void)

The return value follows the UNIX date/time format, and you can use the date() function to format it. The following snippet displays the date the page was last modified:

echo "Last modified: ".date("H:i:s a". getlastmod());

The stat() function returns an indexable array with detailed information about the file with the given name:

array stat(string filename)

The following information is returned in the array elements:

0 Device

2 Index node protection mode

3 Number of links

4 Owner user ID

5 Owner group ID

6 Index node device type

7 Size in bytes

8 Time of last call

9 Time of last modification

10 Last modified time

11 Block size for file system I/O

12 Number of allocated blocks

Thus, if you want to know the last time a file was accessed, look at element 8 of the returned array. Let's look at an example:

$file - "datafile.txt";

list($dev, $inode, $inodep, $nlink, $uid, $gid, $inodev, $size, $atime, $mtime, $ctime,

$bsize) = stat($file);

print "$file is $size bytes.
";

print "Last access time: $atime
";

print "Last modification time: $mtime
";

Result:

popen.php is 289 bytes.

Last access time: August 15 2000 12:00:00

Last modification time: August 15 2000 10:07:18

In this example, I used the list() construct to assign names to each return value. Of course, you can just as easily return an array, loop through the elements and display all the necessary information. As you can see, the stat() function allows you to get various useful information about a file.

Displaying and changing file characteristics

Each file on UNIX family systems has three important characteristics:

  • belonging to a group;
  • owner;
  • permissions.

All these characteristics can be changed using the appropriate PHP functions. The features described in this section do not work on Windows family systems.

If you do not have experience with UNIX operating systems, information about the characteristics of the UNIX file system can be found at http://sunsite.auc.dk/linux-newbie/FAQ2.htm. The topics of group membership, ownership, and permissions are discussed in Section 3.2.6.

The chgrp() function attempts to change the group to which a given file belongs. chgrp() function syntax:

int chgrp (string filename, mixed group)

The filegroup() function returns the group ID of the owner of the file with the given name, or FALSE on error. Filegroup() function syntax:

int filegroup (string filename)

The chmod() function changes the permissions of a file with the given name. chmod() function syntax:

int chmod (string filename, int permissions)

Permissions are specified in octal notation. The specifics of setting a parameter to the chmod() function are demonstrated in the following example:

chmod("data_file.txt", g+r); // Doesn't work

chmod("data_file.txt", 766); // Does not work

chmod("data_file.txt", 0766); // Works

The fileperms() function returns the permissions of the file with the given name, or FALSE on error. Fileperms() function syntax:

int fileperms (string filename)

The chown() function attempts to change the owner of a file. The right to change the owner of a file is limited to the privileged user. chown() function syntax:

int chown (string filename, mixed user)

The fileowner() function returns the user ID for the owner of the file with the given name. Fileowner() function syntax:

int fileowner (string filename)

Copying and renaming files

Among other useful system functions Activities that can be performed in PHP scripts include copying and renaming files on the server. These operations are performed by two functions: copy() and rename().

Copying a file in a PHP script is no more difficult than using UNIX commands Wed The problem is solved by the PHP function copy(). The syntax of the soru() function is:

int copy (string source, string destination)

The function copy() tries to copy the source file to the destination file; returns TRUE on success, FALSE on failure. If the destination file does not exist, the copy() function creates it. The following example shows how to create a backup copy of a file using the copy() function:

$data_file = "data.txt";

copy($data_file. $data_file".bak") or die("Could not copy $data_file");

The rename() function renames a file. If successful, TRUE is returned, and if unsuccessful, FALSE is returned. Rename() function syntax:

bool rename (string old_name, string new_name)

An example of renaming a file using the rename() function:

$data_file = "data.txt";

rename($data file, $datafile".old") or die("Could not rename $data file");

Deleting files

The unlink() function deletes a file with the given name. Syntax:

int unlink (string file)

If you are working with PHP on a Windows system, you may sometimes experience problems using this feature. In this case, you can use the system() function described above and delete the file with the DOS del command:

system("del filename.txt");

Working with catalogs

PHP functions allow you to view and navigate the contents of directories. Listing 7.8 shows a typical directory structure on a UNIX system.

Listing 7.8. Typical directory structure

The dirname() function complements basename() - it extracts the path from the fully qualified file name. The syntax of the dirname() function is:

string dirname (string path)

An example of using dirname() to extract a path from a full name:

$path = "/usr/locla/phppower/htdocs/index.php";

$file = dirname($path); // $file = "usr/local/phppower/htdocs"

The dirname() function is sometimes used in conjunction with the $SCRIPT_FILENAME variable to obtain the full path to the script from which the command is executed:

$dir - dirname($SCRIPT_FILENAME);

The is_dir() function checks whether a file with a given name is a directory:

bool is_dir (string filename)

The following example uses the directory structure from Listing 7.8:

$ isdir = is_dir("index.html"); // Returns FALSE

$isdir = is_dir("book"); // Returns TRUE

The mkdir() function does the same thing as the UNIX command of the same name - it creates a new directory. mkdir() function syntax:

int mkdir (string path, int mode)

The path parameter specifies the path to create the new directory. Don't forget to end the parameter with the name of the new directory! The mode parameter determines the permissions assigned to the created directory.

Just as the fopen() function opens a manipulator to work with a given file, the opendir() function opens a manipulator to work with a directory. The syntax of the opendir() function is:

int opendir (string path)

The closedir() function closes the directory handle passed as a parameter. The closedir() function syntax is:

void closedir(int directory_manipulator)

The readdir() function returns the next element of the specified directory. Syntax:

string readdir(int directory_manipulator)

Using this function, you can easily list all files and subdirectories located in the current directory:

$dh = opendir(" .);

while ($file = readdir($dh)) :

print "$file
"; endwhile;

The chdir() function works just like the UNIX cd command; it changes to the directory specified by the parameter. chdir() function syntax:

int chdir (string directory)

In the following example, we navigate to the book/ subdirectory and print its contents:

$newdir = "book";

chdir($newdir) or die("Could not change to directory ($newdir)"); $dh = opendir(" . ");

while ($file = readdir($dh)) ;

print "$file
";

The rewlnddir() function moves the current position pointer to the beginning of the directory opened by the opendir() function. The rewinddir() function syntax is:

void rewinddir (int directory_manipulator)

Project 1: Simple hit counter

The script presented in this section counts the number of hits to the page it is on. Before moving on to the code in Listing 7.9, review the algorithm written in pseudocode:

  1. Assign the $access variable the name of the file in which the counter value will be stored.
  2. Use the file() function to read the contents of $access into the $visits array. The @ prefix before the function name suppresses possible errors (for example, there is no file with the given name).
  3. Set the $current_visitors variable to the value of the first (and only) element of the $visits array.
  4. Increase $current_visitors value by 1.
  5. Open the $access file for writing and set the current position pointer to the beginning of the file.
  6. Write the $current_visitors value to the $access file.
  7. Close the manipulator that references the $access file.

Listing 7.9. Simple hit counter

// Script: simple hit counter

// Purpose: saving the number of hits in a file

$access = "hits.txt"; // The file name is chosen arbitrarily

$current_visitors = $visits; // Retrieve the first (and only) element

+$current_visitors; // Increase the hit counter

$fh = fopen($access. "w"); // Open the hits.txt file and install

// pointer to the current position at the beginning of the file

@fwrite($fh, $current_visitors);// Write a new counter value

// to the file "hits.txt"

fclose($fh); // Close the file manipulator "hits.txt"

Project 2: building a site map

The script in Listing 7.10 builds a sitemap -- hierarchical image all folders and files on the server, starting from the specified directory. Calculating the padding of the elements that make up a sitemap uses the functions defined in this and previous chapters. Before moving on to the program, review the algorithm written in pseudocode:

  1. Declare service variables to store the parent directory, the name of the graphic file with the image of the folder, the page name and the server OS flag (Windows or another system).
  2. Declare a display_directory() function that reads the contents of a directory and formats it for display in the browser.
  3. Construct the directory path by combining the name passed in the $dir1 variable with $dir.
  4. Open a directory and read its contents. Format directory and file names and display them in the browser.
  5. If the current file is a directory, call display_di rectory() recursively and pass it the name of the new directory to display. Calculate the indentation used when formatting the output.

If the file is not a directory, it is formatted to display as a hyperlink (and the indentation used in formatting is also calculated).

Listing 7.10. Sitemap.php program

// File: sitemap.php

// Purpose: building a site map

// Directory from which map construction begins

$beg_path = "C:\Program FilesVApache Group\Apache\htdocs\phprecipes";

// File with a graphic image of the folder.

// The path must be Relative* to the root directory of the Apache server

$folder_location = "C:\My Documents\PHP for Programmers\FINAL CHPS\graphics\folder.gif";

// Text in the window title $page_name = "PHPRecipes SiteMap";

// On which system will the script be used - Linux or Windows?

// (0 - Windows; 1 - Linux)

$usingjinux = 0;

// Function: display_directory

// Purpose: reading the contents of the directory specified by the parameter

// $dir1, followed by formatting of the directory and file hierarchy.

// The function can be called recursively.

function display_directory ($dir1, $folder_location, $using_linux, $init_depth) (

// Update path

Sdh = opendir($dir);

while($file = readdir($dh)) :

// Directory elements "." and ".." are not displayed.

if (($file != ".") && ($file != "..")) :

if ($using_linux == 0) :

$depth = explode("\\", $dir): else:

$depth = explode("/", $dir); endif ; $curtent_depth = sizeof($depth);

// Build the path according to the rules of the operating system used. if ($using_linux == 0) :

$tab_depth = $current_deptn - $init_depth;

$file = $dir. "\\", $file; else:

$file = $dir. "/",$file; endif;

// Does $file contain a directory? if (is dir($file)) :

// Calculate indentation

while ($x< ($tab_depth * 2)) :

$x++; endwhile;

print "

".basename($file)."
";

// Increment counter

// Recursive call to display_directory() function

display_directory($file, $folder_location, $using_linux, $init_depth);

// Not a directory

// Build a path according to the rules of the used

// operating system.

if ($using_linux == 0) :

$tab_depth = ($current_depth - $init_depth) - 2; $x = 0;

// Calculate indentation

while ($x< (($tab_depth * 2) + 5)) :

print " ".basename($file)."
";

print " ".basename($file)."
";

endif; // Is_dir(file) endif: // If ! "." or ".."

// Close the directory closedir($dh);

<? print "$page_name"; ?>

// Calculate initial padding

if ($using_linux == 0) :

$depth = explode("\\", $beg_path);

$depth = explode("/", $beg_path);

$init_depth = sizeof($depth);

display_directory($beg_path, $folder_location, $using_linux, $init_depth);

In Fig. Figure 7.1 shows the result of running the script for a directory with several chapters of this book.

Rice. 7.1. Displaying the directory structure on the server using the sitemap.php script

Results

This chapter introduced many of PHP's tools for working with files. In particular, we considered the following issues:

  • checking the existence of files;
  • opening and closing files and I/O streams;
  • writing to and reading from a file;
  • redirecting the file to the output stream;
  • launching external programs;
  • file system operations.

The material in this chapter sets the stage for the next chapter, “Strings and Regular Expressions,” because when developing web applications, string processing and I/O operations are very closely related.

Every programmer should be able to work with files correctly. This article is aimed at beginner PHP programmers, but the “collection of recipes” will also be useful for advanced users.

Working with files is divided into 3 stages:

  1. Opening a file.
  2. Data manipulation.
  3. Closing the file.

I. Opening a file

To open a file in the PHP environment, use the function fopen(). The required parameters for this function are the file name and file mode.

$fp = fopen("counter.txt", "r");

According to the PHP documentation, the following types of file modes are distinguished:

  1. r – open the file for read-only.
  2. r+ - opens a file for reading and writing at the same time.
  3. w – creates a new empty file. If such a file already exists at the time of the call, it is destroyed.
  4. w+ - similar to r+, only if such a file exists at the time of calling, its contents are deleted.
  5. a – opens an existing file in write mode, with the pointer shifted to the last byte of the file (to the end of the file).
  6. a+ - opens a file in read-write mode, with the pointer shifted to the last byte of the file (to the end of the file). The contents of the file are not deleted.

Note: There may be one more optional parameter at the end of any of the lines: b or t . If b is specified, the file is opened in binary read/write mode. If t, then the line feed translation mode is set for the file, i.e. it is perceived as textual.

To demonstrate, consider the following scenario:

//Opens a file in different modes
$fp = fopen("counter.txt", "r"); // Binary mode
$fp = fopen("counter.txt", "rt"); // Text mode
$fp = fopen("http://www.yandex.ru", "r");// Opens an HTTP connection for reading
$fp = fopen("ftp://user: [email protected]", "w"); //Open an FTP connection indicating the login and password
?>

II. File Data Manipulation

You can write data to a file using PHP using the function fwrite(). This function takes 2 required parameters and 1 optional one. The required parameters are the file descriptor and the file mode:

$fp = fopen("counter.txt", "a"); // Open the file in write mode
$mytext = "We need to write this line\r\n"; // Source string
$test = fwrite($fp, $mytext); // Write to file
if ($test) echo "The data was successfully entered into the file.";
else echo "Error writing to file.";
fclose($fp); //Close the file
?>

To read a file line by line, use the function fgets(). The function takes 2 required parameters:


if ($fp)
{
while (!feof($fp))
{
$mytext = fgets($fp, 999);
echo $mytext."
";
}
}

fclose($fp);
?>

Note: In this example, the value 999 specifies the number of characters that will be read until the pointer reaches the end of file (EOF).

In order to read the file as a single whole, you need to use the function readfile(), which takes 1 required parameter. The function opens a file, displays its contents in a browser window, and then closes the file:

echoreadfile("counter.txt");
?>

You can also use the fpassthru() function which takes 1 required parameter. Before using this feature, you must open the file in Read mode. When the file is finished reading, the function automatically closes the file (and the file descriptor becomes invalid).

$fp = fopen("counter.txt", "r"); // Open the file in read mode
if ($fp) echo fpassthru($fp);
elseecho "Error opening file";
?>

Very often there are situations when it is necessary to read the contents of a site into an array. This feature involves using the function file(). When this function is called, each line of the file will be stored in a separate element of the specified array.

Note: The function should not be used file() to binary files (binary-safe), because It is not secure in terms of reading binary files, and if it encounters an end-of-file (EOF) character somewhere, it does not guarantee that you will read the entire binary file.

$file_array = file("counter.txt"); // Read the file into the $file_array
// Working with array data
?>

Note: Working with arrays is described in detail, authors: Mukhametshin D.F., Simdyanov I.V.

At the end of the article, you will find a good “cookbook” on arrays that provides solutions to many problems that a web programmer encounters every day.

Let's imagine a situation where a file needs to be read character by character. To do this we can use the function fgetc(). The function takes a single parameter. The function is useful if we need to find any character or the number of identical characters.

$fp = fopen("counter.txt", "r"); // Open the file in read mode
if ($fp)
{
while(!feof($fp))
{
$char = fgetc($fp);
if ($char == "c") $i = $i + 1;// Find the character "c"
}
echo "Number of 'c' letters in file: ". $i;
}
else echo "Error opening file";
?>

III. Closing a file

The file is closed using the function fclose(), which takes 1 required parameter.

$fp = fopen("counter.txt", "r");
if ($fp)
{
echo "The file is open";
fclose($fp); // Closing the file
}
?>

Collection of recipes

1) We need to check whether this or that file exists. To do this we will use the function file_exists().

myfile("counter.txt"); // Use the myfile function, passing the file name as an argument

function myfile($name) //Create a function to check the existence of a file
{
if (file_exists($name)) echo "The file exists";

}
?>

Note: Function file_exists does not check files on the remote web server. For the function to work correctly, the file with the script must be located on the same server as the file being checked.

2) Determine the file size using the function filesize()

myfile("counter.txt");

function myfile($name) //Create a function to check the existence of a file and determine the file size
{
if (file_exists($name)) echo "File size: ".filesize($name)." bytes";
else echo "File does not exist";
}
?>

3) Create a temporary file using the function tmpfile()

$myfile = tmpfile();
fwrite($myfile, "This line is written to a temporary file."); // Write to a temporary file
fseek($myfile, 0); // Set the file pointer
echo fread($myfile, 1024); // output the contents of the file
?>

4) You need to determine the number of lines in the file. To do this we use the function count()

$fp = file("counter.txt");
echo "Number of lines in file: ".count($fp);
?>

5) We need to use a file locking mechanism

$fp = fopen("counter.txt", "a");
flock($fp, LOCK_EX); // Lock the file for writing
fwrite($fp, "Line to write");
flock($fp, LOCK_UN); // Unlock
fclose($fp);
?>

6) We need to remove a certain line from the file

$num_stroka = 5; //Delete line 5 from the file
$file = file("counter.txt"); // Read the entire file into an array

for($i = 0; $i< sizeof($file); $i++)
if($i == $num_stroka) unset($file[$i]);

$fp = fopen("counter.txt", "w");
fputs($fp, implode("", $file));
fclose($fp);
?>

7) Determining the file type. Using the function

In PHP, you often have to deal with creating a file... it's very simple: there is no file on disk, the code was run and the file appeared, then you can read this file into another variable or even any page on the Internet and then write something there... but for this you need to know special functions... more about that in this article...

To create a file in PHP in an executable script, you just need to specify a few functions:

Let's take a look at an example:

$text = "Some text to write to the file";
$fp = fopen("file.txt", "w");
fwrite($fp, $text);
fclose($fp);
?>

Here you should know:

fopen()- the function opens the file for reading or writing and clarifications;

This clarification (the mode parameter of the fopen function) is very important:

  • "r" - open a file in php Only for reading. The cursor is placed at the beginning.
  • "r+" - open a file in php for reading and writing. The cursor is placed at the beginning. !!! - with these two modes r and r+, the files must already be created (otherwise an error will appear Warning: fopen(file.txt) : failed to open stream: No such file or directory in ...), and we only read or we have the opportunity to add.
  • "w" - the file is opened ONLY for writing. The file is truncated to zero length - that is, it is overwritten. What is needed is written and the Cursor is placed at the beginning.
  • "w+" - opens a file for writing AND READING! The rest is the same as in the "w" mode. !!! - in these two modes - if the file has not been created - AN ATTEMPT WILL BE MADE TO CREATE IT!
  • "a" - open the file ONLY for writing. Unlike "w", this option does not overwrite the contents of the file, but places the cursor at the end of the line and appends the content that we wanted to add to the end.
  • "a+" - open the file for writing and reading.

fwrite($fp, $text) - a function for writing to a file in PHP - that is, what is in the $text variable is written to a file that is in the $fp variable;

fclose($fp) - function for closing the file that we wrote to the $fp variable;

Now you can easily create files in php correctly, open them for reading and editing.

Useful PHP additions and functions for working with an open file:

while(!feof($fp))(
$mytext = fgets($fp, 99);
echo $mytext."
";
}

here the condition is met - “until the end of the file is reached, do this” while(!feof($fp))

1. Function fgets($fp, 99) - allows you to divide all content into sections of 99 bytes and further, to see this more clearly we place a tag

This string function fgets(resource handle [, int length]) by default accepts 1024 bytes (1 kilobyte) as the length parameter, if not specified it will be so. This parameter is optional as of PHP 4.2.0 (Returns FALSE in case of error)

Additional functions for opening, writing and creating a file

Function - int readfile(string filename [, bool use_include_path [, resource context]]) - read the file as a whole.

Reads a file and writes the contents to the output buffer. And returns the number of bytes output. In case of an error, it will return if the dog is not used - @readfile.

Something like this will happen:

At the end of the word there is a tag
.

b. Function - array file(string filename [, int use_include_path [, resource context]]), does the same as the readfile function, with one exception it adds the contents of the file to an array:

This way you can read any pages on the Internet: $lines = file("http://site/"); and iterate through the array using the foreach function;

3a. string function file_get_contents(string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] - allows you to get the contents as a single string.

This is a more universal PHP function for reading a file, similar to the file function, only the contents are returned as a string, not an array, and you can set conditions - which byte to start with - offset and where to end - maxlen. On failure, it will return FALSE.

Important!!!- in this case, the function replaces 3 at once: fopen(), fread() and fclose() and thus gets rid of the mark.

3b. int function file_put_contents(string filename, mixed data [, int flags [, resource context]]) - identical to sequential calls to the functions fopen(), fwrite() and fclose() - returns the number of bytes written.

Last update: 11/1/2015

Like most programming languages, PHP supports working with files, which are one of the ways to store information.

Reading and writing files

Opening and closing files

To open files in PHP, the fopen() function is defined. It has the following definition: resource fopen(string $filename, string $mode) . The first $filename parameter represents the path to the file, and the second is the opening mode. Depending on the purpose of opening and the type of file, this parameter can take the following values:

    "r" : The file is opened read-only. If the file does not exist, returns false

    "r+" : The file is opened read-only and writable. If the file does not exist, returns false

    "w" : The file is opened for writing. If such a file already exists, then it is overwritten, if not, then it is created.

    "w+" : The file is opened for writing and readable. If such a file already exists, then it is overwritten, if not, then it is created.

    "a" : The file is opened for writing. If such a file already exists, then the data is written to the end of the file, and the old data remains. If the file does not exist, it is created

    "a+" : The file is opened for reading and writing. If the file already exists, then the data is appended to the end of the file. If the file does not exist, it is created

The output of the fopen function will be a file descriptor. This handle is used for file operations and to close the file.

After finishing work, the file must be closed using the fclose() function, which takes a file descriptor as a parameter. For example, let's open and close a file:

$fd = fopen("form.php", "r") or die("could not open file"); fclose($fd);

The or die("error text") construct allows the script to stop running and display some error message if the fopen function was unable to open the file.

Reading a file

You can use several functions to read a file. For line-by-line reading, the fgets() function is used, which receives a file descriptor and returns one line read. Let's go through the entire file line by line:

Each time fgets() is called, PHP will place the pointer at the end of the line read. To track the end of a file, the feof() function is used, which returns true when the file is completed. And until the end of the file is reached, we can use the fgets() function.

Reading the entire file

In this case, we do not have to explicitly open the file, obtain a handle, and then close the file.

Block reading

You can also do a block-by-block read, that is, read a certain number of bytes from a file using the fread() function:

The fread() function takes two parameters: the file handle to read and the number of bytes to read. When a block is read, the pointer in the file moves to the end of that block. And also using the feof() function you can track the completion of a file.

Write a file

To write a file, use the fwrite() function, which writes the following line to the file:

Another fputs() function works similarly:

Working with the file pointer

When opening a file for reading or writing in "w" mode, the pointer in the file is placed at the beginning. When reading data, PHP moves the pointer in the file to the end of the block of data read. However, we can also manually manipulate the pointer in the file and set it to an arbitrary location. To do this you need to use the function fseek, which has the following formal definition:

Int fseek (resource $handle , int $offset [, int $whence = SEEK_SET ])

The $handle parameter represents a file handle. The $offset parameter is the offset in bytes relative to the beginning of the file from which reading/writing will begin. The third optional parameter specifies how the offset is set. It can take three values:

    SEEK_SET : default value, sets the offset in offset bytes relative to the beginning of the file

    SEEK_CUR : sets the offset in offset bytes relative to the beginning of the current position in the file

    SEEK_END : sets the offset to offset bytes from the end of the file

If the pointer is successfully installed, the fseek() function returns 0, and if the pointer is unsuccessful, it returns -1.

Example of using the function:

$fd = fopen("hello.txt", "w+") or die("could not open file"); $str = "Hello world!"; // line to write fwrite($fd, $str); // write the line to the beginning fseek($fd, 0); // place the file pointer at the beginning fwrite($fd, "Oink"); // write the line at the beginning fseek($fd, 0, SEEK_END); // place the pointer at the end fwrite($fd, $str); // write another line at the end fclose($fd);

Did you like the article? Share it