Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

php - Replace Spaces with Underscores in Uploaded File

I have a basic script that allows my site members to upload short samples of their compositions for customers to listen to.

Some file names have spaces which obviously causes problems when trying to play the samples. Is there a way to replace these spaces with underscores between uploading to the temp directory and moving the file to the 'samples' directory?

<?
            $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;
              }
              }
            }
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After this line:

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

Write:

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

A filename like hello  world.mp3 (two spaces) would come out as hello__world.mp3 (two underscores), to avoid this you could do this instead:

$filename = preg_replace('/s+/', '_', $filename);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...