Я пытаюсь добавить фотографию профиля пользователя, но проблема заключается в перемещении загруженного файла в целевой каталог из -за FakePath. Удален перегруженный разгрузочный раздел файлов и возврат успеха. < /p>
Я уже провел исследование о FakePath, что это из -за безопасности браузера. Я просто хочу проверить его первым на моем компьютере (Localhost). или чтобы получить это [name] [tmp_name] [size] [type], используя код? < /p>
public function add(array $data)
{
if ($errors = $this->registrator->validateUser($data, false)) {
Response::validationError($errors);
}
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
$profilepic = (string)$data['profile_image'];
// Handle secure profile image upload
$targetDirectory = 'c:/Apache24/AdminLTE/dist/assets/img/usersprofile/';
$imageFileType = strtolower(pathinfo($profilepic, PATHINFO_EXTENSION));
// Generate a unique filename: complete_name_uniqueID.extension
$safeName = preg_replace('/[^A-Za-z0-9]/', '_', $data['username']); // Remove special chars
$uniqueID = uniqid();
$imageName = "{$safeName}_{$uniqueID}.{$imageFileType}";
$targetFile = $targetDirectory . $imageName;
$profilepicsize = getimagesize($profilepic);
// Validate image file size
if ($profilepicsize > 5000000) {
return "File size exceeds the 2MB limit.";
}
//Validate Mime Types
if (!in_array($imageFileType, $allowedTypes)) {
return ['success' => false, 'message' => 'Invalid file type. Only JPG, JPEG, PNG, GIF allowed.'];
}
// Prevent executable file uploads
if (preg_match('/\.(php|html|htm|js|exe|sh)$/i', $profilepic[0])) {
return "Invalid file type.";
}
// Ensure upload directory exists
if (!is_dir($targetDirectory)) {
if (!mkdir($targetDirectory, 0755, true)) {
return "Failed to create upload directory.";
}
}
// Move the uploaded file
if (!move_uploaded_file($profilepic, $targetFile)) {
return "Error uploading the image.";
}
// Insert data into the database
$this->db->insert('users', [
'email' => $data['email'],
'username' => $data['username'],
'password' => $this->hashPassword($data['password']),
'confirmed' => 'Y',
'confirmation_key' => '',
'register_date' => date('Y-m-d H:i:s'),
'profile_image' => $imageName
]);
$this->db->insert('user_details', [
'user_id' => $this->db->lastInsertId(),
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'phone' => $data['phone'],
'address' => $data['address']
]);
Response::success(["message" => trans("user_added_successfully")]);
}
Warning: getimagesize(roundtableandchairs.jpg): Failed to open stream: No such file or directory in C:\Apache24\htdocs\AdminLTE\dist\Script\User.php on line 106
line 106 :
$profilepicsize = getimagesize($profilepic);
< /code>
Замена строки 106 < /p>
$profilepicsize = pathinfo($profilepic, PATHINFO_DIRNAME);
ajax.php
case "addUser":
onlyAdmin();
app('user')->add($_POST['user']);
break;
ajax
Http.submit = function (form, data, success, error, complete) {
Util.removeErrorMessages();
var $submitBtn = $(form).find("button[type=submit]");
if ($submitBtn) {
Util.loadingButton($submitBtn, $submitBtn.data('loading-text') || $_lang.working);
}
$.ajax({
url: "Script/Ajax.php",
type: "POST",
dataType: "json",
data: data,
success: function (response) {
form.reset();
if (typeof success === "function") {
success(response);
}
},
error: error || function (errorResponse) {
Util.showFormErrors(form, errorResponse);
},
complete: complete || function () {
if ($submitBtn) {
Util.removeLoadingButton($submitBtn);
}
}
});
};
jQuery
$("#adduser-form").validate({
rules: {
email: {
required: true,
email: true
},
username: "required",
password: {
required: function () {
return ! editUserMode;
},
minlength: 6
},
password_confirmation: {
required: function () {
return ! editUserMode;
}
}
},
submitHandler: function(form) {
Http.submit(form, getUserFormData(form), function () {
location.reload();
});
}
});
/**
* Builds the create/update user form data.
* @param form
*/
function getUserFormData(form) {
return {
action: editUserMode ? "updateUser" : "addUser",
user: {
user_id: editUserMode ? activeUser : null,
email: form['email'].value,
username: form['username'].value,
password: Util.hash(form['password'].value),
password_confirmation: Util.hash(form['password_confirmation'].value),
profile_image: form['profile_image'],
first_name: form['first_name'].value,
last_name: form['last_name'].value,
address: form['address'].value,
phone: form['phone'].value,
}
};
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... f-fakepath
Перемещение загруженной ошибки файла из -за FakePath [закрыто] ⇐ Jquery
Программирование на jquery
-
Anonymous
1756905746
Anonymous
Я пытаюсь добавить фотографию профиля пользователя, но проблема заключается в перемещении загруженного файла в целевой каталог из -за FakePath. Удален перегруженный разгрузочный раздел файлов и возврат успеха. < /p>
Я уже провел исследование о FakePath, что это из -за безопасности браузера. Я просто хочу проверить его первым на моем компьютере (Localhost). или чтобы получить это [name] [tmp_name] [size] [type], используя код? < /p>
public function add(array $data)
{
if ($errors = $this->registrator->validateUser($data, false)) {
Response::validationError($errors);
}
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
$profilepic = (string)$data['profile_image'];
// Handle secure profile image upload
$targetDirectory = 'c:/Apache24/AdminLTE/dist/assets/img/usersprofile/';
$imageFileType = strtolower(pathinfo($profilepic, PATHINFO_EXTENSION));
// Generate a unique filename: complete_name_uniqueID.extension
$safeName = preg_replace('/[^A-Za-z0-9]/', '_', $data['username']); // Remove special chars
$uniqueID = uniqid();
$imageName = "{$safeName}_{$uniqueID}.{$imageFileType}";
$targetFile = $targetDirectory . $imageName;
$profilepicsize = getimagesize($profilepic);
// Validate image file size
if ($profilepicsize > 5000000) {
return "File size exceeds the 2MB limit.";
}
//Validate Mime Types
if (!in_array($imageFileType, $allowedTypes)) {
return ['success' => false, 'message' => 'Invalid file type. Only JPG, JPEG, PNG, GIF allowed.'];
}
// Prevent executable file uploads
if (preg_match('/\.(php|html|htm|js|exe|sh)$/i', $profilepic[0])) {
return "Invalid file type.";
}
// Ensure upload directory exists
if (!is_dir($targetDirectory)) {
if (!mkdir($targetDirectory, 0755, true)) {
return "Failed to create upload directory.";
}
}
// Move the uploaded file
if (!move_uploaded_file($profilepic, $targetFile)) {
return "Error uploading the image.";
}
// Insert data into the database
$this->db->insert('users', [
'email' => $data['email'],
'username' => $data['username'],
'password' => $this->hashPassword($data['password']),
'confirmed' => 'Y',
'confirmation_key' => '',
'register_date' => date('Y-m-d H:i:s'),
'profile_image' => $imageName
]);
$this->db->insert('user_details', [
'user_id' => $this->db->lastInsertId(),
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'phone' => $data['phone'],
'address' => $data['address']
]);
Response::success(["message" => trans("user_added_successfully")]);
}
Warning: getimagesize(roundtableandchairs.jpg): Failed to open stream: No such file or directory in C:\Apache24\htdocs\AdminLTE\dist\Script\User.php on line 106
line 106 :
$profilepicsize = getimagesize($profilepic);
< /code>
Замена строки 106 < /p>
$profilepicsize = pathinfo($profilepic, PATHINFO_DIRNAME);
[b] ajax.php[/b]
case "addUser":
onlyAdmin();
app('user')->add($_POST['user']);
break;
[b] ajax [/b]
Http.submit = function (form, data, success, error, complete) {
Util.removeErrorMessages();
var $submitBtn = $(form).find("button[type=submit]");
if ($submitBtn) {
Util.loadingButton($submitBtn, $submitBtn.data('loading-text') || $_lang.working);
}
$.ajax({
url: "Script/Ajax.php",
type: "POST",
dataType: "json",
data: data,
success: function (response) {
form.reset();
if (typeof success === "function") {
success(response);
}
},
error: error || function (errorResponse) {
Util.showFormErrors(form, errorResponse);
},
complete: complete || function () {
if ($submitBtn) {
Util.removeLoadingButton($submitBtn);
}
}
});
};
[b] jQuery [/b]
$("#adduser-form").validate({
rules: {
email: {
required: true,
email: true
},
username: "required",
password: {
required: function () {
return ! editUserMode;
},
minlength: 6
},
password_confirmation: {
required: function () {
return ! editUserMode;
}
}
},
submitHandler: function(form) {
Http.submit(form, getUserFormData(form), function () {
location.reload();
});
}
});
/**
* Builds the create/update user form data.
* @param form
*/
function getUserFormData(form) {
return {
action: editUserMode ? "updateUser" : "addUser",
user: {
user_id: editUserMode ? activeUser : null,
email: form['email'].value,
username: form['username'].value,
password: Util.hash(form['password'].value),
password_confirmation: Util.hash(form['password_confirmation'].value),
profile_image: form['profile_image'],
first_name: form['first_name'].value,
last_name: form['last_name'].value,
address: form['address'].value,
phone: form['phone'].value,
}
};
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79754238/moving-uploaded-file-error-becasue-of-fakepath[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия