Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php create file with given size

Tags:

php

createfile

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

like image 457
Mike Avatar asked Aug 31 '10 11:08

Mike


3 Answers

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
$ 
like image 120
codaddict Avatar answered Nov 18 '22 06:11

codaddict


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.

like image 35
symcbean Avatar answered Nov 18 '22 08:11

symcbean


Late, but it's really easier than the other answers.

$size = 100;
$fp = fopen('foo.dat',"w+");
fwrite($fp,str_repeat(' ',$size),$size);

The w+ will either create the file or overwrite it if it already exists.

For a really big file I usually cheat:

`truncate -s 10g foo.dat`;
like image 1
Danial Avatar answered Nov 18 '22 06:11

Danial