Question

delete a file using php

Asked by: ellandrd

i have folder full of images.

is there any way using php to delete the file(s)

example

i have 4 files (images) called

D001_image1.jpg
D001_image2.jpg
D002_image1.jpg
D003_image1.jpg

in a lopp use php to delete all files with D001_image[i].jpg from the folder

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-06-16 at 04:30:59ID21460224
Tags

php

,

delete

,

file

Topic

PHP Scripting Language

Participating Experts
4
Points
500
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. parsing .jpg as php and returning a jpg?
    I want to use random images on my site, but I'd like to have them displayed by using jpg as the php extention. First of all, the server needs to be able to read a jpg as a php file -- I'm thinking this can be accomplished with htaccess. Second, this .jpg file (essentially a ...
  2. PHP Upload image
    Dear all, I have looked around and it been frustrating for the past 3 hrs....I would liek to the scripts for a form which would help me upload image files onto teh server. So basically, should have 2 files: A form for browsing my PC and choosing an image which is submitt...
  3. PDF to JPG in PHP
    Is there a good way to thumbnail PDFs to JPG in PHP? I'm looking to automate this function for my users. Size of the image doesn't matter as I can resize it after I get a thumbnail of the PDF in JPG.
  4. outlook will not display .jpg images
    outlook will not display .jpg images
  5. RewriteRule Jpg -> php in htaccess
    I would like to be able to rewrite separate jpg files to go into php files using rewriterule, not redirect. ive been trying and trying cant seem to make it work. any help would be apperciated.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: RoonaanPosted on 2005-06-16 at 04:33:37ID: 14229862

Yes, you would use:

unlink'('D001_image.jpg');

I think you can figure out how to write the loop yourself?

-r-

 

by: ThGPosted on 2005-06-16 at 04:34:56ID: 14229871

should be something like this. Remember that the $dir directory must be 777 permission if you run it from HTTP!

$dir = "/path/to/images";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
           if (preg_match('/^D001_image\d\.jpg$/', $file))
              unlink($dir . "/" . $file);
       }
       closedir($dh);
   }
}

 

by: ellandrdPosted on 2005-06-16 at 05:22:04ID: 14230294

unlink'('D001_image.jpg');

this is a php function?

and is the ' before the open bracket a miss type?

>> unlink'('D001_image.jpg');

 

by: lowfieldPosted on 2005-06-16 at 05:42:16ID: 14230445

 

by: RoonaanPosted on 2005-06-16 at 05:52:10ID: 14230530

>> unlink'('D001_image.jpg');
Yes that was a mistype naturaly.

-r-

 

by: neesterPosted on 2005-06-16 at 07:06:22ID: 14231225

Unlink is a common command.
PERL uses unlink too!
:)

 

by: ellandrdPosted on 2005-06-16 at 08:14:49ID: 14232110

ok guys, sorry i had to finish off some of my other questions off first.

right im trying to do, this delete any images associated with a record in a mysql db.

the table is called tblProperties which stores details on properties.

the page im trying to code is for deleting properties from the db., but not only delete the properties, but delete the images belong to that property too. all the images are stored in another folder. so far i can delete the properties record in the db with no hassle, but the next step is deleting the images too.

here is my code for deleting the property details/record from the db:

if (!$link_id) $link_id = db_connect();
                  $id = $_POST['id'];
                  if($id)
                  {
                        $Query = "SELECT record_id FROM tblProperties WHERE record_id=$id";
                        $PropertiesResult = mysql_query($Query, $link_id) or die("Database troubles</body></html>");
                        if ($row = mysql_fetch_array($PropertiesResult))
                        {
$ref_num = $row['property_ref_num'];                              
$Query = "DELETE FROM tblProperties WHERE record_id = $id";
                              mysql_query($Query, $link_id) or die("Database troubles deleting Property</body></html>");
                              ?>
                              <p>Property Deleted.<br>Redirecting you to the main page. Please wait...</p>
                              <script type="text/javascript">
                              <!--
                                    redirect('main.php');
                              //-->
                              </script>
                              <?php
                        }
                  }
                  else
                  {
                        die("No Record ID present");
                  }


