PHP file Function : file_exists | fopen

Today’s topic will be the PHP file function. Using file(), a file is read into an array. A line from the file, complete with the newline character, is contained in each element of the array. Before that, we discussed PHP Cookies, PHP Operators, PHP Forms, and PHP Cookies. If you are unaware of these, take immediate action!

How do PHP file function work?

You can use the filesystem functions to access and modify the filesystem.

Simply put, a file is a computer’s resource for storing data.

Typically, files are used to store information like:

  • Program configuration options
  • simple information like contact names and phone numbers.
  • photographs, images, etc.

PHP File Formats Support

Numerous file formats are supported by PHP’s file functions, including:

  • File.txt
  • File.log
  • File.custom_extension i.e. file.xyz
  • File.csv
  • File.gif, file.jpg, etc
  • Comparing files to databases, which need additional software and expertise to manage DBMS systems, databases offer a permanent, cost-effective data storage solution for simple data.
  • In order to later retrieve and analyze simple data, such as server logs, you want to store it.
  • You want to save the program.ini file’s settings.

Configuration at Runtime

The settings in php.ini have an impact on how the filesystem functions behave.

Name Default  Description  Changeable
allow_url_fopen
“1”  
enables the use of URLs by functions of the fopen() type.PHP_INI_SYSTEM
allow_url_include“0”(available since PHP 5.2)PHP_INI_SYSTEM
user_agent
NULL
sets the user agent that PHP will use to send (available since PHP 4.3)PHP_INI_ALL
default_socket_timeout“60”Sets the socket-based streams’ default timeout, in seconds (available since PHP 4.3)PHP_INI_ALL
from“”When using ftp and HTTP wrappers, this specifies the email address to be used on unauthenticated FTP connections as well as in the From header for HTTP connections.PHP_INI_ALL
auto_detect_line_endings“O”PHP will check the data read by fgets() and file() to see if it uses Unix, MS-Dos, or Mac line-ending characters when the value is set to “1”. (available since PHP 4.3)PHP_INI_ALL
sys_temp_dir“”(available since PHP 5.5)PHP_INI_SYSTEM

PHP Filesystem – Functions

FunctionDescription
basename()returns the path’s filename component.
chgrp()makes a file group change
chmod()alterations tto he file mode
chown()alterations the file owner
clearstatcache()the file status cache is cleared
copy()duplicates a file
delete()Visit unlink ()
dirname()returns the path’s directory name component.
disk_free_space() gives the disk’s or filesystem’s free space.
disk_total_space()returns the size of a filesystem or disc in its entirety.
diskfreespace()Disk free space’s alias ()
fclose()closes a running file
feof()determines whether an open file has reached the “end-of-file” (EOF).
fflush()Buffer output is flushed to an open file.
fgetc()a single character from an open file is returned.
fgetcsv()returns a line from a CSV file that is open.
fgets()a line from an open file is returned.
fgetss()Discontinued as of PHP 7.3. returns a line from a file that is open with the HTML and PHP tags removed.
file()files are read into an array.
file_exists()determines whether a file or directory is present
file_get_contents()creates a string by reading a file.
file_put_contents()data is written to a file.
fileatime()returns a file’s most recent access time.
filectime()returns the file’s most recent change time.
filegroup()returns a file’s group ID.
fileinode()returns a file’s inode number.
filemtime()gives the file’s most recent modification time.
fileowner()returns the file’s user ID (owner).
fileperms()gives the file’s permissions back.
filesize()gives the file size back.
filetype()gives the file type back.
flock()opens or closes a file
fnmatch()checks the filename or string against the given pattern.
fopen()launches a file or URL
fpassthru()writes the outcome to the output buffer after reading until the end of the file at the current position.
fputcsv()writes a line in CSV format to an open file.
fputs()Fwrite’s alternate name ()
fread()reads a file that is open (binary-safe)
fscanf()parses input from an open file in accordance with the format specified.
fseek()search for in an open file
fstat()information about an open file is returned
ftell()returns the position in an open file at the moment.
ftruncate()limits the length of an open file to a certain value.
fwrite()writes to a file that is open (binary-safe)
glob()gives back an array of filenames or directories that match a given pattern.
is_dir()finds out whether a file is a directory.
is_executable()examines a file’s executability
is_file()examines a file to see if it is a regular file.
is_link()determines if a file is a link
is_readable()determines whether a file can be read.
is_writable()determines if a file is writable
is_writeable()substitute for is writable ()
lchgrp()the group ownership of a symbolic link is modified
lchown()alters the user who owns a symbolic link.
link()establishes a hard link
linkinfo()provides details about a hard link.
lstat()information about a file or symbolic link is returned.
mkdir()establishes a directory
move_uploaded_file()repositions a file that has been uploaded.
parse_ini_file()a configuration file is analysed
parse_ini_string()a configuration string is broken down.
pathinfo()information about a file path is returned
pclose()closes a pipe that popen opened ()
popen()unlocks a pipe
readfile()a file is read, then it is written to the output buffer.
readlink()returns the symbolic link’s target.
realpath()gives the absolute pathname back.
realpath_cache_get()realpath cache entries are returned
realpath_cache_size()Realpath cache size is returned.
rename()file or directory renaming
rewind()backs up a file pointer
rmdir()eliminates a vacant directory
set_file_buffer()Stream set write buffer’s alternate name (). the size of the write operation’s buffer for the specified file is set.
stat()returns data regarding a file.
symlink()makes a symbolic connection
tempnam()                               makes a special temporary file
tmpfile()makes a special temporary file
touch()sets a file’s access and modification times.
umask()alterations to file permissions
Unlink ()eliminates a file

