Php图像上传:更改图像名称

时间:2014-12-22 01:36:56

标签: php sql image mysqli image-uploading

我有一个图片上传表单,可以将图片上传到数据库。

这是我使用的代码,它为每个图像生成一个随机值,这要归功于下面的技巧。

$name = "cover".rand(1,1000000).".jpg"; // generates random image name

但是,如果上传的文件不是.jpg,该怎么办?它可以是png,gif或任何其他图像文件。如何将文件扩展名动态添加到图像的末尾?

我还想使用更强的随机函数函数,我应该使用什么样的函数为每个图像赋一个唯一的值?

表格

<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
    <input type="hidden" name="MAX_FILE_SIZE" value="350000">
    <input name="picture" type="file" id="picture" size="50">
    <input name="upload" type="submit" id="upload" value="Upload Picture!">
</form>

upload.php的

<?php
// if something was posted, start the process... 
if (isset($_POST['upload'])) {

// define the posted file into variables 
    $name = $_FILES['picture']['name'];
    $tmp_name = $_FILES['picture']['tmp_name'];
    $type = $_FILES['picture']['type'];
    $size = $_FILES['picture']['size'];

// if your server has magic quotes turned off, add slashes manually 
    if (!get_magic_quotes_gpc()) {
        $name = addslashes($name);
    }

// open up the file and extract the data/content from it 
    $extract = fopen($tmp_name, 'r');
    $content = fread($extract, $size);
    $content = addslashes($content);
    fclose($extract);

// connect to the database 
    include "../cn/connect.php";

   $name = "cover".rand(1,1000000).".jpg"; // generates random image name

// the query that will add this to the database 
    $stmt = $sqli->prepare("INSERT INTO image1(name, type, size) VALUES (?,?,?)");
    $stmt->bind_param("sss", $name, $_FILES['picture']['type'], $_FILES['picture']['size']);
    $stmt->execute();
    $stmt->close();
    echo "Mission has been completed, sir!";

    if (!empty($_FILES)) {
        $target = "upload/";
        $target = $target . basename($_FILES['picture']['name']);
        $ok = 1;
        $picture_size = $_FILES['picture']['size'];
        $picture_type = $_FILES['picture']['type'];
        //This is our size condition 
        if ($picture_size > 5000000) {
            echo "Your file is too large.<br>";
            $ok = 0;
        }


        //This is our limit file type condition 
        if ($picture_type == "text/php") {
            echo "No PHP files<br>";
            $ok = 0;
        }

        //Here we check that $ok was not set to 0 by an error 
        if ($ok == 0) {
            Echo "Sorry your file was not uploaded";
        } //If everything is ok we try to upload it
        else {
            if (move_uploaded_file($_FILES['picture']['tmp_name'], $target)) {
                echo "The file " . basename($_FILES['picture']['name']) . " has been uploaded <br/>";
            } else {
                echo "Sorry, there was a problem uploading your file.";
            }
        }
    }

    echo "Successfully uploaded your picture!";
} else {
    die("No uploaded file present");
}

?>

1 个答案:

答案 0 :(得分:1)

不会

$type = $_FILES['picture']['type'];

告诉你它是什么类型的文件?只需使用它来附加(有效)正确的文件格式。