Помогите дать название загружаемым файлам

Я не специалист по php, поэтому не знаю даже основ. Очень прошу помочь, если возможно. Я установил снипет для загрузки ресурсов из фронтэнда, но он очень неудобно переназывает файлы, загружаемые манагером. Может кто-то подскажет, как можно в название добавить альяс?
Вот код снипета:
<?php
// initialize output;
$output = true;
$counter = 1;
 
// valid extensions
$ext_array = array('jpg', 'png', 'gif', 'JPG', 'mp3');
$mydir = $modx->user->get('id'); // Path from root that user specifies
 
// create unique path for this form submission
$uploadpath = 'assets/uploads/'.$mydir.'/';
 
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
 
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
 
// loop through files
foreach ($submittedfiles as $sf) {
 
    // Get Filename and make sure its good.
    $filename = basename( $_FILES[$sf]['name'] );
 
    // Get file's extension
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    $ext = mb_strtolower($ext); // case insensitive
 
    // is the file name empty (no file uploaded)
    if($filename != '') {
         
        // is this the right type of file?
        if(in_array($ext, $ext_array)) {
     
            // clean up file name and make unique
            $filename = $counter . '.' . $ext; 
            $filename = str_replace(' ', '_', $filename); // spaces to underscores
            $filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
             
            // full path to new file
            $myTarget = $target_path . $filename;
             
            // create directory to move file into if it doesn't exist
            mkdir($target_path, 0755, true);
             
            // is the file moved to the proper folder successfully?
            if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                // set a new placeholder with the new full path (if you need it in subsequent hooks)
                $myFile = $uploadpath . $filename;
                $hook->setValue($sf,$myFile);
                // set the permissions on the file
                if (!chmod($myTarget, 0644)) { /*some debug function*/ }
                 
            } else {
                // File not uploaded
                $errorMsg = 'There was a problem uploading the file.';
                $hook->addError($sf, $errorMsg);
                $output = false; // generate submission error
            }
         
        } else {
            // File type not allowed
            $errorMsg = 'Type of file not allowed.';
            $hook->addError($sf, $errorMsg);
            $output = false; // generate submission error
        }
     
    // if no file, don't error, but return blank
    } else {
        $hook->setValue($sf, '');
    }
$counter = $counter + 1;
}
return $output;
Заранее благодарен всем, кто откликнется.
Сергій
18 апреля 2015, 14:58
modx.pro
1 265
0

Комментарии: 2

Abu
Abu
19 апреля 2015, 21:43
0
Ну имя файла формируется тут

// clean up file name and make unique
            $filename = $counter . '.' . $ext; 
            $filename = str_replace(' ', '_', $filename); // spaces to underscores
            $filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
изменяй его как хочешь, что за альянс не совсем понял — если ресурс создан, вместо вышеперечисленного, как-то так
$filename = $modx->resource->get('pagetitle');
хотя штамп надо поставить наверное, для дублей
$filename = date(«Y-m-d_G-i-s_»). $filename; // add date & time
Ну или какой нибудь индекс сделать
    Сергій
    22 апреля 2015, 16:01
    0
    Спасибо. Я уже понял, что ничего не получится, потому что этот файл загружается раньше, чем создается ресурс, к которому он потом прикрепляется. А я хотел, чтобы в названии файла присутствовало поле ЧПУ ресурса, но потом понял, что лучше ID. Но в любом случае это не получится сделать по описанной уже выше причине.
    Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
    2