如何在文件上载脚本中重命名图像文件名?

时间:2016-07-17 22:22:11

标签: php

我无法弄清楚如何在我拥有的文件上传脚本中重命名文件名。

真的很感谢任何帮助!!

以下是我正在处理的脚本。

<?php
$target_dir = "../user_profile_pictures/";
$target_file = $target_dir . basename($_FILES["profile_pic"]["name"]);
$uploadOk = 1;
$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
    echo "Lo siento, el archivo ya existe.";
    $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType !=     "png") {
    echo "Lo siento, solo se permiten imagenes tipo jpg, jpeg o png.";
$uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Lo siento, el imagen no se ha subido.";

    // if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $target_file)) {
        echo "El imagen ". basename( $_FILES["profile_pic"]["name"]). " se ha subido.";
    } else {
        echo "Ha habido un error al subir el archivo.";
    }
}
?>

3 个答案:

答案 0 :(得分:1)

试试这个,我在原始代码中添加了一个newname变量。

<?php
$target_dir = "../user_profile_pictures/";
$target_file = $target_dir . basename($_FILES["profile_pic"]["name"]);
$newname = "chosen-name";
$uploadOk = 1;
$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Lo siento, el archivo ya existe.";
$uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType !=     "png") {
echo "Lo siento, solo se permiten imagenes tipo jpg, jpeg o png.";
$uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Lo siento, el imagen no se ha subido.";

// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"],  $target_dir.$newname)) {
    echo "El imagen ". basename( $_FILES["profile_pic"]["name"]). " se ha subido.";
} else {
    echo "Ha habido un error al subir el archivo.";
}
}
?>

答案 1 :(得分:0)

in move_uploaded_file($ _ FILES [“profile_pic”] [“tmp_name”],$ target_file) 将$ target_file替换为目录和新文件。

'b

答案 2 :(得分:0)

使用rename() 就像这样

Select  Ads_ComputersID, AdTitle, AdDesc, CityID, CategoryID, Price
From [dbo].[Ads_Computers] where CityID in ( Select CityID from [dbo].[Cities] where [StateID] in (select StateID from [dbo].[States] where CountryID=10))