Php-mysql Course

First, it's important to know that if the PHP server runs on a Linux server, a folder must have minimum CHMOD access permissions of 0755 for PHP scripts to open a file.
To create or alter files, you normally need to set global access permissions of 0777.
If you use PHP server (WampServer, XAMPP) on Windows you don't need to set these CHMOD permissions

PHP has a set of functions that allow you to open a file, read it and/or write to it, and then close the file. The first of these, fopen(), is the most important. Before apply any of the other functions, you must open the file with "fopen()".
  - Syntax:
fopen('filename', mode)
"filename" contains the name of the file to be opened.
"mode" specifies the type of access to the file. It may be any of the following: - The internal pointer is like the cursor in a word processor: PHP starts reading or writing from wherever the pointer is positioned when you call fread() or fwrite().

Under Microsoft Windows, ASCII files and binary files are treated differently. When you open a binary file on Windows, specify "b" as the last character of the "mode". For example, "rb" for reading, "wb" for writing, "a+b" to read and add.


Closing a File

An open file consumes system resources. When a script has finished using a file, the script should close the file, freeing those resources.
At the end of a script, PHP automatically closes open files. However, it is recommended to close files more quickly, whenever possible.
To close a file, use fclose().
fclose(file_handle);
- "file_handle" is a handle to a file successfully opened by "fopen()".
  - Example:
<?php
$fo = fopen('files/test.txt', 'r');

// some code to be executed

fclose($fo);
?>

Creating a new file with fopen()

To create a new file with fopen(), set a name for the file, use this function with "x" (or "xb") mode, add some data with "fwrite()", than close the file.
Using the "x" (or "xb") mode, it makes sure you're not overwriting an existing file. But if you want to overwriting an existing file, you can use "w" (or "wb") mode.
PHP must have read and write permissions (CHMOD 0777) in the folder in which you want to create the file.
  - Example:
<?php
$filename = 'files/test.txt';
$str = 'Free PHP course and tutorials.'. PHP_EOL. 'Web site: https://coursesweb.net';

// opens the file with "xb" mode
if ($fo = fopen($filename, 'xb')) {
  // write the $str value
  fwrite($fo, $str);

  // close the file and output a message if success
  if (fclose($fo)) echo 'The file was created';
}
else echo 'Unable to create the file.';
?>
- PHP_EOL is a PHP constant that represents a new line on any operating system.
If you run this script in your browser, it should create a "test.txt" file in the "files" directory, with the content added in the $str variable, and displays: "The file was created." (This file will also be used in the next examples).

The changes to a file with read and write operations are saved only when you call fclose() or when the script comes to an end. Although PHP saves the file when the script ends all operations, you should always close the file explicitly, with "fclose()".

Reading a file with fread()

The fread() function reads a specified amount of data from a file.
  - Syntax:
fread(file_handle, size)
"file_handle" is a handle to a file successfully opened by "fopen()".
"size" is the number of bytes read.
  - Example:
<?php
// gets the first 50 bytes of a file into a string
$filename = 'files/test.txt';
if ($fo = fopen($filename, 'r')) {
  $str = fread($fo, 50);

  echo $str;

  fclose($fo);
}
else echo 'Unable to open the file.';
?>
If you want to read the whole file with "fread()", you need to use the "filesize()" to get and pass the whole file size.
  - Example:
<?php
// gets the first 50 bytes of a file into a string
$filename = 'files/test.txt';
if ($fo = fopen($filename, 'r')) {
  $str = fread($fo, filesize($filename));

  echo $str;

  fclose($fo);
}
else echo 'Unable to open the file.';
?>

If you want to get the whole content of a file into a string, use file_get_contents() as it has much better performance than "fread()".

Reading a File Line by Line

You can use the fgets(file_handle) function to read a single line from a file. It needs as parameter a "file-handle" returned by "fopen()".
  - Example:
<?php
// gets the first line of a file into a string
$filename = 'files/test.txt';
if ($fo = fopen($filename, 'r')) {
  $line = fgets($fo);

  echo $line;

  fclose($fo);
}
else echo 'Unable to open the file.';
?>

