PHP Create File

Summary: in this tutorial, you will learn a couple of ways to create a new file in PHP.

Creating a file using the fopen() function

The fopen() function opens a file. It also creates a file if the file doesn’t exist. Here’s the syntax of the fopen() function:

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

To create a new file using the fopen() function, you specify the $filename and one of the following 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

Except for the 'a' and 'a+', the file pointer is placed at the beginning of the file.

If you want to create a binary file, you can append the character 'b' to the $mode argument. For example, the 'wb+' opens a binary file for writing.

The following example uses fopen() to create a new binary file and write some numbers to it:

<?php

$numbers = [1, 2, 3, 4, 5];
$filename = 'numbers.dat';

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

foreach ($numbers as $number) {
    fputs($f, $number);
}
fclose($f);
Code language: HTML, XML (xml)

How it works.

  • First, define an array of five numbers from 1 to 5.
  • Second, use the fopen() to create the numbers.dat file.
  • Third, use the fputs() function to write each number in the $numbers array to the file.
  • Finally, close the file using the fclose() function.

Creating a file using the file_put_contents() function

The file_put_contents() function writes data into a file. Here’s the syntax of the file_put_contents() function:

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

If the file specified by the $filename doesn’t exist, the function creates the file.

The file_put_contents() function is identical to calling the fopen(), fputs(), and fclose() functions successively to write data to a file.

The following example downloads a webpage using the file_get_contents() function and write HTML to a file:

<?php

$url = 'https://www.php.net';
$html = file_get_contents($url);
file_put_contents('home.html', $html);Code language: HTML, XML (xml)

How it works.

  • First, download a webpage https://www.php.net using the file_get_contents() function.
  • Second, write the HTML to the home.html file using the file_put_contents() function

Summary

  • Use the fopen() function with one of the mode w, w+, a, a+, x, x+, c, c+ to create a new file.
  • Use the file_put_contents() function to create a file and write data to it.
  • The file_put_contents() function is identical to calling fopen(), fputs(), and fclose() functions successively to write data to a file.
Did you find this tutorial useful?