Могу ли я использовать поле формы для переименования файла загружаемого изображения?

У меня есть поле «Загрузить файл» в моей форме, чтобы посетители моего сайта могли загружать изображения.

    <input type="file" name="fileToUpload" id="fileToUpload">

В настоящее время файл сохраняется на моем сервере с тем же именем, с которым он был загружен.

Я хотел бы добавить поле ввода в мою форму (как показано ниже), чтобы пользователь мог ввести новое «имя» для файла [image].

    <input name="imageRename" id="imageRename">

Мне нужен совет по изменению текущего php-кода для переименования файла перед его сохранением на моем сервере.

Вот текущий код php для обработки изображений:

    <?php
$target_dir = "articles/article-images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"]))
{
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false)
{
echo "". $check[""].""; $uploadOk = 1;
}
else
{
echo "&#xd7; FILE IS NOT AN IMAGE"; $uploadOk = 0;
}
}
if(file_exists($target_file))
{
echo "&#xd7; THIS IMAGE ALREADY EXIST ON SERVER"; $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000)
{
echo "&#xd7; FILE IS TOO LARGE"; $uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
echo "&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED"; $uploadOk = 0;
}
if ($uploadOk == 0)
{
echo "&#xd7; IMAGE WAS NOT UPLOADED";
}
else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo '<img class="fixed-ratio-resize" src="../../articles/article-images/'. basename( $_FILES["fileToUpload"]["name"]). '">';
}
else
{
echo "&#xd7; IMAGE WAS NOT UPLOADED";
}
}
?>

2

Решение

Пример для моего комментария:

файл для загрузки вызова image_10.jpg

имя файла, который вы хотите imag_xpto.jpg

код для изменения:

$target_dir = "articles/article-images/";
$target_new_name = "imag_xpto.jpg";
//your code...
$target = $target_dir.$target_new_name;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
//Your code...

Если вы хотите, чтобы поле давало новое имя, вам нужно всего лишь создать поле ввода в html и использовать этот код для его получения.

код для поста:

HTML:

<input type =  "text" name = "inputfieldname">

PHP:

$target_new_name = $_POST['inputfieldname'];

Ваш код с некоторыми советами по отладке и улучшению Вашего кода

<?php

if(isset($_POST["submit"]))
{
$target_new_name = $_POST["inputfieldname"]; //you can and you should  protect, if you are sending null or empty or undefined it can cause problems in the future. For protect you can use isset and verify if the name it's null or "".
$target_dir = "articles/article-images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$target_new_file_name =  $target_dir.$target_new_name.".".$imageFileType; // Check with an "error_log($target_new_file_name);" the string "$target_new_file_name". Because it is in the creation of the new string, that the problems occur
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false)
{
echo "". $check[""].""; $uploadOk = 1;
}
else
{
echo "&#xd7; FILE IS NOT AN IMAGE"; $uploadOk = 0;
}
}
//if(file_exists($target_file)) - You should now verify that the new file name exists on the server

if(file_exists($target_new_file_name))
{
echo "&#xd7; THIS IMAGE ALREADY EXIST ON SERVER"; $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000)
{
echo "&#xd7; FILE IS TOO LARGE"; $uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
echo "&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED"; $uploadOk = 0;
}
if ($uploadOk == 0)
{
echo "&#xd7; IMAGE WAS NOT UPLOADED";
}
else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_new_file_name))
{
echo '<img class="fixed-ratio-resize" src="'.$target_new_file_name.'">'; // I'm not really sure about this part of the code, I'm used to another type of html creation in php
}
else
{
echo "&#xd7; IMAGE WAS NOT UPLOADED";
}
}
?>

У меня не было возможности протестировать, поэтому в коде могут быть некоторые ошибки.

Простой способ. Любые вопросы, просто спросите, что я постараюсь ответить

1

Другие решения

Вы должны проверить, что пользователь фактически представил значение для нового имени и если не использовать оригинал (или случайный). Кроме того, вы можете использовать предопределенные характеристики ошибок, найденные в объекте $ _FILES, для облегчения обработки.

<?php

$filefield='fileToUpload';
$textfield='imageRename';

/*
function to return the reason for any failure
*/
function uploaderror( $code ){
switch( $code ) {
case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini";
case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded";
case UPLOAD_ERR_NO_FILE: return "No file was uploaded";
case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder";
case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk";
case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension";
default: return "Unknown upload error";
}
}

/*
test that the required items are present in posted data
*/
if( isset( $_FILES[ $filefield ],$_POST[ $textfield ] ) ){

$target_dir = "articles/article-images/";
$errors=array();

/* set permitted file extensions - not foolproof btw */
$allowed=array('jpg','jpeg','png','gif');

/* get the properties of the uploaded file */
$obj=(object)$_FILES[ $filefield ];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;/*
determine the new name of the file if the user supplied a new name or not
*/
$newname = !empty( $_POST[ $textfield ] ) ? $_POST[ $textfield ] : false;
$ext = pathinfo( $name, PATHINFO_EXTENSION );

$name =( $newname ) ? $newname .= ".{$ext}" : $name;/* no errors so far, proceed with logical tests of your own */
if( $error==UPLOAD_ERR_OK ){

if( !in_array( $ext,$allowed ) ) $errors[]="&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED";
if( $size > 500000 )$errors[]="&#xd7; FILE IS TOO LARGE";
if( !getimagesize( $tmp ) )$errors[]="&#xd7; FILE IS NOT AN IMAGE";
if( !is_uploaded_file( $tmp ) )$errors[]="&#xd7; POSSIBLE FILE UPLOAD ATTACK";if( empty( $errors ) ){
/*
set the new file location
*/
$targetfile = $target_dir . DIRECTORY_SEPARATOR . $name;

/*
save the file
*/
$status = move_uploaded_file( $tmp, $targetfile );

/*
determine what to do if it succeeded or not
*/
if( $status ){
echo '<img class="fixed-ratio-resize" src="../../articles/article-images/'. basename( $name ). '" />';
} else {
exit('error');
}
} else {/* edited: changed commas to periods */
exit( '<pre>'.print_r($errors,1).'</pre>' );
}
} else {
exit( uploaderror( $error ) );
}
}
?>

Вышеописанное работало нормально, когда я проверял это, используя форму ниже — единственное другое отличие — путь к целевому каталогу, который я установил c:\temp\fileuploads в тестовых целях.

    <form id='fileupload' action='/test/so_upload_image_target.php' method='post' enctype='multipart/form-data'>
<h1>Upload an image - test</h1>
<input type='file' name='fileToUpload' />
<input type='text' name='imageRename' value='boobies' />
<input type='submit' />
</form>
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector