benhall14/php-upload

一个PHP上传类,使处理上传和验证更快、更简单。

dev-master 2019-11-04 16:51 UTC

This package is auto-updated.

Last update: 2024-09-05 02:57:05 UTC


README

一个PHP类,使处理上传和文件验证变得非常简单。您可以使用链式方法来设置上传参数,如最小/最大文件大小、MIME类型和文件扩展名。一旦设置完毕,您只需简单地将 ignition(). 开启即可。

对于更高级的上传选项,此类允许您添加回调并遍历等待上传的文件以执行自己的验证和检查。

测试表明与 PHP 5.6 和 PHP 7. 兼容。

使用composer安装

现在您可以使用composer安装上传类

$ composer require benhall14/phpUpload

请确保包含composer自动加载器并使用正确的命名空间。

require 'vendor/autoload.php';

use benhall14\phpUpload\Upload as Upload;

API选项

->version()

version() 方法将返回类版本。

$upload->version();

->submitted()

submitted() 方法将根据选定的输入元素是否已提交返回 truefalse

$upload->submitted();

->setMessages()

您可以通过将自定义消息数组传递给 setMessages() 方法来覆盖默认消息。

$upload->setMessages($custom_messages);

默认消息是

$messages = [
    # When the file element in the class is invalid.
    'invalid_file_element' => 'Invalid File Element ID', 
    # When no files have been selected for upload.
    'nothing_uploaded' => 'No files have been selected to upload.', 
    # When the destination path is invalid.
    'invalid_destination' => 'Invalid Destination Path', 
    # When the upload path could not be created.
    'could_not_create_path' => 'The %s doesn\'t exist and could not be created.', 
    # When the file element is missing from the __construct() method.
    'file_input_missing' => 'The file id %s is missing from the upload form.', 
    # When the uploaded file(s) don't fit the criteria for the minimum file size.
    'too_small' => 'Too small', 
    # When the uploaded file(s) don't fit the criteria for the maximum file size.
    'too_large' => 'Too large', 
    # When the uploaded file(s) don't fit the criteria for the allowed mime types.
    'invalid_mime' => 'Invalid mime type uploaded (%s). Allowed mime types are: %s.', 
    # When the uploaded file(s) don't fit the criteria for the allowed file extensions.
    'invalid_ext' => 'Invalid file type uploaded (%s). Allowed file types are: %s.', 
    # When the uploaded file(s) could not be moved due to a server or permission error.
    'upload_move_error' => 'The file could not be uploaded: Permission Error', 
    # When the destination path set does not exist and/or could not be created.
    'destination_missing' => 'The destination path configuration setting is missing.', 
];

->getAllowedExtensions()

这将返回当前允许的文件扩展名列表。

$extensions = $upload->getAllowedExtensions();

->setAllowedFileExtensions()

这是一个基本但不太安全的方法,用于匹配上传的文件扩展名与预定义的允许扩展名列表。允许的文件类型可以是文件扩展名数组 array('jpg', 'png', 'gif'),管道分隔的列表 'jpg|png|gif',或通配符字符串 '*'

$upload->setAllowedFileExtensions('jpg|png|gif');
# or
$upload->setAllowedFileExtensions('*');
# or
$upload->setAllowedFileExtensions(array('jpg', 'png', 'gif'));

->setAllowedMimeTypes()

这是一个更安全的方法,用于匹配上传的文件MIME类型与预定义的允许MIME类型列表。允许的MIME类型可以是MIME类型数组 array('image/jpg', 'image/png') 或通配符字符串 '*'

# to allow all types
$upload->setAllowedMimeTypes('*');

# to only allow jpg and png images.
$upload->setAllowedMimeTypes(array('image/jpg', 'image/png'));

->getAllowedMimeTypes()

这将返回当前允许的MIME类型列表。

$mime_types = $upload->getAllowedMimeTypes();

->getMaxFileSize()

这将返回当前最大文件大小(以字节为单位)。

$size = $upload->getMaxFileSize();

->setMaxFileSize($maximum_file_size = false, $type = 'b')

这将设置允许上传的最大大小。第一个参数是整数大小,第二个参数是类型 - 例如 b、kb、mb 或 gb。

$upload->setMaxFileSize(10, 'mb');

->getMinFileSize()

这将返回当前最小文件大小(以字节为单位)。

$size = $upload->getMaxFileSize();

->setMinFileSize($minimum_file_size = false, $type = 'b')

这将设置允许上传的最小大小。第一个参数是整数大小,第二个参数是类型 - 例如 b、kb、mb 或 gb。

$upload->setMinFileSize(1, 'mb');

->setDestinationPath($path = false)

设置上传的目标路径。它可以是绝对路径或脚本相对路径。

$upload->setDestinationPath('uploads/');

->setExtensionAs($extension = null)

强制上传文件使用传递的 $extension。这不会更改MIME类型 - 只会强制新的文件扩展名。如果您只想接受某些文件类型 - 例如jpg,它允许强制jpg扩展名。

$upload->setExtensionAs('jpg');

->setName($name = false, $clean = true)

使用 cleanFilename 方法设置覆盖文件名。 这只能用于单个元素文件

$upload->setName('my-image');

->generateName($bool)

设置配置选项以动态创建随机文件名。

$upload->generateNames(true);

->ignition()

这是主要的点火开关。必须在设置所有配置选项之后调用。

这将填充文件计数和内部文件对象。这将启动上传引擎。

$upload->ignition();

->hasErrors()

这将根据是否发生错误返回 truefalse。它可以与 errors() 结合以显示错误列表。

if($upload->hasErrors()){
	foreach($upload->errors() as $error){
		echo '<li>ERROR: ' . $error . '</li>';
	}
}

->errors()

