Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 19 total  RSS 

Empty a Directory with PHP

// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone
//
// SureRemoveDir('EmptyMe', false);
// SureRemoveDir('RemoveMe', true);

<?php
function SureRemoveDir($dir, $DeleteMe) {
    if(!$dh = @opendir($dir)) return;
    while (false !== ($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
    }

    closedir($dh);
    if ($DeleteMe){
        @rmdir($dir);
    }
}
?>

Use Ruby to create a directory

Create a directory named 'temp' if it doesn't already exist. Source: 'Create a new directory if it's missing' http://snippets.dzone.com/posts/show/2554 [snippets.dzone.com] Reference: mkdir_p http://ruby-doc.org/core/classes/FileUtils.html#M004346 [ruby-doc.org]
FileUtils.mkdir_p 'temp'

Mark directories to be deleted based on their date-stamp

This Ruby code selects file directories which are older than a certain date and outputs an XML file naming all the directories to be removed. It does this by reading a directory listing formatted within the XML file 'dir.xml', all directories are named by a date-stamp, which is used to determine if the directory should be removed.

This example is used to maintain the webcamera (named 'pear') which saves it's images to a date-stamped directory daily. Any directory which is older than 14 days will be marked for deletion.

  def directory_housekeeping()
    lifespan = 14
    format_mask = 'm_d_y'
    separator = format_mask.match(/[\_*\-]/).to_s
    
    earliest_date = Time.now + (60 * 60 * 24) * -lifespan
    cut_off_date = Date.new(y=earliest_date.year,m=earliest_date.month,d=earliest_date.day)
        
    a_format = Array.new
    a_format[0] = format_mask.match(/^[y,m,d]*/).to_s
    a_format[1] = format_mask.match(separator + '[y,m,d]*').to_s.gsub(separator,'')
    a_format[2] = format_mask.match('[y,m,d]$').to_s
    
    file = File.new('../housekeeping/webcam_pear/dir.xml')
    ddoc = REXML::Document.new(file)
    file.close
    
    file_delete = File.new('../housekeeping/webcam_pear/files2delete.xml', 'w')
    doc_delete = Document.new()
    doc_delete.add_element('files')
    
    ddoc.root.elements.each('file') do |file_node|
      sfile = file_node.text
      idate = Array.new
      idate[0] = sfile.match(/^\d*/).to_s.to_i
      idate[1] = sfile.match(/\_\d*/).to_s.gsub(separator,'').to_i
      idate[2] = sfile.match(/\_\d*\d$/).to_s.gsub(separator,'').to_i

      h = Hash.new
      0.upto(2) {|i| h[a_format[i]] = idate[i]}

      file_date = Date.new(y=h['y'], m=h['m'], d=h['d'])

      if file_date < cut_off_date
        o_file2delete = Element.new('file')
        o_file2delete.text = file_date.strftime(dformat)
        doc_delete.root.add_element o_file2delete
      end
    end
    file_delete.puts doc_delete
  end



file: dir.xml
<dir>
  <file>11_4_2007</file>
  <file>11_5_2007</file>
  <file>11_6_2007</file>
  <file>11_7_2007</file>
  <file>11_8_2007</file>
  <file>11_9_2007</file>
  <file>12_10_2007</file>
  <file>12_11_2007</file>
  <file>12_1_2007</file>
  <file>12_12_2007</file>
  <file>12_13_2007</file>
  <file>12_14_2007</file>
  <file>12_15_2007</file>
  <file>12_16_2007</file>
  <file>12_17_2007</file>
  <file>12_18_2007</file>
  <file>12_19_2007</file>
  <file>12_20_2007</file>
  <file>12_21_2007</file>
  <file>12_2_2007</file>
  <file>12_22_2007</file>
  <file>12_23_2007</file>
  <file>12_24_2007</file>
  <file>12_25_2007</file>
  <file>12_26_2007</file>
  <file>12_27_2007</file>
  <file>12_28_2007</file>
  <file>12_3_2007</file>
  <file>12_4_2007</file>
  <file>12_5_2007</file>
  <file>12_6_2007</file>
  <file>12_7_2007</file>
  <file>12_8_2007</file>
  <file>12_9_2007</file>
 </dir>

file: files2delete.xml
<files>
  <file>11_4_2007</file>
  <file>11_5_2007</file>
  <file>11_6_2007</file>
  <file>11_7_2007</file>
  <file>11_8_2007</file>
  <file>11_9_2007</file>
  <file>12_10_2007</file>
  <file>12_11_2007</file>
  <file>12_1_2007</file>
  <file>12_12_2007</file>
  <file>12_13_2007</file>
  <file>12_14_2007</file>
  <file>12_15_2007</file>
  <file>12_2_2007</file>
  <file>12_3_2007</file>
  <file>12_4_2007</file>
  <file>12_5_2007</file>
  <file>12_6_2007</file>
  <file>12_7_2007</file>
  <file>12_8_2007</file>
  <file>12_9_2007</file>
 </files>

Using Ruby to list directory names from a remote machine

The first line of code executes an external shell command which retrieves directory names into an array. The second line of code displays each directory making sure to chop the '/', and '\n' from the name.
dir_listing = `ssh 192.168.1.10 'ls */ -d'`
dir_listing.each { |directory| puts directory.chop.chop }

Note: In this example ssh access to the remote machine does not prompt the user for a password as the hosts know each other. see ssh-keygen.

Using Ruby to delete a file directory

In this example the file we want to delete is a non-empty directory called sample.
  require 'fileutils' 

  FileUtils.rm_r 'sample'

Directory Compare

ColdFusion - Compare two directories and report:
1. What files exist in folder A, but not B.
2. What files exist in folder B, but not A.
3. What files exist in both, but appear different.

<cfsetting requesttimeout="9999">

<cfparam name="FORM.DevelopmentDirectory" default="/kkkkkk/lllll/bbbb/ccc">
<cfparam name="FORM.ProductionDirectory" default="/mmmmmm/ggggg/bbbb/ccc">
<cfparam name="FORM.CommonDirectory" default="/ccc">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Directory Compare</title>
</head>

<body>

<h3>Directory Compare</h3>
<form name="directoryCompare" action="index.cfm" method="post">
<table>
	<tr>
    	<td>Development Directory</td>
        <td><input name="DevelopmentDirectory" id="DevelopmentDirectory" type="text" value="<cfoutput>#FORM.DevelopmentDirectory#</cfoutput>" size="70"></td>
    </tr>
	<tr>
    	<td>Production Directory</td>
        <td><input name="ProductionDirectory" id="ProductionDirectory" type="text" value="<cfoutput>#FORM.ProductionDirectory#</cfoutput>" size="70"></td>
    </tr>
	<tr>
    	<td>Common Directory</td>
        <td><input name="CommonDirectory" id="CommonDirectory" type="text" value="<cfoutput>#FORM.CommonDirectory#</cfoutput>" size="40"></td>
    </tr>
    <tr>
    	<td>&nbsp;</td>
        <td><input type="submit" name="submit" value="submit"></td>
    </tr>
</table>
</form>

<cfif isdefined('FORM.submit')>

<cfdirectory action="list" directory="#FORM.ProductionDirectory#" name="prodDir" recurse="yes">
<!--- <cfdump var="#prodDir#"> --->
<cfdirectory action="list" directory="#FORM.DevelopmentDirectory#" name="devDir" recurse="yes">
<!--- <cfdump var="#devDir#"> --->


<!--- Need common directory base to compare --->
<cfset dev_strip = Mid(FORM.DevelopmentDirectory,1,FindNoCase(FORM.CommonDirectory,FORM.DevelopmentDirectory))>
<cfset prod_strip = Mid(FORM.ProductionDirectory,1,FindNoCase(FORM.CommonDirectory,FORM.ProductionDirectory))>


<!--- o = Output Container --->
<cfset o = StructNew()>
<cfset o.keys = ArrayNew(1)>


<cfloop query="prodDir">

	<!--- Put array string in the order that will sort correctly --->
	<cfset L = prodDir.TYPE & "|" & ReplaceNoCase(prodDir.DIRECTORY,prod_strip,"","all") & "/" & prodDir.NAME >
	<!--- Turn the type/dir/name into something that makes a valid variable name --->
	<cfset k = "K" & cfusion_encrypt(L,"key")>

	<!--- Have we encountered this entry before? --->
	<!--- This also filters duplicates between the two queries. --->
	<cfif not StructKeyExists(o,k)>
		<!--- Add to list of valid values --->
		<cfset ArrayAppend(o.keys,L & "|" & k)>
        <cfset o[k] = StructNew()>
		<cfset o[k].prod_path = "">
		<cfset o[k].prod_type = "">
		<cfset o[k].prod_size = "">
		<cfset o[k].dev_path = "">
		<cfset o[k].dev_type = "">
		<cfset o[k].dev_size = "">
	</cfif>

	<cfset o[k].prod_path = prodDir.DIRECTORY & "/" & prodDir.NAME>
	<cfset o[k].prod_type = prodDir.TYPE>
	<cfset o[k].prod_size = prodDir.SIZE>

</cfloop>
<!--- <cfdump var="#o#"> --->


<cfloop query="devDir">

	<!--- Put array string in the order that will sort correctly --->
	<cfset L = devDir.TYPE & "|" & ReplaceNoCase(devDir.DIRECTORY,dev_strip,"","all") & "/" & devDir.NAME >
	<!--- Turn the type/dir/name into something that makes a valid variable name --->
	<cfset k = "K" & cfusion_encrypt(L,"key")>

	<!--- Have we encountered this entry before? --->
	<!--- This also filters duplicates between the two queries. --->
	<cfif not StructKeyExists(o,k)>
		<!--- Add to list of valid values --->
		<cfset ArrayAppend(o.keys,L & "|" & k)>
        <cfset o[k] = StructNew()>
		<cfset o[k].prod_path = "">
		<cfset o[k].prod_type = "">
		<cfset o[k].prod_size = "">
		<cfset o[k].dev_path = "">
		<cfset o[k].dev_type = "">
		<cfset o[k].dev_size = "">
	</cfif>

	<cfset o[k].dev_path = devDir.DIRECTORY & "/" & devDir.NAME>
	<cfset o[k].dev_type = devDir.TYPE>
	<cfset o[k].dev_size = devDir.SIZE>

</cfloop>
<!--- <cfdump var="#o#"> --->


<cfset ArraySort(o.keys,"textnocase","asc")>


<cfoutput>
<table cellspacing="0" border="0" cellpadding="3">
	<tr>
        <th>Development</th>
    	<th>Production</th>
    </tr>
	<cfloop index="i" from="1" to="#ArrayLen(o.keys)#">
	    <cfset k = ListLast(o.keys[i],"|")>
	<tr>
    	<!--- DEV --->
        <td style="border-bottom:1px solid ##CCCCCC;">
        	<cfif o[k].prod_path EQ "">
            	<!--- On Dev NOT on Prod --->
				<span style="color:##0000FF; font-weight:bold;">
            <cfelse>
            	<cfif o[k].prod_size NEQ o[k].dev_size>
                	<!--- On Dev and On Prod, but Differnet --->
					<span style="color:##FF9900; font-weight:bold;">
                <cfelse>
                	<!--- On Dev and On Prod and The Same (probably) --->
					<span>
				</cfif>
			</cfif>
        	#o[k].dev_path#&nbsp;
            </span>
			<cfif o[k].dev_path NEQ "">
            <span style="font-size:smaller; color:##999999;">(#o[k].dev_size#)</span>
            </cfif>
        </td>
        <!--- PROD --->
    	<td style="border-bottom:1px solid ##CCCCCC;">
        	<cfif o[k].dev_path EQ "">
            	<!--- On Prod NOT On Dev --->
				<span style="color:##FF0000; font-weight:bold;">
            <cfelse>
            	<cfif o[k].prod_size NEQ o[k].dev_size>
                	<!--- On Dev and On Prod, but Differnet --->
					<span style="color:##FF9900; font-weight:bold;">
                <cfelse>
                	<!--- On Dev and On Prod and The Same (probably) --->
					<span>
				</cfif>
			</cfif>
        	#o[k].prod_path#&nbsp;
            </span>
			<cfif o[k].prod_path NEQ "">
            <span style="font-size:smaller; color:##999999;">(#o[k].prod_size#)</span>
            </cfif>
        </td>
    </tr>
    </cfloop>
</table>
</cfoutput>
</cfif>

</body>
</html>

basename & dirname in Perl

These two Perl functions implement approximations of the UNIX utilities `basename` and `dirname`, though basename() automatically strips off the last extension no matter what.
sub basename($) {
 my $file = shift;
 $file =~ s!^(?:.*/)?(.+?)(?:\.[^.]*)?$!$1!;
 return $file;
}

sub dirname($) {my $file = shift; $file =~ s!/?[^/]*/*$!!; return $file; }

Image aggregator

This PHP snippet outputs the contents of a table (beginning & ending tags not included) containing all the images from the current directory.
<?PHP
 $columns = 3;
 $im = glob("*.{gif,jpg,png}", GLOB_BRACE);
 $rows = ceil(count($im) / $columns);
 for ($i = 0; $i < $rows; $i++) {
  echo "\n<TR>";
  for ($j = $columns*$i; isset($im[$j]) && $j - $columns*$i < $columns; $j++) {
   echo "<TD>$im[$j]<BR><IMG SRC='$im[$j]'></TD>";
  }
  echo "</TR>";
 }
?>

Directory List with PHP

// description of your code here

This code list all files and subdirectories in a dirctory with links.


<html><head><title>ribafs.net - Tutoriais</title></head>
<body bgcolor='#FFFACD'>
<h2 align=center><a href="http://ribafs.net">http://ribafs.net - <?php echo date('d/m/Y H:i:s'); ?></a></h2>

<?php
$dn = opendir (dirname(__FILE__));
$exclude = array("index.php", ".", "..");

// adiciona os arquivos ao array $arquivos
while($fn = readdir($dn)) {
	if ($fn == $exclude[0] || $fn == $exclude[1] || $fn == $exclude[2]) continue;
	$arquivos[] = $fn;
}
// ordena o vetor
sort($arquivos);
// exibe os arquivos

foreach ($arquivos as $arquivo)

if (is_dir($arquivo)){
	$dir .= "<img src='/imagens/diretorio.png'>&nbsp;<a href='$arquivo'>$arquivo</a><br>";
}else{
	$tamanho = filesize($arquivo);
	$m = 'bytes';
	if ($tamanho>1024) {
		$tamanho=round($tamanho/1024,2);
		$m = 'KB';
	} elseif($tamanho > 1024*1024){
		$tamanho = round(($tamanho/1024)/1024,2);
		$m = 'MB';
	}
	$arq .= "<img src='/imagens/arquivo.png'>&nbsp;<a href='$arquivo'>$arquivo</a> - $tamanho $m<br>";
}
echo $dir . $arq;

closedir($dn);
?>


Perl: Dirify string

Clean up a string for creation of a directory named using the string.

my $dir = dirify('The s^#%@$!#! <b>title</b> ever');     # outputs 'The-S-Title-Ever'

sub dirify {
    my $s = shift;

    $s =~ s!<[^>]+>!!gs;            # Remove HTML tags.
    $s =~ s!<!&lt;!gs;

    $s =~ s!&[^;\s]+;!!g;           # Remove HTML entities.
    $s =~ s![^A-Za-z0-9-_ ]! !g;    # Allow only alphanumeric chars.
    $s =~ s!\s+! !g;                # Remove extra spaces.
    $s =~ s!\s$!!g;         
    $s =  lc $s;                    # Convert to lower-case.   
    $s =~ s!(\b.)!\U$1!g;           # Capitalize words (Comment out if you don't need this)
    $s =~ tr! !-!s;                 # Finally, change space chars to dashes.

    return $s;
}
« Newer Snippets
Older Snippets »
Showing 1-10 of 19 total  RSS