Бакрин Андрей
24 сент. 2014 г., 7:28

Загрузка фото в профиль пользователя

Здравствуйте. Возникла идея загрузить в профиль пользователя не одно, а несколько изображений. В связи с чем для этих целей была выбрана идея сохранения путей к фото в дополнительные поля профиля extended. Плюсом такого решения видится возможность автоматического создания полей, соответствующее количеству загружаемых фотографий. Для загрузки фото на сервер используется сниппет:
<php $modx->log(modX::LOG_LEVEL_ERROR,'Start of script-'); // initialize output; $output = true; // get the current user name to for dicroty placement $userName = $modx->user->get('username'); // valid extensions $ext_array = array('jpg', 'jpeg', 'gif', 'png'); // create unique path for this form submission $uploadpath = 'assets/userfiles/' . $userName .'/'; // get full path to unique folder $target_path = $modx->config['base_path'] . $uploadpath; // get uploaded file names: $submittedfiles = array_keys($_FILES); //get exsisting user profile data for Profile_Photos $fields = $modx->user->getOne('Profile')->get('extended'); $Photo_fields = $fields['Profile_Photos']; $modx->log(modX::LOG_LEVEL_ERROR,'what is the user profile photo -'.$fields['Profile_Photos']); $modx->log(modX::LOG_LEVEL_ERROR,'linsting var is the user profile photo -'.$Photo_fields); // 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 $modx->log(modX::LOG_LEVEL_ERROR,'in for loop file namnes are?-'.$filename ); if($filename != '') { $modx->log(modX::LOG_LEVEL_ERROR,'in file name loop'.$filename); // is this the right type of file? if(in_array($ext, $ext_array)) { //create file called the filename that has been sanitized $modx->log(modX::LOG_LEVEL_ERROR,'before sanitization'.$filename); $filename = strtolower(preg_replace("/[^A-Za-z0-9.]+/i", "-", $filename)); //$filename = $filename . '.'.$ext ; $modx->log(modX::LOG_LEVEL_ERROR,'after sanitization and.ext'.$filename); // 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); if(file_exists($myTarget)) { chmod($myTarget,0755); //Change the file permissions if allowed unlink($myTarget); //remove the file } // 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) $hook->setValue($sf, $uploadpath . $filename); // set the permissions on the file if (!chmod($myTarget, 0644)) { /*some debug function*/ } } else { // File not uploaded $modx->log(modX::LOG_LEVEL_ERROR,'here was a problem uploading the file? -'.$Photo_fields); $errorMsg = 'There was a problem uploading the file.'; $hook->addError($sf, $errorMsg); $output = false; // generate submission error } } else { // File type not allowed $modx->log(modX::LOG_LEVEL_ERROR,'Type of file not allowed. -'.$Photo_fields); $errorMsg = 'Type of file not allowed.'; $hook->addError($sf, $errorMsg); $output = false; // generate submission error $modx->log(modX::LOG_LEVEL_ERROR,'generate submission error'); } $modx->log(modX::LOG_LEVEL_ERROR,'Completed we have a valif photo name'.$Photo_fields); $modx->log(modX::LOG_LEVEL_ERROR,'Completed we have a valif file name'.$filename); } // if no file, don't error, but return blank else { $modx->log(modX::LOG_LEVEL_ERROR,'filename is blank -'.$filename); $modx->log(modX::LOG_LEVEL_ERROR,'before the $Photo_fields != if-'.$Photo_fields); //return exsisting photofields value if ($Photo_fields != '') { $modx->log(modX::LOG_LEVEL_ERROR,'in the $Photo_fields != if-'.$Photo_fields); $modx->log(modX::LOG_LEVEL_ERROR,'Completed using already entered Photo_fields-'.$Photo_fields); $hook->setValue($sf, $Photo_fields); } else{ // is the file name empty (no file uploaded) and exsiting photofields empty $hook->setValue($sf, ''); $modx->log(modX::LOG_LEVEL_ERROR,'at a last else hook should have a no known value for photofields -'.$Photo_fields); $modx->log(modX::LOG_LEVEL_ERROR,'file anem should be blank as well..... -'.$filename); } } } return $output;
Сама же форма для загрузки обычная с
input type="file"
JS скриптом добавляем количество полей для загрузки, столько сколько необходимо. И тут возникла проблема. Информация из формы сохраняется массивом у полей для загрузки
name="user_photo[]"
И при загрузке, в дополнительное поле профиля ничего не записалось. Кроме того, ничего и не загрузилось на сервер. В связи с этим вопрос - проблема ли это сниппета для загрузки или проблема того, что ModX не сохраняет в дополнительное поле массив? Есть ли пути решения данного вопроса?
А при чем тут MODX? У вас обработчик формы на чистом php (я уже не буду придираться к самому коду, это не суть), его и копайте. Делаем print_r($_FILES) и смотрим что там вообще в переданных данных есть, и копаем далее.
Как бы есть переживания по поводу того, сохраняет ли ModX в дополнительное поле массив, судя по всему сохраняет. Буду копать обработчик.
Сначала надо разобраться есть ли там массив вообще, обрабатываются ли загруженные файлы и т.д. и т.п., а только потом уже смотреть сохраняется ли массив. И массив проверить просто
$data = array(.......); $modx->user->Profile->set('extended', $data); $modx->user->save();
И смотрим в БД. Там должна быть сериализованная строка.

Добавить комментарий