这返回在上传过程中发生的错误数组。它可以与 hasError() 结合使用。

if($upload->hasErrors()){
	foreach($upload->errors() as $error){
		echo '<li>ERROR: ' . $error . '</li>';
	}
}

->isMultiple()

这将返回 truefalse,取决于是否有多个文件正在上传。

$is_multiple = $upload->isMultiple();

->fileCount()

这将返回提交的文件上传数量。

$count = $upload->fileCount();

->debug()

这将为开发和测试打印调试消息。

$upload->debug();

->successes()

这返回成功上传的文件数组。

foreach($upload->successes() as $files){
	echo $file->name . ' has been uploaded';
}

->files()

这返回文件对象数组。如果在上传()之后调用,还将返回上传状态。

foreach($upload->files() as $files){
	echo $file->name;
}

->upload()

这自动执行上传文件的验证和处理,无需额外编码。

$upload->upload();

回调选项

此类的原因是为了提供最简单的方式来处理上传和验证,而无需手动执行所有检查。以下回调方法可以用于高级上传集成。如果您正在寻找简单的集成 - 请参阅上面的 upload()

->each($callback)

each() 接受一个回调,并遍历每个等待上传的文件。

$upload->each(function($file){
	# this will print the file object for each upload found.
	print_r($file);
});

->success($callback)

将回调应用于所有成功上传的文件。

$upload->success(function($file){
	echo $file->name . ' has been successfully uploaded.';
});

->error($callback)

将回调应用于所有发生错误的上传。

$upload->error(function($file){
	echo $file->name . ' could not be uploaded due to an error.';	
});

->validate($file)

在提供的 $file 上运行验证方法。这用于 each() 回调中。

$upload->each(function($file){
	$isValid = $this->validate($file);
});

->process($file)

在提供的 $file 上运行实际的上传。这用于 each() 回调中。

$upload->each(function($file){
	$isValid = $this->validate($file);
	if($isValid){
		$this->process($file);
	}
});

#$file 所有返回 $file 对象的方法将具有以下属性。

$file->id; # The id of the upload.
$file->source->path; # the source tmp_path
$file->source->filename; # the source file name
$file->source->extension; # the source file extension
$file->source->name; # the source file name
$file->source->size; # the source size
$file->source->type; # the source type from $_FILES
$file->source->mime_type; # the source mime type
$file->source->error; # the $_FILES error.
$file->destination->size; # the destination file size
$file->destination->mime_type; # the destination mime type
$file->destination->extension; # the destination file extension
$file->destination->filename; # the destination file nameof
$file->destination->path; # the destination file path
$file->success # returns boolean true/false
$file->isValid # returns boolean true/false

示例:简单上传

在这个示例中,我们展示了上传器的最简单形式。我们使用以下 HTML 代码

<!DOCTYPE html>
<html>
	<body>
		<form method="post" enctype="multipart/form-data">
		    Select image to upload:
		    <input type="file" name="image_upload[]" id="image_upload">
		    <input type="file" name="image_upload[]" id="image_upload">
		    <input type="file" name="image_upload[]" id="image_upload">
		    <input type="file" name="image_upload[]" id="image_upload">
		    <input type="submit" value="Upload Image" name="submit">
		</form>
	</body>
</html>

PHP

try {
	$upload = new Upload('image_upload');

	if ($upload->submitted()) {
		$upload
			->setDestinationPath('uploads/') 
			->setAllowedMimeTypes(array('image/jpg', 'image/jpeg', 'image/png', 'text/plain'))
			->setMaxFileSize(2, 'mb')
			->ignition()
			->upload();

		if ($upload->hasErrors()) {
			# loop through each file that has error'd
			foreach ($upload->errors() as $file) {
				foreach ($file->errors as $error) {
					echo '<li>' . $error . '</li>';
				}
			}
		} else {
			echo 'Upload(s) Complete!';
		}
	}
} catch (Exception $e) {
	die($e->getMessage());
}

示例:高级上传

在这个高级示例中,我们可以展示回调方法。同样,我们使用以下 HTML 代码

<!DOCTYPE html>
<html>
	<body>
		<form method="post" enctype="multipart/form-data">
		    Select image to upload:
		    <input type="file" name="image_upload[]" id="image_upload">
		    <input type="file" name="image_upload[]" id="image_upload">
		    <input type="file" name="image_upload[]" id="image_upload">
		    <input type="file" name="image_upload[]" id="image_upload">
		    <input type="submit" value="Upload Image" name="submit">
		</form>
	</body>
</html>

PHP

try {
    $upload = new Upload('image_upload');

    if ($upload->submitted()) {
		$upload
		    ->setDestinationPath('uploads/')
		    ->setAllowedMimeTypes(array('image/jpg', 'image/jpeg', 'image/png', 'text/plain'))
		    ->setMaxFileSize(2, 'mb')
		    ->ignition();

		$upload->each(function ($file) use ($upload) {
			if ($upload->validate($file)) {

				# we can use $file here and perform additional checks or manipulations.

				# now we process the upload
				if ($upload->process($file)) {
				    echo '<li>' . $file->destination->name . ' has been uploaded <b>SUCCESSFULLY</b>.</li>';
				    
				    return;
				}
			}

			echo '<li><b>ERROR:</b> ' . $file->source->name . ' could not be uploaded.</li>';

			return;
		});
	}
} catch (Exception $e) {
	die($e->getMessage());
}

要求

经过测试,与 PHP 5.6 和 PHP 7 兼容

许可证

版权所有 © Benjamin Hall,ben@conobe.co.uk https://conobe.co.uk

许可协议:MIT

捐赠吗?

如果您认为这个项目在某种程度上对您有帮助或有用,请考虑为我买一杯咖啡 - 真心感谢 :)

Donate