【问题标题】:Renaming uploaded file重命名上传的文件
【发布时间】:2015-03-16 20:17:02
【问题描述】:

我正在尝试通过添加上传者名称($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>";

【问题讨论】:

  • 你期待什么?你在扩展后添加user
  • 在$filename'by'.$user 中,您肯定缺少.,但也请参阅@u_mulder 的评论。

标签: php file-upload filenames rename


【解决方案1】:

您需要拆分原始文件名(或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;

【讨论】:

  • 你是对的@u_mulder 更新了代码,谢谢!
【解决方案2】:

使用pathinfo函数

$user = 'username';
$filename = $_FILES['uploaded_file']['name'];
$path_parts = pathinfo($filename);
$newname = "{$path_parts['filename']}_by_{$user}.{$path_parts['extension']}";

【讨论】:

    【解决方案3】:

    您也可以使用pathinfo 来解析文件名:

    $file_parts = pathinfo($uploaded_filename);

    $new_name = $file_parts['filename'].'by'.$user.'.'.$file_parts['extension'];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多