[英]PHP file upload - rename file
Using www.w3schools.com/php/php_file_upload.asp as a base, I want to upload a file but change the file name to include a field in my form, plus specific test.使用www.w3schools.com/php/php_file_upload.asp作为基础,我想上传一个文件,但更改文件名以在我的表单中包含一个字段,以及特定的测试。
How can I do this?我怎样才能做到这一点? (I very new to this) (我对此很陌生)
EG.例如。 file name being uploaded = TestFile.jpeg正在上传的文件名 = TestFile.jpeg
I want the file renamed to be [first_name field in form]_invoice.jpeg我希望文件重命名为 [first_name field in form]_invoice.jpeg
This is my form:这是我的表格:
<form action="upload.php" method="post" enctype="multipart/form-data">
First name
<input type="text" name="first_name" id="first_name" />
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
This is my PHP:这是我的 PHP:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "pdf" && $imageFileType != "txt" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only PDF, TXT, JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Change the first lines in the the code like this:像这样更改代码中的第一行:
<?php
$target_dir = "uploads/";
$imageFileType = strtolower(pathinfo($_FILES["fileToUpload"]["name"],PATHINFO_EXTENSION));
$target_file = $target_dir . trim($_POST['your_name']) . '_invoice.' . $imageFileType;
$uploadOk = 1;
But you should also have to have <input type="text" name="your_name">
in your form because according your code and the article , there's no text-typed input.但是您还应该在表单中包含<input type="text" name="your_name">
因为根据您的代码和文章,没有文本输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.