我在oop class.php文件上工作。我想实现__contruct()函数。我不知道为什么它不起作用。
我认为有错误,但我不知道如何编写。 $args['file_upload'] = $_FILES['file_upload'][''] ?? NULL;
谢谢。
fileupload.class.php
public function __construct($string){
$this->filename = $_FILES['$string']['name']['0'];
$this->temp_path = $_FILES['$string']['tmp_name']['0'];
$this->type = $_FILES['$string']['type']['0'];
$this->size = $_FILES['$string']['size']['0'];
}
public function create() {
if(move_uploaded_file....
}
fileupload.php
if(is_post_request()) {
//Create record using post parameters
$args = [];
$args['prod_name'] = $_POST['prod_name'] ?? NULL;
$args['file_upload'] = $_FILES['file_upload'][''] ?? NULL;
$image = new Imageupload($args);
$result = $image->create();
if($result === true) {
$new_id = $image->id;
$_SESSION['message'] = 'The image was uploaded.';
} else {
// show errors
}
} else {
// display the form
$image = [];
}
<p><input name="file_upload[]" type="file" id="file_upload[]" value=""></p>
<p>Product name: <input type="text" name="prod_name" value="" /></p>
UPDATE1函数有效
public function add_files() {
$this->filename = $_FILES['file_upload']['name']['0'];
$this->temp_path = $_FILES['file_upload']['tmp_name']['0'];
$this->type = $_FILES['file_upload']['type']['0'];
$this->size = $_FILES['file_upload']['size']['0'];
}
$image = new Imageupload($args);
$image->add_files();
最佳答案
看起来您正在重新创建轮子? :)
尝试为此目的创建一个库。
https://github.com/brandonsavage/Upload
在您的操作系统中安装composer并在命令行中运行以下命令
composer require codeguy/upload
HTML
<form method="POST" enctype="multipart/form-data">
<input type="file" name="foo" value=""/>
<input type="submit" value="Upload File"/>
</form>
的PHP
<?php
$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);
// Optionally you can rename the file on upload
$new_filename = uniqid();
$file->setName($new_filename);
// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$file->addValidations(array(
// Ensure file is of type "image/png"
new \Upload\Validation\Mimetype('image/png'),
//You can also add multi mimetype validation
//new \Upload\Validation\Mimetype(array('image/png', 'image/gif'))
// Ensure file is no larger than 5M (use "B", "K", M", or "G")
new \Upload\Validation\Size('5M')
));
// Access data about the file that has been uploaded
$data = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
// Try to upload file
try {
// Success!
$file->upload();
} catch (\Exception $e) {
// Fail!
$errors = $file->getErrors();
}
关于php - PHP oop(__construct)文件上传,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59248046/