2017-01-25 15 views
1

テンポラリアップロードフォルダにあるすべてのファイルの名前を変更し、ファイル名に一意のID参照番号を付けてから、名前を変更した後に増加すると思われる接尾辞_xが続きますファイル名にmyidnumber_1.jpg, myidnumber_2.jpg, etc.PHP - テンポラリフォルダ内のファイルの名前を変更する

などの問題があります。問題は、私のコードでは、renameコマンドが好きではないようだが、ファイル拡張子を保持していないということです。これに対処する方法に関する提案はありますか?

// Get array of all files in temp folder and rename 
$check_folder = scandir("../../pages/fo_dmlog/attachments/".$_SESSION['Holidex']."/temp/".$_SESSION['myusername']."/"); 
$n = 1; 

foreach ($check_folder as $check_file) { 
    if (in_array($check_file, array(".",".."))) continue; 

    $newName = str_replace($check_file,$logID."_".$n,$check_file); 
    rename($check_folder . $check_file, $check_folder . $newName); 

    echo "Attachment: $check_file<br>"; 
    $n++; 
} 

EDIT:フィードバックのための

// Get array of all files in temp folder and rename 
$check_folder = scandir("../../pages/fo_dmlog/attachments/".$_SESSION['Holidex']."/temp/".$_SESSION['myusername']."/"); 
$logID = "132456"; 
$n = 1; 

foreach ($check_folder as $check_file) { 
    if (in_array($check_file, array(".",".."))) continue; 

    $extension = end(explode(".", $check_file)); 
    $newName = str_replace($check_file,$logID."_".$n.$extension,$check_file); 
    rename($check_folder . $check_file, $check_folder . $newName); 

    // instead of rename, can also move the files right away 
    //move_uploaded_file($newName, "../".$logID."/" .$newName); 

    echo "Attachment: $newName<br>"; 
    $n++; 
} 
+0

1.それは、絶対ファイルパスで作業する方が良いでしょう。 2.あなたはどこかで定義されていない変数 '$ logID'を使用しています。 3.以前の不思議な変数( '$ logID')+" _ "と数字で完全なファイル名(拡張子を含む)を置き換えます。最初にファイル拡張子を保存してから、ファイルの名前を変更した後に追加する必要があります。 –

+0

Btw、このスクリプトを実行するたびにすべてのファイルの名前を変更していますか? –

+0

1.スクリプトを実行するたびにすべてのファイルの名前を変更しないでください。アップロード後にmove_uploaded_fileを使用してください。2.一部のパスにすべてのファイルの名前を変更したい場合は、bashスクリプトを使用してPHPから呼び出すことをお勧めします。 – Arkowsky

答えて

1

おかげで、次のコードは動作します:

// Get array of all files in temp folder and rename 
$dir = "../../pages/fo_dmlog/attachments/".$_SESSION['Holidex']."/temp/".$_SESSION['myusername']."/"; 
$check_folder = scandir($dir); 
$n = 1; 

foreach ($check_folder as $check_file) { 
    if (in_array($check_file, array(".",".."))) continue; 

    $extension = end(explode(".", $check_file)); 
    $newName = str_replace($check_file,$n.'.'.$extension,$check_file); 
    rename($dir . $check_file, $dir . $newName); 

    // instead of rename, can also move the files right away 
    //move_uploaded_file($newName, "../".$log_ID."/" .$newName); 

    echo "Attachment: $newName<br>"; 
    $n++; 
} 
+1

_Suggestion:_拡張子を取得するクリーナーな方法: '$ extension = pathinfo($ filename、PATHINFO_EXTENSION);'。 –

+0

喜んで撮影。これはパフォーマンスに影響しますか? – Armitage2k

+0

私はそれをテストしていませんが、私はその目的のために設計された関数を使うことは、分割して(したがって、新しい配列を作成する)、最後のインデックスをフェッチするよりも良いと思います。しかし私が言ったように、私はそれについてのベンチマークを何もしていない。とにかく、おそらくマイクロ最適化になるでしょう。 –

関連する問題