what i now need to do is include the above code into my code to delete the images too...

as i mentioned above the image names are in a format like "ReferenceNum_image1.jpg"

only the reference number part of all the images change depending on what properties is selected to be deleted.

is it clear to what i want to do?

can somebody help me please?



 

by: RoonaanPosted on 2005-06-16 at 08:21:49ID: 14232203

Ellendr:

First add the next function to your file:
function delete_images_by_refnum($image_folder, $ref_num)
{
  $d = opendir($image_folder);'
  if(!is_resource($d)) return;
  while($f = readdir($d))
  {
    if(substr($f, 0, strlen($ref_num)+1) == $ref_num + '_')
      unlink ($image_folder.'/'.$f);
  }
}

Secondly edit the code you quotes in your last post to call the function:

                    if ($row = mysql_fetch_array($PropertiesResult))
                    {
                     $ref_num = $row['property_ref_num'];                        
                     delete_images_by_refnum(dirname(__FILE__).'/myimagefolder', $ref_num);

You have to change the first argument to state the correct foldername offcourse. You have to provide a relative link to the file this code is in. So when your code is in lib/delete.php and your images are in img/ the command would be:
                     delete_images_by_refnum(dirname(__FILE__).'/../img', $ref_num);

Kind regards

-r-

 

by: ellandrdPosted on 2005-06-16 at 08:35:48ID: 14232379

what i have is:

the relative path to my image folder is:

e:\\domains\\a\\antons-law.com\\user\\htdocs\\properties\\property_images\\

this page is located in folder called "properties"

so now my code looks like:

function delete_images_by_refnum($image_folder, $ref_num)
{
  $d = opendir($image_folder);'
  if(!is_resource($d)) return;
  while($f = readdir($d))
  {
    if(substr($f, 0, strlen($ref_num)+1) == $ref_num + '_')
      unlink ($image_folder.'/'.$f);
  }
}

if (!$link_id) $link_id = db_connect();
               $id = $_POST['id'];
               if($id)
               {
                    $Query = "SELECT record_id FROM tblProperties WHERE record_id=$id";
                    $PropertiesResult = mysql_query($Query, $link_id) or die("Database troubles</body></html>");
                    if ($row = mysql_fetch_array($PropertiesResult))
                    {
$ref_num = $row['property_ref_num'];    

delete_images_by_refnum(dirname("e:\\domains\\a\\antons-law.com\\user\\htdocs\\properties").'/property_images', $ref_num);


                     
$Query = "DELETE FROM tblProperties WHERE record_id = $id";
                         mysql_query($Query, $link_id) or die("Database troubles deleting Property</body></html>");
                         ?>
                         <p>Property Deleted.<br>Redirecting you to the main page. Please wait...</p>
                         <script type="text/javascript">
                         <!--
                              redirect('main.php');
                         //-->
                         </script>
                         <?php
                    }
               }
               else
               {
                    die("No Record ID present");
               }


am i right in the way ive got my code for the directory?

 

by: RoonaanPosted on 2005-06-16 at 08:45:23ID: 14232498

Ah, you have to full absolute path, that's even better.

Change the command to:

delete_images_by_refnum("e:\\domains\\a\\antons-law.com\\user\\htdocs\\properties\\property_images', $ref_num);

Or either

delete_images_by_refnum("e:/domains/a/antons-law.com/user/htdocs/properties/property_images', $ref_num);

-r-

 

by: ellandrdPosted on 2005-06-16 at 08:53:31ID: 14232574

ok i got this error:

Parse error: parse error, unexpected T_STRING in e:\domains\a\antons-law.com\user\htdocs\properties\secure\propertiesdelete.php on line 261

line 261 is:

$Query = "DELETE FROM tblProperties WHERE record_id = $id";

my code at the end of the page to delete is:

if (!$link_id) $link_id = db_connect();
                  $id = $_POST['id'];
                  if($id)
                  {
                        $Query = "SELECT record_id FROM tblProperties WHERE record_id=$id";
                        $PropertiesResult = mysql_query($Query, $link_id) or die("Database troubles</body></html>");
                        if ($row = mysql_fetch_array($PropertiesResult))
                        {

                              $ref_num = $row['property_ref_num'];

                              delete_images_by_refnum("e:\\domains\\a\\antons-law.com\\user\\htdocs\\properties\\property_images', $ref_num);

                              $Query = "DELETE FROM tblProperties WHERE record_id = $id";
                              mysql_query($Query, $link_id) or die("Database troubles deleting Property</body></html>");
                              ?>
                              <p>Property Deleted.<br>Redirecting you to the main page. Please wait...</p>
                              <script type="text/javascript">
                              <!--
                                    redirect('main.php');
                              //-->
                              </script>
                              <?php
                        }
                  }
                  else
                  {
                        die("No Record ID present");
                  }


                  function delete_images_by_refnum($image_folder, $ref_num)
                  {
                        $d = opendir($image_folder);

                        if(!is_resource($d)) return;

                        while($f = readdir($d))
                        {
                              if(substr($f, 0, strlen($ref_num)+1) == $ref_num + '_')
                                    unlink ($image_folder.'/'.$f);
                        }
                  }

 

by: RoonaanPosted on 2005-06-16 at 09:03:37ID: 14232703

delete_images_by_refnum("e:\\domains\\a\\antons-law.com\\user\\htdocs\\properties\\property_images', $ref_num);

should be either

delete_images_by_refnum("e:\\domains\\a\\antons-law.com\\user\\htdocs\\properties\\property_images", $ref_num);

or

delete_images_by_refnum('e:\\domains\\a\\antons-law.com\\user\\htdocs\\properties\\property_images', $ref_num);

The start and ending quotes didn't match up.

 

by: ellandrdPosted on 2005-06-16 at 09:04:20ID: 14232712

work here is finished. i have to go home now, but will be back online when i get home to finish this.

if you could take  alook at my code and see if you can find the error?

 

by: RoonaanPosted on 2005-06-16 at 09:05:51ID: 14232732

It could be that I am offline later this evening, but will respond back tomorrow if not toning :-)

 

by: ellandrdPosted on 2005-06-16 at 11:36:51ID: 14234156

ah, a simple error like that can go unnoticed very easy!!

you have very sharp eyes!!

 

by: ellandrdPosted on 2005-06-16 at 12:06:14ID: 14234449

ok i got a error on permissions?

you can see a screen shot here:

http://www.antons-law.com/properties/error.jpg

 

by: ellandrdPosted on 2005-06-16 at 12:19:35ID: 14234595

another thing i noticed too, when i delete 1 property hoping that properties images are deleted too, i find all my images get deleted when i refresh the page??

any ideas?

Ellandrd

 

by: RoonaanPosted on 2005-06-17 at 00:20:42ID: 14238161

The errors indicate that the line below is incorrect. Because this line fails the script just unlinks every item readdir returns, including parent directory ('..'), current directory ('.') and any other directories.

if(substr($f, 0, strlen($ref_num)+1) == $ref_num + '_')

I think it might be because of the $ref_num + '_'. Can you have a try with:

if(substr($f, 0, strlen($ref_num)+1) == $ref_num.'_')

And otherwise we could probably use:

if(preg_match('/^'.intval($ref_num).'_image/i', $f))

Hope this helps (finally ;-) )

-r-

 

by: ellandrdPosted on 2005-06-17 at 00:26:52ID: 14238185

Good morning Roonan,

i will change my line to:

if(substr($f, 0, strlen($ref_num)+1) == $ref_num.'_')

and see what happens, give me a minute, to make the changes and i'll get back to you

Ellandrd

 

by: ellandrdPosted on 2005-06-17 at 00:37:46ID: 14238234

it worked.

it was this line of code...

if(substr($f, 0, strlen($ref_num)+1) == $ref_num.'_')

thanks a million. grade A plus the 500 points!

can we now concentrate on my second question that we left yesterday and get that working?

Ellandrd

 

by: RoonaanPosted on 2005-06-17 at 00:44:41ID: 14238268

Thanks for the A, I will accompany to the other question.

-r-

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...