简体   繁体   中英

Why is this Upload File with Random Name PHP script not working?

I have an upload PHP script and before it uploads the file, it renames it to to a random name, so no files that are already there will be overrided. The problem is that it is not working properly. It is putting in a bunch of weird symbols in the file name, and when I try viewing the file, it has a 404 error. It was working before I added this random name part in. Here's the PHP script that I have right now:

<?php
// Where the file is going to be placed 
$target_path = "files/";

/* Rename file with random name and keep extension */
    $length = 10;
    $characters = ’123456789’;
    $string="";
    for($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
$pos = strrpos(basename( $_FILES['uploadedfile']['name']), ".");
$ext = str_split(basename( $_FILES['uploadedfile']['name']), $pos);
$target_path = $target_path.$string.$ext[1]; 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "<h2>Your file has been uploaded!</h2><br /><p>Your file has been uploaded successfully. <a href='".$target_path."'>Click here</a> to see the file you uploaded.
    <br /><br /><br />
    <h2>A link to your file</h2><br />The full link to your file is:
    <br /><br />
    <code>http://www.example.com/upload/".$target_path."</code></p>";
} else{
    echo "<span class='error'>There was an error uploading the file, please try again.</span>";
}
?>

For some reason, it is really acting weird. Then, when I view the folder /files/ in my hosting file manager and I try deleting a file with the weird symbols in it, and I refresh and they are all back. Take a look at this screenshot:

在此输入图像描述

Weird, huh?

I will probably need a new random naming PHP script, but this is annoying because I delete all of those files, and, what do you know, they come right back when I reload! It's like the PHP is forcing them to not delete or something.

Thanks for any help in advance,
Nathan

You put forwardticks around your string of characters instead of quotes: '123456789' . Changing those to quotes will probably fix your error.

But You should be using tempnam() . A PHP function which generates a random and unique file name, creates a file and returns the file name.

You just specify the folder you want the file in, and a prefix for the filename (only the first three characters are used on Windows), and it does all the "random" for you while guaranteeing uniqueness, so you generating the same random number twice and overwrite a file.

PS. Despite the functions name, the file is not temporary. If you want to delete it you have to do so yourself. You can use unlink() for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM