Delete folder contents from PHP

Posted on 2011-05-13
Last Modified: 2012-05-11
I have a PHP script that needs to delete a series of jpgs in a folder  the folder path is:


How do I script this to achieve this but leave the folder intact?
Question by:pda4me
    LVL 8

    Accepted Solution

    Dellete all jpg files in folder by mask:
    $mask = "*.jpg";
    array_map("unlink", glob($mask));

    Open in new window

    Delete only files listed in array:
    $filelist = array("image1.jpg", "image2.jpgs");
    array_map("unlink", $filelist);

    Open in new window

    LVL 30

    Expert Comment

    by:Marco Gasi
    Try this:

    $dir = '/var/www/vhosts/';
    $iterator = new DirectoryIterator($dir);
      if ($iterator->isFile() && ! $iterator-> isDot()){
        $ext = explode('.', $iterator->getFilename());
        if ($ext = 'jpg'){

    Author Closing Comment

    Worked GREAT!  Thanks!

    Featured Post

    Gigs: Get Your Project Delivered by an Expert

    Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

    Join & Write a Comment

    Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
    Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
    The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now