Question

How can i create in PHP a file with a given size (no matter the content)?

I have to create a file bigger than 1GB. Arround 4-10GB maximum

Was it helpful?

Solution

You can make use of fopen and fseek

define('SIZE',100); // size of the file to be created.
$fp = fopen('somefile.txt', 'w'); // open in write mode.
fseek($fp, SIZE-1,SEEK_CUR); // seek to SIZE-1
fwrite($fp,'a'); // write a dummy char at SIZE position
fclose($fp); // close the file.

On execution:

$ php a.php

$ wc somefile.txt
  0   1 100 somefile.txt
$ 

OTHER TIPS

If the content of the file is irrelevant then just pad it - but do make sure you don't generate a variable too large to hold in memory:

<?php
$fh = fopen("somefile", 'w');
$size = 1024 * 1024 * 10; // 10mb
$chunk = 1024;
while ($size > 0) {
   fputs($fh, str_pad('', min($chunk,$size)));
   $size -= $chunk;
}
fclose($fh);

If the file has to be readable by something else - then how you do it depends on the other thing which needs to read it.

C.

Look my code at bottom

^^ The best feature is here with 0s to create a 4GB file ^^

FUNCTION CreatFileDummy($file_name,$size) {   
// 32bits 4 294 967 296 bytes MAX Size
    $f = fopen($file_name, 'wb');
    if($size >= 1000000000)  {
        $z = ($size / 1000000000);       
        if (is_float($z))  {
            $z = round($z,0);
            fseek($f, ( $size - ($z * 1000000000) -1 ), SEEK_END);
            fwrite($f, "\0");
        }       
        while(--$z > -1) {
            fseek($f, 999999999, SEEK_END);
            fwrite($f, "\0");
        }
    }
    else {
        fseek($f, $size - 1, SEEK_END);
        fwrite($f, "\0");
    }
    fclose($f);

Return true;
}

test it ^^ Max in Php 32bit 4 294 967 296 :

CreatFileDummy('mydummyfile.iso',4294967296);

You want Write , Read and Creat File Dummy my code is here ^^ :

https://github.com/Darksynx/php

Algorithm to Generate a LARGE Dummy File

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top