Solved

Deleting certain files

Posted on 2016-09-08
9
56 Views
Last Modified: 2016-09-09
I have this code to delete all my files
          if(unlink($file))
            {
            	echo "file named $file has been deleted successfully";
            }
            else
            	{
            	echo "file is not deleted";
            	}
        }

Open in new window


$files are files that contain '.5010.' But everytime I run this it echos out file not deleted. It has full permission, Im not sure what Im missing.
0
Comment
Question by:Jasmine Ikhreishi
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 56

Expert Comment

by:Julian Hansen
ID: 41789434
What does this output?

if (is_writable($file)) {
   if (unlink($file)) {
     echo "file named $file has been deleted successfully";
    }
    else {
      echo "file is not deleted";
    }
}
else {
  if (file_exists($file)) {
    echo "File {$file} exists but is not writable";
  }
  else {
    echo "File {$file} does not exist";
  }
}

Open in new window

0
 
LVL 1

Author Comment

by:Jasmine Ikhreishi
ID: 41789443
<?php 
//error_reporting(E_ALL);
//ini_set('display_errors' ,1);

 
$find = '.5010.';
$directory_with_files = './'.date('m-d-Y');
$dh  = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
    if(in_array($filename, array('.', '..')) || is_dir($filename))
        continue;

    $files[] = $filename;
}


foreach($files as $file)
{
    //find only 5010 files
    if(stripos($file, $find) !== false)
    {
        // open the 5010 file
        $handle = fopen(date('m-d-Y').'/'.$file, "r");
        $file_content = file_get_contents(date('m-d-Y').'/'.$file);
        $handle2 = fopen(date('m-d-Y').'/'.$file, "r");
        $file_content2 = file_get_contents(date('m-d-Y').'/'.$file);
     
        
        if ($handle) {
            $header = '';
            $name = '';
            $footer = '';
            $payor_blocks = array();
            
            
            // determine if file has more than one payor
            $payor_count = substr_count($file_content, 'N1');
            //if the file has more than one payor
            if($payor_count > 1) {
                //read the file line by line
                $header_end = false;
                $block_start = false;
                $count = 1;

           if($handle2){
                $line_number = 0;
                $line_stop= array();
                while (($line1 = fgets($handle2)) !== false) {
                
                	$line_number++;
                
                	if(strpos($line1, 'CAS') !==false){
                		 
                		$line_stop[] = $line_number;
                	}
                
                }
                $footer_line = count($line_stop)-2;
                $footer_line = $line_stop[$footer_line];
                
                
                $line_number = 0; }
                
                //look for occurances of CAS and what line each on is on
               
                while (($line = fgets($handle)) !== false) {
                    $line_number++;
                   

                    //look for the first payor block
                    if(strpos($line, 'N1') !== false || $block_start) {
                        $header_end = true; $block_start = true;
                         if(strpos($line, 'N1') !== false) {
                         	$count++;
                         }  
                            
                        //see if the block finished
                         if($line_number == $footer_line) {
                         	$block_start = false;
                         	$payor_blocks[$count] .= $line;
                         	$count++;
                         }
                  $payor_blocks[$count] .= $line;
                    } else {
                        //append to the header
                        if($header_end) {
                            $footer .= $line."\n";
                           
                        } else {
                            $header .= $line."\n";
                        }
                    }
      
                }
               
                //get payor blocks and create a file foreach payor
                $new_files = array();
                foreach($payor_blocks as $block) {
                    $filename = date('m-d-Y').'/'.$file . "_" . $count;
                    $count++;
                    $new_files[] = array(
                        'name' => $filename,
                        'content' => $header."\n".$block."\n".$footer	
                    	
                    );
                }
           
                //loop through new files and create them
                foreach($new_files as $new_file) {
                    //create file
                	$myfile = fopen($new_file['name'], "w");
   
                    //put contents in the file               	
                	fwrite($myfile, $new_file['content']);	
              		//close the file
                	fclose($myfile);
                }
                
               // echo "<pre>" . print_r($new_files, true) . "</pre>";
            } 
            else{

            	// DO what u were doing in script #1
           while (($line = fgets($handle)) !== false)
            {
            	$refid = 'REF*2U*';
            	
            	if(stripos($line, $refid) !== false)
            	{
            		$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
            		$refnumber = trim($refnumber);
            	
            		if($refnumber != '')
            		{
            			$refnumber = '_'.$refnumber.'_';
            			$filerenamed = str_replace($find, $refnumber,$file);
            			copy('./'.date('m-d-Y').'/'.$file, './'.date('m-d-Y').'/'. $filerenamed);
            			
            		}
            		//echo $refnumber . "\n";
            		
            	}
            
            	}
            }
            //delete here
        
        }

    }
    		// DONE - close the file
    				fclose($handle);
}

		//combine all files
		file_put_contents("combined.txt", ""); // Empty the file first
		foreach ($new_files as $my_file) {
		file_put_contents("combined.txt", $my_file, FILE_APPEND);

}

Open in new window


I want to delete the orginal ones that have 5010, not the ones that are done after split, do you have any idea where I put that in my code?
0
 
LVL 56

Expert Comment

by:Julian Hansen
ID: 41789467
Please read my last post - I need to know what the output is from the code I posted.
1
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41789489
Please, please, please set error_reporting(E_ALL) in the top of your PHP scripts.  Set the error display and the error logging.  You've got these enormously valuable features commented out in the most recent post.  You ALWAYS want to know of ALL of the ERRORS.  And you might get a better, quicker answer if you post this in E-E Gigs where you can get hands-on assistance.
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 41789491
This expert suggested creating a Gigs project.
Gigs recommendation checked!
0
 
LVL 1

Author Comment

by:Jasmine Ikhreishi
ID: 41789505
Sucessfully deleted but thats all the files so I think I put it in a wrong area, thats why I posted my code
0
 
LVL 1

Author Comment

by:Jasmine Ikhreishi
ID: 41789527
Where should I put the code if I just want it to delete the original files?
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41789593
We would need to understand how you identify "the original files" in this context.  Would this be all the files with '.5010.'?

See also: https://www.experts-exchange.com/questions/28968224/How-can-i-delete-certain-files-from-php-in-a-directory.html
0
 
LVL 83

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 250 total points
ID: 41789690
You might want to read the comments here:  http://php.net/manual/en/function.unlink.php   There are several situations in which 'unlink' does not delete a file.  In particular, if the file is still 'open', it won't be deleted.
2

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

685 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