5

我有一个基本脚本,允许我的网站成员上传他们作品的简短样本供客户收听。

一些文件名有空格,这在尝试播放样本时显然会导致问题。有没有办法在上传到临时目录和将文件移动到“样本”目录之间用下划线替换这些空格?

<?
            $url = "http://domain.com/uploads/samples/";
            //define the upload path
            $uploadpath = "/home/public_html/uploads/samples";
            //check if a file is uploaded
             if($_FILES['userfile']['name']) {
              $filename = trim(addslashes($_FILES['userfile']['name']));
            //move the file to final destination
              if(move_uploaded_file($_FILES['userfile']['tmp_name'],
            $uploadpath."/". $filename)) {

              echo "

    bla bla bla, the final html output

            ";

              } else{
                if ($_FILES['userfile']['error'] > 0)
              {
                   switch ($_FILES['userfile']['error'])
                {
                  case 1:  echo 'File exceeded upload_max_filesize';  break;
                  case 2:  echo 'File exceeded max_file_size';  break;
                  case 3:  echo 'File only partially uploaded';  break;
                  case 4:  echo 'No file uploaded';  break;
                }
                exit;
              }
              }
            }
?>
4

3 回答 3

13

在这一行之后:

$filename = trim(addslashes($_FILES['userfile']['name']));

写:

$filename = str_replace(' ', '_', $filename);

hello world.mp3(两个空格)这样的文件名会显示为hello__world.mp3(两个下划线),为了避免这种情况,您可以这样做:

$filename = preg_replace('/\s+/', '_', $filename);
于 2012-05-15T17:34:06.107 回答
0
$filename = str_replace(' ', '-', trim(addslashes($_FILES['userfile']['name'])));

为什么addslashes呢?这似乎也有点太简单了——我错过了什么吗?

于 2012-05-15T17:34:32.003 回答
0

尝试;

$filename = trim(str_replace(" ","_", $_FILES['userfile']['name']));
于 2012-05-15T17:39:50.930 回答