我有一个网页表格来上传来自用户的图片。然后,我正在创建一个iOS应用程序来显示从用户加载的图片。但是如果文件名包含空格或特殊字符(如á,é,í,ó,ú,等等),则该应用程序不会加载图片,大多数用户来自西班牙.
这是我正在使用的代码:
<?php if ((isset($_POST["enviado"])) && ($_POST["enviado"] == "form1")) {
$randomString = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1) . substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
echo $randomString;
$nombre_archivo = $_FILES['userfile']['name'];
move_uploaded_file($_FILES['userfile']['tmp_name'], "logos/".$randomString.$nombre_archivo);
?>我使用随机函数来避免重复的文件名。
我如何更改用户提供的文件名,并可能包含空格和/或特殊字符,以一种可以在iOS应用程序中完美加载的方式?
发布于 2014-02-24 06:22:12
上传后重命名文件。这是对OP在评论中的问题的回答
// get the uploaded file's temp filename
$tmp_filename = $_FILES['userfile']['tmp_name'];
// get the file's extension
$path = $_FILES['userfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
// rename the uploaded file with a timestamp, insert the destination directory and add the extension
$new_filename = 'logos/'.date('Ymdhms').'.'.$ext;
// put the renamed file in the destination directory
move_uploaded_file($tmp_filename, $new_filename);编辑:OP问题的新答案
<?php
if((isset($_POST["enviado"])) && ($_POST["enviado"] == "form1")) {
// get the uploaded file's temp filename
$tmp_filename = $_FILES['userfile']['tmp_name'];
// get the file's extension
$path = $_FILES['userfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
// rename the uploaded with a timestamp file, add the extension and assign the directory
$new_filename = 'logos/'.date('Ymdhms').'.'.$ext;
// put the renamed file in the destination directory
move_uploaded_file($tmp_filename, $new_filename);
}发布于 2014-02-24 05:25:02
这是你需要做的。1)生成唯一的基于id的文件名字符串。2)用新生成的文件名重命名文件。
<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>发布于 2014-02-24 05:29:44
如果您实际上希望将用户输入的字符串保留为文件名的一部分,则可以这样做,将UTF-8字符音译为其ASCII等效字符(如果可能的话),然后删除任何非ASCII字符和无效字符:
function get_file_name($string) {
// Transliterate non-ascii characters to ascii
$str = trim(strtolower($string));
$str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
// Do other search and replace
$searches = array(' ', '&', '/');
$replaces = array('-', 'and', '-');
$str = str_replace($searches, $replaces, $str);
// Make sure we don't have more than one dash together because that's ugly
$str = preg_replace("/(-{2,})/", "-", $str );
// Remove all invalid characters
$str = preg_replace("/[^A-Za-z0-9-]/", "", $str );
// Done!
return $str;
}您可以尝试将其与文件的唯一ID结合起来,这样,如果两个用户上传一个文件名相同的文件,则不会发生冲突。
https://stackoverflow.com/questions/21979399
复制相似问题