PHP fwrite() Function

To write files, use the fwrite() function.

It has the syntax listed below.

<?php
fwrite($hero, $honda, $suzuki);
?>

HERE,

•      The PHP function for writing to files is “fwrite().”

•      “$hero” is the file pointer resource

•      “$honda” is the data to be written in the file.

•      “$bmw” is optional and can be used to specify the maximum file length.

PHP Fclose Function

It is utilized to close a PHP file that is open at the moment.

It has the syntax listed below.

<?php
fclose($honda); 
?>

HERE,

•      The PHP function “fclose()” is used to close an open file.

•      “$hero” is the file pointer resource.

Now let’s examine an example that generates the file my settings.txt.

The following functions will be used.

  • fopen()
  • fwrite()
  • fclose()

The aforementioned example is put into practice in the code found in “create my settings file.php.”

Open a File :

<?php 

$fm = fopen("my_settings.txt", 'x')

or

die("Failed to create file"); ?>

Closing a file :

<?php

fclose($sh);

?>

Create File :

?php 
$fm = fopen("project.txt", 'x') or die("Failed to create file"); 
$test = <<<_END 
localhost;root;pwd1234;my_database 

_END; 
fwrite($fm, $test) or die("Could not write to file"); 
fclose($fm); 
echo "File 'project.txt' written successfully";
?>    

Testing the code

Launch your browser and go to http://localhost/phptuts/create_project.php.

You will see the next page.

  OUTPUT
  File 'project.txt' written successfully

NOTE : You will receive an error message if your disc is full or if you do not have permission to write files.

Return to the previous page at http://localhost/php/file_function.php

What outcomes do you observe? | i.e given below.

PHP Fgets Function

PHP files are read line by line using the fgets function. Its basic syntax is as follows. fgets($honda); HERE,

The PHP function for reading file lines is “$fgets.

The file pointer resource is “$honda.”

Now let’s take a look at an example using the fopen and fgets functions to read my settings.txt file.

The aforementioned example is implemented in the reading my settings.php code below.

<?php
$fm = fopen("project.txt", 'r') or die("File does not exist or you lack permission to open it");
$line = fgets($fm);
echo $line; fclose($fm);
 ?>

HERE,

The “fopen” function provides the file’s pointer when called.

The “die()” function is used to indicate errors. There is a message display and script execution.

PHP Copy Function

To copy files, use the PHP copy function. Its basic syntax is as follows. copy ($file,$copied file); RIGHT HERE

The name and file path of the file to be copied are specified by “$file”.

The path and name of the copied file were specified by “copied file”.

The implementation is demonstrated in the code below.

<?php
copy('project.txt', 'project_backup.txt') or die("Could not copy file");
echo "File successfully copied to 'project_backup.txt'"; 
?>

Deleting a file

The file is deleted using the unlink function. In the code below, the implementation is displayed.

<?php
if (!unlink('project_backup.txt'))
{
     echo "Could not delete file";
 }
else
{
     echo "File 'project_backup.txt' successfully deleted"; 
}
 ?>

PHP File_get_contents Function

The entire file contents can be read using the file get contents function.

The code below displays the implementation.

File get contents returns the file data as a string, whereas fgets reads the file line by line. This is the difference between file get contents and fgets.

Summary

  • A resource for storing data is a file.
  • Working with files is made simple by the extensive set of built-in functions available in PHP.
  • fopen, fclose, and file get contents are examples of common file functions.
  • The functions covered are summarised in the table below.
FunctionDescription
File_existsused to check whether a file is present or not  
fopenused to access files. The returned object is a pointer to the opened file.
fwriteutilized to create files
fcloseopen closed files using this
fgetswhen reading a file line by line.
copyutilized to copy a current file
unlinkused to eliminate a current file
file_get_contentsused to give back a file’s contents as a string.  

You Might Like

Leave a Reply

Your email address will not be published. Required fields are marked *