How can I create a random file name

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
andylyon87
Forum Contributor
Posts: 168
Joined: Sat Jan 31, 2004 5:31 am
Location: Dundee

How can I create a random file name

Post by andylyon87 »

I want to create a string that will allow me to write and read from a randomly generated txt file. The problem is that I want it to generate a random file at the beginning and the read and write from that file all the way through. It is for a chat room for my friends.
qads
DevNet Resident
Posts: 1199
Joined: Tue Apr 23, 2002 10:02 am
Location: Brisbane

Post by qads »

Code: Select all

<?php
$str = md5(time().MD5(rand(100, 489754)).time());
?>
andylyon87
Forum Contributor
Posts: 168
Joined: Sat Jan 31, 2004 5:31 am
Location: Dundee

Post by andylyon87 »

would I be able to read and write to a file created by the above code(the file being the same each time). How would I reference this in a writetofile function could I use

Code: Select all

$thefile = "$str.txt"
or

Code: Select all

$thefile = "$str"
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Code: Select all

<?php
$str = md5(time().MD5(rand(100, 489754)).time());
$fp = fopen($str, 'w');
fputs($fp, 'Some test text');
fclose($fp);
echo file_get_contents($str);
?>
andylyon87
Forum Contributor
Posts: 168
Joined: Sat Jan 31, 2004 5:31 am
Location: Dundee

Post by andylyon87 »

Would it be possible to work this into a user form, so that the user inputs the information.
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Sure, you'de basically just replace,
fputs($fp, 'Some test text');
with
fputs($fp, $_POST['usertext']); for example.
Course i left out all the usual validation/error checking etc..etc.., but that's the theory :o
jaxn
Forum Commoner
Posts: 55
Joined: Fri Jan 16, 2004 1:50 pm
Location: Nashville, TN

Post by jaxn »

whoa, why make it so complicated?!?!?

There are functions in PHP for this:
http://www.php.net/tmpfile
http://www.php.net/manual/en/function.tempnam.php

-Jackson
Post Reply