Creating a file in PHP With Examples

In this article, we will be creating a file in PHP in the easiest way with a detailed explanation as well as best program examples. This article is a continuation of the previous topic, entitled PHP File to Array.

In PHP, creating a file can simply be done with the use of fopen() function.

Creating a file in PHP With Examples
Creating a file in PHP With Examples

Creating a file using the fopen() function in PHP

The fopen() is a built-in function which is used for creating a file. It sounds a little bit confusing, but in PHP (Hypertext Preprocessor). The same function can create a file and open a files.

Syntax:

fopen ( string $filename , string $mode , bool $use_include_path = false , resource $context = ? ) : resource

For creating a new file with the use of fopen() function we need to specify or declared a $filename and one mode.

Modes:

ModeFile Pointer
‘w+’At the beginning of the file
‘a’At the end of the file
‘a+’At the end of the file
‘x’At the beginning of the file
‘x+’At the beginning of the file
‘c’At the beginning of the file
‘c+’At the beginning of the file

TAKE NOTE: If you want to create a (binary file), you will need to append the character ‘b‘ to an argument name $mode. For example, this ‘wb+’ automatically opens and close the file for writing a binary.

Example:

<?php

// file called
$numbers = [11, 12, 13, 14, 15];
$filename = 'numbers.dat';

$f = fopen($filename, 'wb');
if (!$f) {
    die('Error creating the file ' . $filename);
}

foreach ($numbers as $number) {
    fputs($f, $number);
}
fclose($f);

?>

The program works in this way.

  • First, is to define an array which consists of five numbers from 11 to 15.
  • Second, the fopen() and fwrite functions should be used to create a numbers.dat file.
  • Third, the fputs() function is used to write each number in the array name $numbers to file.
  • Lastly, terminate the file with the use of fclose() function.

Creating a file using the file_put_contents() function in PHP

The file_put_contents() is a function which is used to write data into the existing file.

Syntax:

file_put_contents ( string $filename , mixed $data , int $flags = 0 , resource $context = ? ) : int

TAKE NOTE: Once the file upload is showing results of $filename doesn’t exist, the function successfully creates the file.

In addition, if the function returns file_put_contents() is identical when calling the fputs(), fopen(), and fclose() functions sequentially to write data in a file.

For example:

<?php

$url = 'https://itsourcecode.com/';
$html = file_get_contents($url);
file_put_contents('home.html', $html);

?>

The program works in this way.

  • First, the program will download a webpage https://itsourcecode.com/ with the use of function file_get_contents() functions.
  • Lastly, the program will write the HTML (HyperText Markup Language) file using the function file_put_contents().

What does file () do in PHP?

The file() simply works by reading a file into an array. Each element on the array contains a number of lines from the file handling where the newline character is still attached.

How to create a folder and save it in PHP?

In PHP, to create a folder and save, it can simply be done by the function name mkdir(). This is a built-in function that creates a new folder and directory with a specified pathname.

Furthermore, the path and mode are sent as (parameters) to the function mkdir() and it will return TRUE if successful otherwise FALSE if fails.

What is file and directory in PHP?

The file and directory is a set of functions used to retrieve details, update them, and fetch or get information on various system file directories in PHP.

How do I run a PHP file?

The PHP file located inside the (htdocs) folder, if you want to execute or run the system, you need to open it in any web browser such as Google Chrome, Mozilla Firefox, and Brave and enter the folder name example “localhost/sample. php” and simply click the enter button.

How do I edit a PHP file?

To edit a file you will need to install a text editor such as VS Code, Sublime Text and any other PHP code editor online.

What is the file extension of PHP?

The file extension of PHP is (.php) which need to be put on the end of every file which is similar to a PowerPoint file with a (.ppt) file extension.

Summary

This article tackle in Creating a file, and also tackles Creating a file using the file_put_contents() function, what does file () does, how to create a folder and save it, what is file and directory, how we run a PHP file, how do I edit a PHP file, and what is the file extension.

