Solved

Deleting certain files

Posted on 2016-09-08
9
33 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 51

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 51

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
 
LVL 108

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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 108

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 108

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 82

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

747 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

10 Experts available now in Live!

Get 1:1 Help Now