File

Prepend string to a file with stream

I hope you have PHP5.
Yesterday someone in Qunu asked me is there a way to prepend a string in front of a file. I said the only way is to load the entire file into the memory, write the string into the file then append the file in the memory into the file.

I told him to check back my site later, I will come up with something better.
So I did, I would post this yesterday but for some real life reasons, it's postponed till today.
I'm a helpful person, you can Qunu me once in a while if you have PHP problem
This function suppose the script can write to the same directory of the script and you are using PHP5.

function prepend($string, $filename){
	$context = stream_context_create ();
	$fp = fopen($filename,'r',1,$context);
	$tmpname = md5($string);
	file_put_contents($tmpname,$string);
	file_put_contents($tmpname,$fp,FILE_APPEND);
	fclose($fp);
	unlink($filename);
	rename($tmpname,$filename);
}

The function first create a stream, a resource. then convert $fp to a stream. The script puts the string into a temporary file, and append the stream to the end. After that, replace the original file with the temporary file.

Simple file shredder in PHP

File shredding is used to destroy the data written on the disk. Usually rewrite the data once is enough to destroy the data, but for extreme measure, use super strong magnetic field.
The function I wrote below WORKS ONLY IF new data is written directly on top of the original file. This will be determined by your file system, and I don't know which file system works, but I know that NFS or Journaling file systems does not work.

function shred($filename,$strength=1,$fast=null){
	$size = filesize($filename);
 
	while($i < $strength){
		$fh = fopen($filename,'w');
		if($fast){
		$str = chr(rand(0,255));
			$str = str_repeat($str,$size);
		}else{
			$str = md5(rand(0,2147483647));
			$n = 32;
			while($n<$size){
				$str .= md5($str);
				$n+=32;
			}
		}
 
		fwrite($fh,substr($str,0,$size));
		fclose($fh);
		++$i;
	}
	return true;
}

Syndicate content
Honey Pot that kill bots