I hope this lesson has helped you learn PHP a lot. Check out my previous and latest articles for more life-changing tutorials that could help you a lot.

Common use cases for Creating a file

  • Web application development. Full-stack PHP apps using vanilla PHP or Laravel/Symfony frameworks.
  • WordPress plugin/theme development. Custom functionality for the world’s most popular CMS.
  • API development. REST or GraphQL endpoints serving mobile apps and SPAs.
  • CLI tools. Command-line scripts for cron jobs, data migration, or automation.
  • Legacy code maintenance. PHP powers a large share of the web; understanding it is a durable skill.

Working code example

<?php
declare(strict_types=1);

class UserService {
    public function getGreeting(string $name): string {
        if ($name === "") {
            throw new InvalidArgumentException("Name is required");
        }
        return "Welcome, " . htmlspecialchars($name);
    }
}

$service = new UserService();
echo $service->getGreeting("Alice");
?>

Best practices

  • Enable strict types. declare(strict_types=1) at the top of every file catches type coercion bugs.
  • Use Composer. Modern PHP uses Composer for dependency management, autoloading, and PSR-4 class naming.
  • Follow PSR standards. PSR-12 for coding style, PSR-4 for autoloading, PSR-3 for logging.
  • Write unit tests with PHPUnit. Aim for 70%+ code coverage on business-critical modules.
  • Use static analysis. PHPStan or Psalm catch many bugs before code runs.

Common pitfalls

  • Global state. Overusing global variables makes testing hard. Prefer dependency injection.
  • SQL concatenation. Always use prepared statements. Never concatenate user input into SQL strings.
  • Missing type declarations. Old PHP allowed loose types. Modern PHP encourages strict typing everywhere.
  • Ignoring errors. Set error_reporting(E_ALL) in development. Handle errors explicitly in production.

Frequently Asked Questions

What PHP version does this tutorial target?
This tutorial is written for PHP 8.0 or higher. Modern features (arrow functions, named arguments, match expressions, enums, nullsafe operator) work best in PHP 8.1+. For legacy PHP 7.x, most examples still run but with fallback syntax.
Do I need XAMPP to run PHP code examples?
For beginners, XAMPP (Apache + PHP + MySQL) is the easiest setup on Windows. On Mac, use MAMP or Homebrew php. On Linux, install php-cli via apt or yum. For quick one-off tests, use an online PHP sandbox like PHP Sandbox or 3v4l.org.
How do I test the code snippets in this tutorial?
Save each example as a .php file inside XAMPP htdocs folder, start Apache in XAMPP Control Panel, then open http://localhost/yourfile.php in a browser. For pure PHP CLI code, run php yourfile.php from the terminal.
Can I use this in a Laravel project?
Yes. Most native PHP functions covered in these tutorials work identically inside Laravel. Some Laravel helpers (str_helpers, arr_helpers) provide framework-specific wrappers around the same functions.
Where can I get more PHP practice projects?
Browse itsourcecode.com PHP Projects for 300+ free capstone-ready systems (POS, inventory, hospital management, e-commerce). Each includes source code, database SQL, and installation guide for BSIT capstone students.

Glenn Azuelo

Programmer & Technical Writer at PIES IT Solution

Glenn Azuelo is a programmer and writer at PIES IT Solution, author of 40+ PHP tutorials, Java capstone projects, and Python game guides at itsourcecode.com. Specializes in PHP built-in functions (string manipulation, arrays, filesystem, magic methods), Java Windows Forms projects for BSIT capstone (chat application, POS, faculty management, memory game), and Python game programming with Pygame (chess, blackjack, dice).

Expertise: PHP · PHP Tutorials · PHP Built-in Functions · PHP String Functions · PHP Array Functions · PHP Magic Methods · Java · Java Swing · Windows Forms · Python · Pygame · Capstone Projects  · View all posts by Glenn Azuelo →

Leave a Comment