用PHP重命名$ _FILES(文件)

时间:2015-12-12 08:35:28

标签: php file post

我想知道为什么我的代码不会正确地重命名我的文件。以下是我认为我的代码所做的事情。

  • 从POST
  • 获取;compile with nasm.exe -f elf tutorial4.asm ;gcc -m32 tutorial4.o -o tutorial4.exe global _main extern _printf extern _scanf global _yes_msg global _no_msg section .data msg db "Please say yes or no? [y/n] ", 0 msgy db "You said yes! ", 0 msgn db "You said no! ", 0 yes db 'y', 0 no db 'n', 0 fmt db "%s", 0 section .bss inpt resb 200 section .text _yes_msg: push msgy call _printf add esp, 4 _no_msg: push msgn call _printf add esp, 4 _main: push ebp mov ebp, esp push msg call _printf add esp, 4 push inpt push fmt call _scanf mov eax, inpt mov edx, 'y' cmp eax, edx jne _no_msg jmp _yes_msg add esp, 8 mov esp, ebp pop ebp ret (文件)
  • 将其移至特定文件夹($_FILES
  • 将其重命名为日期格式(我想这样做,以便没有相同名称的文件)


uploads/

非常感谢你。我是PHP的新手,所以如果您有任何其他提示,请随时告诉他们:)

编辑:文件实际上从临时目录移动到目标目录,它不会被重命名。

3 个答案:

答案 0 :(得分:1)

你可以直接替换

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$temps = time();
$target_file = $target_dir . $temps . '.' . $imageFileType;

底部的if / else语句

if ($uploadOk == 0) {
    $_SESSION['error'] = "There was an error uploading your file, please try again !";
    header('location:upload.php');
} else {
    if (!move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $_SESSION['error'] = "There was an error uploading your file, please try again !";
        header('location:upload.php');
    }
}

完整档案。

<?php
session_start();

$target_dir = "uploads/";
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$temps = time();
$target_file = $target_dir . $temps . '.' . $imageFileType;

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {

    } else {
        $_SESSION['error'] = "This is not an image -.-";
        header('location:upload.php');
    }
}

if ($_FILES["fileToUpload"]["size"] > 2000000) {
    $_SESSION['error'] = "The uploaded image must be smaller than 2MB";
    header('location:upload.php');
}

$allowed_extensions = array("jpg", "png", "jpeg", "gif");

if(!in_array($imageFileType, $allowed_extensions)) {
    $_SESSION['error'] = "Sorry, only JPG, PNG & GIF files are allowed";
    header('location:upload.php');
}

if ($uploadOk == 0) {
    $_SESSION['error'] = "There was an error uploading your file, please try again !";
    header('location:upload.php');
} else {
    if (!move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $_SESSION['error'] = "There was an error uploading your file, please try again !";
        header('location:upload.php');
    }
}
?>

答案 1 :(得分:0)

您可以使用以下内容: -

  $arrExtension = @explode('.', $_FILES["fileToUpload"]["name"]);
  $fileName = 'prefix-'. time() . '.' . $arrExtension[1]);

答案 2 :(得分:-1)

文件名不能包含“:”字符。尝试使用其他类似time()的东西,它会返回当前的时间戳,或者只是将你的时间中的“:”字符改为“ - ”。