tags:

views:

55

answers:

3

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

Mike


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

+3  A: 

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
$ 
codaddict
`fseek()` does not alter file size.
jmz
@Downvoter: care to explain?
codaddict
Now that you've edited the code to do an `fwrite()`, it works, but your original answer only mentioned `fseek()`. In the future, you should give the full code, like the edited version, or explain in more detail. The person asking the question doesn't know how to do it, that's why he is asking.
jmz
this fails when i try to create a file bigger than 1GB on a win 2003 server system (i have all rights, and it's NTFS)
Mike
@Mike It's quite possible you do, and you'll never get past 2GB on windows. The fseek php function gets an integer, which is implemented as a signed long (32-bit on windows). Even on Linux you might get some problems; PHP support for large files is somewhat sketchy. If you really need this, you'll probably have to write an extension.
Artefacto
i've researched and i will use EXEC(fsutil file createnew temp.del 1000) to use the included utility "fsutil" that can create a file as big as i care it to be.
Mike
A: 

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:

$fh=open("somefile", 'w');
$size=10245;
$chunk=1024;
while ($size>0) {
   fputs($fh, str_pad('', min($chunk,$size)));
   $size-=$chunk;
}
flcose($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.

symcbean
A: 

Check this link

http://www.phpeasystep.com/phptu/3.html

You will get some idea in this.

Karthik