Recently I am writing a website that needs to upload pictures. If the pictures are modified, the pictures will be useless and will occupy the hard disk resources of the server, so I thought of using the unlink function to delete old photos.
Problem: The unlink function can only delete the relative directory relative to the function execution file or the absolute directory on the disk.
Both directories are inconvenient because the image directory stored on the website is a relative path to the root directory of the website.
Solution:
Define the constants of the website disk directory in the entry file, and splice them when deleting;
In index.php
// 定义磁盘目录 // 定义磁盘目录 define('__DOCUMENT_PATH__',substr(__FILE__ ,0,-10) ); 然后定义一个公共函数 function delOldPic($url) { unlink(__DOCUMENT_PATH__.$pic); }
Just use a custom function to delete it.
Let’s take a look at the definition of the PHP unlink() function through an example.
Definition and usage
unlink() function deletes files.
If successful, return true, otherwise return false.
Syntax
unlink(filename,context)
Notes: Support for context was added in PHP 5.0.0.
Example:
<?php $file = "test.txt"; if (!unlink($file)) { echo ("Error deleting $file"); } else { echo ("Deleted $file"); } ?>
Recommended tutorial:PHP tutorial
The above is the detailed content of Example tutorial on deleting old photos from the website in PHP. For more information, please follow other related articles on the PHP Chinese website!