[/tab]Here's the solution. Since you want DIFFERENT file to be created when the script is executed, we have to depend on some very random non-repeating figure to generate the filenames so that they aren't repeated and there' no chance of name collission and files being overwritten. We can use the
microtime() function in php which gives us time resolution finer than a second.
[tab]microtime() returns a string that contains the
microseconds part of the elapsed time since the epoch, a space and seconds since the epoch. For example, a return value of
0.12345678 1234567890 would mean that
1234567890.12345678 seconds have elapsed since the epoch. Here a
string is returned, because the
double type doesn't have enough capacity to hold the entire value and yet maintain the microsecond precision that is required.
CODE
list ( $microsecs, $secs ) = explode ( ' ', microtime () );
[/tab]This will call the microtime() routine and fetch the seconds elapsed since the epoch. The
explode function simply splits the returned value into microsecs and seconds based on the space (' ') in between and stores them into the variables
$microsecs & $secs with help of the list function (which can assign individual values to the variables provided as its parameter from an array). Once we have the values, we can proceed to defining a unique filename. Lets say, we take the name
"Report and append the microseconds part to it - that'd give us a fairly unique filename everytime you run the script. The chances of hitting upon the same filename is about 1/99999999 = 0.00000001 i.e., everytime you access microtime(), you have a chance of 1 in 10 million to arrive upon the same filename - I think you can afford to be pretty happy with the results. Right, lets forge our file name and store it in another variable called
$filename.CODE
$filename = 'Report' . $microsecs . '.txt';
[tab]This just appends your microseconds and ".txt" to the string "Report" giving you a filename like,
Report12345678.txt. Next we go about writing that file out...
CODE
$fh = fopen ( $filename, 'w' ) or die ( "Cannot open $filename for writing. " . $php_errormsg );
.....
// Code to write data to file
.....
fclose ( $fh );
[/tab]That's it - that'll write out whatever you want into this random file and close it - and since we didn't specify any directory for the file to be created in, it happens in the same directory that the script is run from...Now if we put all this code together:
CODE
.....
// Other parts of your script
.....
.......
list ( $microsecs, $secs ) = explode ( ' ', microtime () );
$filename = 'Report' . $microsecs . '.txt';
$fh = fopen ( $filename, 'w' ) or die ( "Cannot open $filename for writing. " . $php_errormsg );
.....
// Code to write data to file
.....
fclose ( $fh );
[tab]This should do - I've checked the code and it worked fine on my system. Try it and let me know if it helped..
All the best

Reply