从文件名中删除特殊字符
Posted
技术标签:
【中文标题】从文件名中删除特殊字符【英文标题】:Removing special characters from filename 【发布时间】:2016-02-04 07:41:46 【问题描述】:我正在创建一个人们可以上传图片的网站。但是,当最终用户上传包含特殊字符或外来字符的图像时,该图像确实会上传,但无法在网站上显示,就像该图像在服务器上不存在一样。
我看到很多人在另一个帖子上回答说我需要使用preg_replace
但问题是,我真的不知道如何使用它。我将如何在我的代码中使用它。
这是我的控制器方法:
public function upload(Requests\CreatePostsRequest $request)
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES['fileToUpload']["name"]);
$uploadOk = 1;
$findme = ".";
$pos = strpos($target_file, $findme);
//echo $target_file;
//dd($_POST);
echo ini_get('upload_max_filesize');
echo $_FILES["fileToUpload"]["error"];
$imageFileType = strtolower(substr($target_file,$pos+1));
if(isset($_POST["submit"]))
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
//$check = true;
//dd($check);
if($check !== false)
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
else
echo "File is not an image.";
$uploadOk = 0;
$filecheck = 0;
$orgFileName = $target_file;
while (file_exists($target_file))
$target_file = substr($orgFileName,0,$pos).$filecheck.substr($orgFileName,$pos);
$filecheck++;
$uploadOk = 1;
if ($_FILES["fileToUpload"]["size"] > 500000000*8)
echo "Sorry, your file is too large.";
$uploadOk = 0;
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" )
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
echo $imageFileType;
$uploadOk = 0;
if ($uploadOk == 0)
echo "Sorry, your file was not uploaded.";
else
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$post = new Posts($request->all());
$post->fileToUpload = $target_file;
Auth::user()->posts()->save($post);
else
echo "Sorry, there was an error uploading your file.";
return redirect('');
echo $target_file;
【问题讨论】:
【参考方案1】:使用 preg 替换:
$target_file = $target_dir . preg_replace("/[^a-z0-9\_\-\.]/i", '', basename($_FILES['fileToUpload']["name"]));
这将删除所有不是字母 (a-z)、数字 (0-9) 或破折号、下划线或点的字符(我们希望保留文件扩展名)。最后的i
标志使匹配不区分大小写。
更新
为了使表达式更短,您可以将a-z0-9\_
-part 替换为单词标记\w
。
该模式将是:/[^\w\-\.]/
。这里我们不需要i
标志,因为词令牌为我们处理。
【讨论】:
这不起作用,它不会删除文件名中的“+”。我做对了吗?$target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES['fileToUpload']["name"]); $target_file = preg_replace("/[^A-Za-z0-9\_\-]/", '', $target_file);
@EiðurGeirVilhelmsson - 太棒了。是的,我用保存按钮有点快。确实改变了几次.. Lycka 直到 :)
@MagnusEriksson 你摇滚!
对于反对的选民。如果你觉得这个答案质量太差以至于你想投反对票,请添加评论解释原因。如果您不知道问题所在,就很难解决问题。
@MagnusEriksson 您的解决方案非常适合我!以上是关于从文件名中删除特殊字符的主要内容,如果未能解决你的问题,请参考以下文章