File - potatoscript/php GitHub Wiki

Files in PHP

Overview

PHP provides a wide range of functions for handling files, from reading and writing to file manipulation and error handling. This section covers:

  • Reading Files
  • Writing Files
  • File Handling Functions
  • File Uploads
  • File Permissions
  • File System Functions

Reading Files

PHP makes it easy to read files in various ways. The most common methods are fopen(), file_get_contents(), and readfile().

Example (Using file_get_contents()):

<?php
// Read the content of a file into a string
$content = file_get_contents('example.txt');
echo $content; // Outputs the content of 'example.txt'
?>

Explanation:

  • file_get_contents() reads the entire file into a string. This is the simplest and most common method for reading text files.

Example (Using fopen() and fgets()):

<?php
// Open the file for reading
$file = fopen('example.txt', 'r');
if ($file) {
    // Read one line at a time
    while (($line = fgets($file)) !== false) {
        echo $line . "<br>"; // Outputs each line of the file
    }
    fclose($file); // Close the file after reading
} else {
    echo "Unable to open the file.";
}
?>

Explanation:

  • fopen() opens a file for reading or writing.
  • fgets() reads a file line by line, which is useful for processing large files.

Writing Files

You can write data to files using the fopen(), fwrite(), and file_put_contents() functions.

Example (Using file_put_contents()):

<?php
// Write data to a file (overwrites the file)
file_put_contents('example.txt', 'Hello, world!');
?>

Explanation:

  • file_put_contents() writes data directly to a file. It overwrites the file if it already exists, and creates the file if it does not exist.

Example (Using fopen() and fwrite()):

<?php
// Open the file for writing
$file = fopen('example.txt', 'w');
if ($file) {
    // Write data to the file
    fwrite($file, 'Hello, world!');
    fclose($file); // Close the file after writing
} else {
    echo "Unable to open the file.";
}
?>

Explanation:

  • fopen() with the 'w' mode opens the file for writing and truncates it to zero length if it exists.
  • fwrite() writes data to the file.

File Handling Functions

PHP offers several useful functions for file manipulation, such as checking file existence, getting file sizes, and modifying file permissions.

Example (Checking if a File Exists):

<?php
// Check if a file exists
if (file_exists('example.txt')) {
    echo "The file exists.";
} else {
    echo "The file does not exist.";
}
?>

Explanation:

  • file_exists() checks whether the specified file exists.

Example (Getting the File Size):

<?php
// Get the size of the file
$fileSize = filesize('example.txt');
echo "The size of the file is: $fileSize bytes.";
?>

Explanation:

  • filesize() returns the size of the file in bytes.

Example (Changing File Permissions):

<?php
// Change the file permissions
chmod('example.txt', 0755);
echo "File permissions changed.";
?>

Explanation:

  • chmod() changes the permissions of a file. The second parameter specifies the permissions in octal format.

File Uploads

PHP makes it easy to handle file uploads from forms using the $_FILES superglobal array. Here's how to handle file uploads securely:

Example (File Upload Form):

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

Example (Handling File Upload in PHP):

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    // Check if the file is an actual image (optional)
    if (isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if ($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }

    // Check if the file already exists
    if (file_exists($targetFile)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check file size (max 5MB)
    if ($_FILES["fileToUpload"]["size"] > 5000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow only certain file formats
    if ($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
        echo "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
            echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

Explanation:

  • $_FILES is used to access uploaded files.
  • move_uploaded_file() moves the uploaded file to a specified directory.
  • The file upload is secured by checking for file type, file size, and whether the file already exists.

File Permissions

Managing file permissions is an important part of file handling. PHP provides functions like chmod(), chown(), and chgrp() to control file permissions.

Example (Changing File Permissions):

<?php
// Change the file permissions to be readable and writable by the owner
chmod('example.txt', 0644);
?>

Explanation:

  • chmod() changes the permissions of a file, and the octal value 0644 grants read/write permissions for the owner and read-only permissions for others.

File System Functions

PHP provides a variety of file system functions for creating, deleting, and checking directories.

Example (Creating a Directory):

<?php
// Create a new directory
mkdir('new_directory');
echo "Directory created successfully.";
?>

Example (Removing a Directory):

<?php
// Remove an empty directory
rmdir('new_directory');
echo "Directory removed successfully.";
?>

Explanation:

  • mkdir() creates a directory.
  • rmdir() removes an empty directory.

Conclusion

In this section, we covered the following topics:

  • Reading Files: Using file_get_contents(), fopen(), and fgets() to read files.
  • Writing Files: Writing data to files using file_put_contents() and fwrite().
  • File Handling Functions: Checking file existence, retrieving file size, and modifying file permissions.
  • File Uploads: Handling file uploads from forms securely with $_FILES.
  • File Permissions: Managing file permissions with chmod(), chown(), and chgrp().
  • File System Functions: Creating and removing directories using mkdir() and rmdir().

By mastering these functions, you’ll be able to handle various file operations in PHP. In the next section, we will dive into MySQL Database Integration, where we will learn how to interact with databases using PHP.


Basic-definition

  • Directory of current included file
  • if a script called 'database.php' which is included from anywhere on the filesystem would like to include the script 'database_class.php', which lays in the same directory
   include_one(dirname(__FILE__).`/database_class.php`);
  • FILE : The full path and filename of the file with symlinks resolved. If used inside an include. The name of the included file is returned.
  • LINE : The current line number of the file.
  • DIR : The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(FILE)
  • FUNCTION : The function name
  • CLASS : The class name, included the namespace it was declared in (Foo\Bar)

JSON-Write-Read

   header('Content-Type:application/json');
   $content = "../../apps/".$_POST["file"];
   $datalist = json_decode(file_get_contents($content),true);
   echo json_encode($datalist); 
   $fp = fopen('../../data.json','w');
   fwrite($fp,json_encode($datalist));
   fwrite($fp);
   _.$Params('file','data.json'); //my own function

Read-File

   $directory = 'files';
   if($handle = opendir($directory.'/')){
      echo 'search\''.$directory.'\':<br>';
      while($file= readdir($handle)){
         if($file!='.'&& file != '..'){
            echo '<a href="'.$directory.'/'.$file.'">'.$file.'</a>';
         }
      }
   }
   echo 'addExpandCollapseAll();startParentNode('2010');';
   $directory = "tcd/2010/";
   if($handle = opendir($directory)){
     while($file = readdir($handle)){
        if($file!='.' && $file != '..'){
           echo 'addNode(\'<a href="'.$directory.$file.' ">'.$file.'</a>\');';
        }
     }
   }
   echo 'endParentNode();';

Upload-File

   $name = $_FILES['file']['name'];
   $size = $_FILES['file']['size'];
   $type = $_FILES['file']['type'];
   $tmp_name = $_FILES['file']['tmp_name'];
   if(isset($name)){
      if(!empty($name)){
         $location = 'uploads/';
         if(move_uploaded_file($tmp_name,$location,$name)){
            echo 'uploaded!';
         }
      }else{
         echo 'please choose a file.';
      }
   }
   <form action="upload.php" method="POST" enctype="multipart/form_data">
      <input type="file" name="file">
      <input type="submit" value="submit">
   </form>
⚠️ **GitHub.com Fallback** ⚠️