PHP unlink() (Delete File) 🎯

beginner
7 min

PHP unlink() (Delete File) 🎯

Welcome to today's lesson, where we're going to learn about the unlink() function in PHP! This function is used to delete a file. By the end of this tutorial, you'll be able to remove files from your projects with ease. πŸ’‘ Pro Tip: This is particularly useful when you need to delete user-uploaded files or temporary files.

What is unlink()? πŸ“

The unlink() function in PHP removes a file from the server. It takes a single argument - the file path of the file you want to delete.

How to use unlink() πŸ’‘

Let's dive into a simple example to understand how the unlink() function works:

php
<?php $file = 'example.txt'; if (unlink($file)) { echo "File $file deleted."; } else { echo "Error: Could not delete file $file."; } ?>

In this example, we're trying to delete a file named example.txt. The unlink() function checks if the file exists and if it can be deleted. If successful, it will output "File example.txt deleted." If not, it will output "Error: Could not delete file example.txt." βœ…

Advanced Usage πŸ“

The unlink() function can also be used with variables containing file paths. Here's an example of a form where a user can upload an image, and when the form is submitted, the old image is deleted:

php
<?php $old_image = 'old_image.jpg'; if (isset($_FILES['new_image']) && $_FILES['new_image']['error'] === UPLOAD_ERR_OK) { $new_image = $_FILES['new_image']['tmp_name']; $new_image_name = $_FILES['new_image']['name']; // Delete the old image unlink($old_image); // Save the new image here } ?>

In this example, we're checking if a new image has been uploaded. If it has, we're saving the new image's temporary name in $new_image, its name in $new_image_name, and then deleting the old image using unlink(). πŸ’‘ Pro Tip: Don't forget to save the new image after deleting the old one!

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the `unlink()` function in PHP do?


That's it for today's lesson on the unlink() function in PHP! Remember to use this function wisely, and always ensure you have the correct file path before deleting a file.

In the next lesson, we'll learn about more PHP functions that help you manipulate files. Stay tuned! πŸš€