Creation with PHP files of a certain size with a random content

The file is not suitable to be accessed via a web browser. It must be started with the command line: “php filename.php” to give the script practically all the time and allow sufficient resources for its execution. In Debian install the tool with: # apt-get install php5-cli. In the directory of the file start it with # php ./filename.php.

<?php

// Generate sized files with random content

function generate_random_file_content($size, $type = "b", $prefix = "file_", $extension = ".txt")
{
	if(!is_numeric($size) || $size <= 0)
		return -1;

	$content = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 
				   "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
	$dirroot = realpath(__DIR__)."/";
	$multiplier = 1024;
	$number = $size;	
	
	switch($type)
	{
		case "b":
			$suffix = "bytes";
			break;
		case "k":
			$suffix = "kbytes";
			$size = $size * $multiplier;
			break;
		case "m":
			$suffix = "mbytes";
			$size = $size * $multiplier * $multiplier;
			break;
		case "g":
			$suffix = "gbytes";
			$size = $size * $multiplier * $multiplier * $multiplier;
			break;
		case "t":
			$suffix = "tbytes";
			$size = $size * $multiplier * $multiplier * $multiplier * $multiplier;
			break;
		default:
			return -2;
			break;
	}
	
	$file_with_path = $dirroot.$prefix.$number.$suffix.$extension;
	$fp = fopen($file_with_path, "w");
	
	if(!$fp)
		return -3;
	
	$sum_bytes_written = 0;
	
	$content_size = sizeof($content);
	
	do
	{
		$content_index = rand(0, $content_size - 1);
		$char = $content[$content_index];
		
		if(!is_numeric($char))
		{
			$make_upper = rand(0, 1);
			if($make_upper)
				$char = strtoupper($char);
		}
		
		$bytes_written = fwrite($fp, $char);

		if($bytes_written === false)
		{
			fclose($fp);
			return -4;
		}
	
		$sum_bytes_written += $bytes_written;
	
		if($sum_bytes_written >= $size)
		{
			fclose($fp);
			return "File '$file_with_path' with '$sum_bytes_written' bytes written. ";
		}
	
	} while(true);
}

$sizes_bytes = array(100, 200, 400, 600, 800);
$sizes_kbytes = array(1, 2, 4, 6, 8, 10, 20, 40, 60, 80, 100, 200, 400, 600, 800);

foreach($sizes_bytes as $bytes)
{
	$result = generate_random_file_content($bytes);
	echo $result."\n";
	if($result < 0)
		break;
}

if(!($result < 0))
{
	foreach($sizes_kbytes as $kbytes)
	{
		$result = generate_random_file_content($kbytes, "k");
		echo $result."\n";
		if($result < 0)
			break;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
*