我试图通过添加上传者名称($ user)来重命名上传的文件 但它只是在扩展部分显示用户名,file.jpguser,这里是代码,
if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 1.4MB
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
($_FILES["uploaded_file"]["size"] < 10485760))
{
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/affichagesimg/'.$filename'by'.$user;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
echo "<script>
alert('votre affichage a était publié avec succés !');
window.location.href='.';
</script>";
答案 0 :(得分:0)
您需要拆分原始文件名(或use built in functionality)以获取扩展名。例如:
<?php
...
$file_parts = explode('.', $uploaded_filename);
$extension = array_pop($file_parts);
$file_stub = implode('.', $file_parts);
$new_name = $file_stub . 'by' . $user . '.' . $extension;
使用您的代码,新文件名为:
<?php
...
$new_filename = $filename . 'by' . $user . '.' . $ext;
答案 1 :(得分:0)
使用pathinfo功能
$user = 'username';
$filename = $_FILES['uploaded_file']['name'];
$path_parts = pathinfo($filename);
$newname = "{$path_parts['filename']}_by_{$user}.{$path_parts['extension']}";
答案 2 :(得分:0)
您也可以使用pathinfo来解析文件名:
$ file_parts = pathinfo($ uploaded_filename);
$ new_name = $ file_parts ['filename']。'by'。$ user。'。'。$ file_parts ['extension'];