# How to work with files/folders in PHP

> Learn how to work with files in PHP using file_exists and filesize, open them with fopen, read with fgets, write with fwrite, and delete with unlink.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2022-09-02 | Topics: [PHP](https://flaviocopes.com/tags/php/) | Canonical: https://flaviocopes.com/php-files-folders/

PHP is a server-side language and one of the handy things it provides is access to the filesystem.

You can check if a file exists using `file_exists()`:

```php
file_exists('test.txt') //true
```

Get the size of a file using `filesize()`:

```php
filesize('test.txt')
```

You can open a file using `fopen()`. Here we open the `test.txt` file in **read-only mode** and we get what we call a **file descriptor** in `$file`:

```php
$file = fopen('test.txt', 'r')
```

We can terminate the file access calling `fclose($fd)`.

Read the content of a file into a variable:

```php
$file = fopen('test.txt', 'r')

fread($file, filesize('test.txt'));

//or

while (!feof($file)) {
	$data .= fgets($file, 5000);
}
```

> `feof()` checks that we haven’t reached the end of the file as `fgets` reads 5000 bytes at a time

You can also read a file line by line using `fgets()`:

```php
$file = fopen('test.txt', 'r')

while(!feof($file)) {
  $line = fgets($file);
  //do something
}
```

To write to a file you must first open it in **write mode**, then use `fwrite()`:

```php
$data = 'test';
$file = fopen('test.txt', 'w')
fwrite($file, $data);
fclose($file);
```

We can delete a file using `unlink()`:

```php
unlink('test.txt')
```

Those are the basics, of course there are [more functions to work with files](https://www.php.net/manual/en/ref.filesystem.php).