The "fgets()" function moves the file pointer to the next line, so, if it's combined with feof() it can reads the whole file line by line.
The feof() function determines whether the end of the file (EOF) has been reached.
  - Example:
<?php
$filename = 'files/test.txt';
if ($fo = fopen($filename, 'r')) {
  // output the content line by line
  while(!feof($fo)) {
    echo fgets($fo). '<br />';
  }

  fclose($fo);
}
else echo 'Unable to open the file.';
?>

Appending content with fopen()

To add new content at the end of a file (after the existing content), use fopen() with "a" (or "ab") mode.
If you want to read and append data, use "a+" (or "a+b") mode..
  - Example:
<?php
$filename = 'files/test.txt';
$new_data = PHP_EOL. 'File handling lesson.';

// opens the file with "ab" mode
if ($fo = fopen($filename, 'ab')) {
  // write the $new_data value
  fwrite($fo, $new_data);

  // close the file and output a message if success
  if (fclose($fo)) echo 'The new data was appended.';
}
else echo 'Unable to create the file.';

// outputs the whole file content
echo '<hr />'. file_get_contents($filename);
?>
Assuming that the "test.txt" is the same file created at the beginning of this lesson, this code will output:
The new data was appended.
Free PHP course and tutorials. Web site: https://coursesweb.net File handling lesson.

Moving the internal pointer

Reading and writing operations always start wherever the internal pointer happens to be.
PHP has two functions that help to move the internal pointer in the place you need:
- To get the current pointer position of the file, use ftell(file_handle) function.
- To move the pointer to the end of a file, use:
  - Example:
<?php
$filename = 'files/test.txt';

// opens the file
if ($fo = fopen($filename, 'r')) {
  $line = fgets($fo);          // read the first line

  // gets and outputs the position of the file pointer
  echo 'The pointer position after read the first line is: '. ftell($fo);

  rewind($fo);                // pointer moved back to beginning

  // move the internal pointer to 30 bytes from the beginning
  fseek($fo, 30, SEEK_SET);

  // outputs the next 10 characters
  echo '<br />'. fread($fo, 10);
  
  // outputs the new position of the file pointer
  echo '<br /> The new position of the file pointer is: '. ftell($fo);

  fclose($fo);
}
else echo 'Unable to open the file.';
?>
Assuming that the "test.txt" is the same file created at the beginning of this lesson, this code will output:
The pointer position after read the first line is: 32
Web site
The new position of the file pointer is: 40

• For other util functions for file handling, see the Using file_put_contents, file_get_contents, readfile and file() tutorial.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which meta tag provides a short description of the page?
<meta content="..."> <meta description="..."> <meta http-equiv="...">
<meta name="description" content="70-160 characters that describes the content of the page" />
Which CSS property is used to stop the wrapping effect of the "float"?
clear text-align position
#some_id {
  clear: both;
}
Click on the method which gets an array with all the elements in the document that have a specified tag name.
getElementsByName() getElementById() getElementsByTagName()
var divs = document.getElementsByTagName("div");
var nr_divs = divs.length;
alert(nr_divs);
Indicate the PHP function which returns the number of elements in array.
is_[) count() strlen()
$arr =[7, 8, "abc", 10);
$nri = count($arr);
echo $nri;        // 4
File Handling with fopen

Last accessed pages

  1. Get Lower, Higher, and Closest Number (5342)
  2. Simple Admin Login PHP Script (10894)
  3. jQuery parent, children and nth-child() (13826)
  4. Display UL bullets and OL numbers on the right side (8088)
  5. Convert BBCode to HTML and HTML to BBCode with JavaScript (9298)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (201)
  2. Read Excel file data in PHP - PhpExcelReader (66)
  3. The Mastery of Love (56)
  4. PHP Unzipper - Extract Zip, Rar Archives (51)
  5. Working with MySQL Database (34)
Chat
Chat or leave a message for the other users
Full screenInchide