开发者

Generating a random file name using while()?

开发者 https://www.devze.com 2023-04-04 12:44 出处:网络
I\'m using a while() loop to create a rand开发者_JAVA百科om file name, check it against a database, then if it already exists, loop. I\'m just a little worried my syntax/usage is off, as I\'ve only do

I'm using a while() loop to create a rand开发者_JAVA百科om file name, check it against a database, then if it already exists, loop. I'm just a little worried my syntax/usage is off, as I've only done this once before ages ago, and haven't used a while() loop in this way since then.

Here's my code:

$i = 0;
while(++$i) {
    $file_name = md5(mt_rand(0,9999999)) . ".php";
    $result = mysql_query("SELECT * FROM x WHERE file_name = '{$file_name}'");

    if(mysql_num_rows($result) == 0) { break; } else { continue;}
}

Would this work, and if not, what's wrong with it?

I know it's a petty question, but testing out whether or not this would work seems a lot more "tasky" (need to create a new table, alter the file name to choose from 1 - 3 things, display a message instead of continue etc.

Any help, as always, would be appreciated!


You don't need $i, since you're not using it, and you don't need to continue in a loop - the loop will automatically loop, that's what it does. You only need to break when you reach the condition under which you want to end the loop:

while(true) {
    $file_name = md5(mt_rand(0,9999999)) . ".php";
    $result = mysql_query("SELECT * FROM x WHERE file_name = '{$file_name}'");

    if (mysql_num_rows($result) == 0) break;
}

You're using hashes in a slightly broken way though. You should be generating a random string longer than an MD5 hash, not shorter. Right now you only have 10,000,000 possible filenames (0..99999999) instead of the full 2^128 that a MD5 can produce. Instead of worrying about hash collisions in a space as large a 2^128, you have a much higher chance of simply generating the same numbers twice, causing multiple trips to the database.


I know it's a petty question, but testing out whether or not this would work seems a lot more "tasky" (need to create a new table, alter the file name to choose from 1 - 3 things, display a message instead of continue etc.

Taking the approach that the code does is also more "tasky" than necessary. It's workable, but why not let the database do the "create a unique file ID" work for you?

Define the file_name column in x to instead be a file_id column which is bigint(20) auto_increment or something like that. Then in the PHP code, issue a query to create a new row, grab the guaranteed-unique numeric ID, and transform it into a file name.


This will work but you can change the line: while(++$i) into while(true)

0

精彩评论

暂无评论...
验证码 换一张
取 消