您可以使上传文件成为它自己的类型,它在数据旁边具有所需的方法。这将使使用更加灵活:
$upload = new UploadFile($_FILES['uploadedFile']);
$message = saveInputFile($upload);
echo $message;
function saveInputFile(UploadFile $upload)
{
if ($check->checkFile($upload->getBasename()) == TRUE) {
$message = $upload->moveTo($target_path)
? sprintf('The file %s has been uploaded', $upload->getBasename())
: 'There was an error uploading the file, please try again!'
;
} else {
$message = "can't be saved!";
}
return $message;
}
新类型UploadFile
代表$_FILE
数组中的一个文件,它是一个包装文件上传携带的基本数据和方法的类。这是一些示例代码:
class UploadFile
{
protected $file;
private $filename;
public function __construct(array $file)
{
$this->file = $file;
}
public function hasError()
{
return $this->getProperty('error') !== UPLOAD_ERR_OK;
}
public function getError()
{
return $this->getProperty('error');
}
public function getBasename()
{
return basename($this->getProperty('name'));
}
public function getFilename()
{
return $this->filename;
}
/**
* @param $newName
* @return NULL|SplFileInfo
* @throws BadMethodCallException
*/
public function moveTo($newName)
{
$newName = (string)$newName;
$filename = $this->getFilename();
if ($filename !== NULL) {
throw new BadMethodCallException(sprintf('Upload file (%s) has been already moved (%s).', $this->getBasename(), $filename));
}
$tmpName = $this->getProperty('tmp_name');
if (move_uploaded_file($tmpName, $newName)) {
$this->filename = realpath($newName);
}
return $this->getFileInfo();
}
/**
* @return SplFileInfo|NULL
*/
public function getFileInfo()
{
$filename = $this->getFilename();
if ($filename !== NULL) {
return new SplFileInfo($filename);
}
}
protected function getProperty($name, $default = NULL)
{
if (isset($this->file[$name])) {
return $this->file[$name];
}
return $default;
}
}
随心所欲地使用它。另请参阅PHP 手册中有关文件上传的SplFileInfo
文档,其中记录了数组的结构和PHP 上传错误代码(这很重要)。$_FILE