我查看过论坛,找不到与我的问题相符的任何内容。即使在我输入标题时,我也会阅读这些文章 这可能会有点复杂,所以我会尽可能轻松地将其分解。感谢任何想要接受它的人......
我的目标是能够安全地上传文件并使用无用的扩展名重命名具有潜在危险的文件。发生的事情就是每次上传时都会添加$后缀,即使这是保存条件语句的方法:
$nameparts = pathinfo($nospaces);
$extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
if (!$this->typeCheckingOn && !empty($this->suffix)){
if (in_array($extension, $this->notTrusted) || empty($extention)){
$this->newName = $nospaces . $this->suffix;
}
protected function moveFile($file)
{
$result = $file['name']. ' was uploaded successfully';
if (!is_null($this->newName)){
$result .= ', and was renamed ' . $this->newName;
}
}
但这里是重要的代码的完整细分(除了我缺少的是什么)
protected $permittedTypes = array(
'image/jpeg',
'image/pjpeg',
'image/gif',
'image/png',
'image/webp',
);
protected $newName;
protected $typeCheckingOn = true;
protected $notTrusted = array ('bin', 'cgi','exe','js','pl','php', 'py', 'sh');
protected $suffix = '.upload';
和公共方法:
public function allowAllTypes($suffix = null)
{
$this->typeCheckingOn = false;
if(!is_null($suffix)) {
if (strpos($suffix, '.') === 0 || $suffix == '') {
$this->suffix = $suffix;
}else {
$this->suffix = ".$suffix";
}
}
}
public function upload()
{
$uploaded = current($_FILES);
if($this->checkFile($uploaded)){
$this->moveFile($uploaded);
}
}
public function getMessages()
{
return $this->messages;
}
protected function checkFile($file)
{
if ($file['error'] !=0){
$this->getErrorMessage($file);
return false;
}
if (!$this->checkSize($file)){
return false;
}
if ($this->typeCheckingOn){
if (!$this->checkType($file)){
return false;
}
}
$this->checkName($file);
return true;
}
protected function checkType($file)
{
if (in_array($file['type'], $this->permittedTypes)){
return true ;
} else{
$this->messages[] = $file['name'] . ' is not a permitted type of file.';
return false;
}
}
protected function checkName($file)
{
$this->newName = NULL;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']){
$this->newName = $nospaces;
}
$nameparts = pathinfo($nospaces);
$extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
if (!$this->typeCheckingOn && !empty($this->suffix)){
if (in_array($extension, $this->notTrusted) || empty($extention)){
$this->newName = $nospaces . $this->suffix;
}
}
}
protected function moveFile($file)
{
$result = $file['name']. ' was uploaded successfully';
if (!is_null($this->newName)){
$result .= ', and was renamed ' . $this->newName;
}
$result .= '.';
$this->messages[] = $result;
}
}
就像我说的那样,通过其他检查的文件将上传。它可以识别错误的文件,如果它在列表中就停止它,但是它用$后缀重新命名每个好的文件。
条件看起来很好,并说明如果有一个pathinfo ['扩展'] AND typeChecking关闭且后缀不为空,如果是,那么如果后缀在非可信列表中或空 - 是唯一应该添加扩展名的时间 但是它会在每次上传时加上后缀。
有人可以帮我指导一下我可能做错了什么吗?我希望我已经解释了我的问题而不会让人感到困惑。我会尽力回答每一个问题。
感谢任何人抽出时间提供帮助。
干杯!
答案 0 :(得分:0)
空($ extention)< - 扩展拼写不同