php 文件上传处理

  首先定义一个上传的目的地:

define('UPLOAD_DIR', 'path/to/upload_test/');

<?php 
define('UPLOAD_DIR','Store/');
if(isset($_POST['upload']))
{
    $file = str_replace(' ', '_', $_FILES['image']['name']);
    if(move_uploaded_file($_FILES['image']['tmp_name'],UPLOAD_DIR.$file))
        echo 'success';
    else
        echo 'error';
    
}
?>
    

<body>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" ?
name="uploadImage" id="uploadImage">
<p>
<label for="image">Upload image:</label>
<input type="file" name="image" id="image" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>

注意Spaces should be removed from filenames before storage on a web server.

define ('MAX_FILE_SIZE', 3000);

<input type="hidden" name="MAX_FILE_SIZE" value="
<?php echo MAX_FILE_SIZE; ?>"  />
<input type="file" name="image" id="image" />

This is a hidden form field, so it won’t be displayed onscreen. However, it is vital
that you place it before the file input field; otherwise, it won’t work. The value
attribute sets the maximum size of the upload file in bytes. 所以隐藏域必须在file之前才行。实验

了放在后面不行。

当文件的尺寸大于MAX_FILE_SIZE时,在php端使用$_FILES['image']['size']总是为0,这点要值得注意

Unfortunately, users can get around this restriction by faking the value of MAX_FILE_SIZE in the hidden field, so it’s important to check the actual size of the  file on the server side, too.

$file = str_replace(' ', '_', $_FILES['image']['name']);
  // convert the maximum size to KB
  $max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
  // begin by assuming the file is unacceptable
  $sizeOK = false;
  
  // check that file is within the permitted size
  if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <= MAX_FILE_SIZE) {
    $sizeOK = true;
    }
  
  if ($sizeOK) {
    switch($_FILES['image']['error']) {
      case 0:
        // move the file to the upload folder and rename it
        $success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR.$file);
        if ($success) {
          $result = "$file uploaded successfully";
          }
        else {
          $result = "There was an error uploading $file. Please try again.";
          }
        break;
      case 3:
        $result = "There was an error uploading $file. Please try again.";
      default:
        $result = "System error uploading $file. Contact webmaster.";
      }
    }
  elseif ($_FILES['image']['error'] == 4) {
    $result = 'No file selected';
    }
  else {
    $result = "$file cannot be uploaded. Maximum size: $max.";
    }
  }
?>

string number_format ( float $number [, int $decimals = 0 ] )   Format a number with grouped thousands

<?php
// if the form has been submitted, display result
if (isset($result)) {
echo "<p><strong>$result</strong></p>";
}
?>

限制上传文件类型

restrict the type

Images image/gif GIF format
image/jpeg JPEG format (includes .jpg files)
image/pjpeg JPEG format (nonstandard MIME type used
by Internet Explorer)
image/png PNG format
 图片基本就这几种格式。 下面的代码可以使用in_array()快速判断

// convert the maximum size to KB
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
// create an array of permitted MIME types
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png');
// begin by assuming the file is unacceptable
$sizeOK = false;
$typeOK = false;
/ check that file is within the permitted size
if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <= ➥
MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of a permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['image']['type']) {
$typeOK = true;
break;
}
}

You can now use $typeOK to control whether the file is moved to the upload folder. Both $typeOK and $sizeOK must be true for the upload to continue. Immediately  after the code you have just entered, amend the if statement like this:
if ($sizeOK && $typeOK) {
switch($_FILES['image']['error']) {
4. There’s just one final touch needed. Add details of the permitted types to the else
statement at the bottom of the script, just before the DOCTYPE declaration.
else {
$result = "$file cannot be uploaded. Maximum size: $max. ➥
Acceptable file types: gif, jpg, png.";}  }

 

Preventing files from being overwritten

  

PHP automatically
   php  overwrites existing files without warning.

  在文件名中加上时间。

time() 返回自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。数字很大

date(format,timestamp)

$success = move_uploaded_file($_FILES['image']['tmp_name'], ➥
UPLOAD_DIR.time().$file);

$now = date('Y-m-d');
$success = move_uploaded_file($_FILES['image']['tmp_name'], ➥
UPLOAD_DIR.$now.$file);

Organizing uploads into specific folders

  

You can take the categorization of upload files a step further by creating a new upload folder
(directory) for each user. This assumes that you require users to log in using a user authentication
process (see Chapters 9 and 15) and store the username in a session variable.
There’s no need to set up the folders in advance; PHP can handle it for you automatically,
as long as the new folders are created inside the upload folder.
Moving uploaded files to specific folders involves just three steps, as follows:
1. Getting the name of the specific folder
2. Creating the folder if it doesn’t already exist
3. Adding the folder name to the upload path

Creating user-specific upload folders

在实际的应用程序中,你会存储用户名和密码到session。并且上传表格会被php session保护。为了论证的目的,用户名这里是hard-coded.

Insert the following code at the beginning of the switch statement:
switch($_FILES['image']['error']) {
case 0:
// $username would normally come from a session variable
$username = 'davidp';
// if the subfolder doesn't exist yet, create it
if (!is_dir(UPLOAD_DIR.$username)) {
mkdir(UPLOAD_DIR.$username);
}

All you need to do now is to add $username to the pathname to the next part of the script, which moves the upload file to its new location.

// check if a file of the same name has been uploaded
if (!file_exists(UPLOAD_DIR.$username.'/'.$file)) {
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['image']['tmp_name'], ➥
UPLOAD_DIR.$username.'/'.$file);
}
else {
// get the date and time
ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$success = move_uploaded_file($_FILES['image']['tmp_name'], ➥
UPLOAD_DIR.$username.'/'.$now.$file);
}

注意文件夹和文件名之间的/ 

上传多个文件

<input type="file" name="image[]" id="image1" />

多个这样的input即可。


<?php
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 51200);

if (array_key_exists('upload', $_POST)) {
  // define constant for upload folder
  define('UPLOAD_DIR', 'C:/upload_test/');
  // convert the maximum size to KB
  $max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
  // create an array of permitted MIME types
  $permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');
  
  foreach ($_FILES['image']['name'] as $number => $file) {
    // replace any spaces in the filename with underscores
    $file = str_replace(' ', '_', $file);
    // begin by assuming the file is unacceptable
    $sizeOK = false;
    $typeOK = false;
  
    // check that file is within the permitted size
    if ($_FILES['image']['size'][$number] > 0 || $_FILES['image']['size'][$number] <= MAX_FILE_SIZE) {
    $sizeOK = true;
    }

    // check that file is of an permitted MIME type
    foreach ($permitted as $type) {
      if ($type == $_FILES['image']['type'][$number]) {
        $typeOK = true;
        break;
        }
      }
  
    if ($sizeOK && $typeOK) {
      switch($_FILES['image']['error'][$number]) {
        case 0:
          // check if a file of the same name has been uploaded
          if (!file_exists(UPLOAD_DIR.$file)) {
            // move the file to the upload folder and rename it
            $success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$file);
            }
          else {
            // get the date and time
            ini_set('date.timezone', 'Europe/London');
            $now = date('Y-m-d-His');
            $success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$now.$file);
            }
          if ($success) {
            $result[] = "$file uploaded successfully";
            }
          else {
            $result[] = "Error uploading $file. Please try again.";
            }
          break;
        case 3:
          $result[] = "Error uploading $file. Please try again.";
        default:
          $result[] = "System error uploading $file. Contact webmaster.";
        }
      }
    elseif ($_FILES['image']['error'][$number] == 4) {
      $result[] = 'No file selected';
      }
    else {
      $result[] = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: gif, jpg, png.";
      }
    }
  }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Multiple file upload</title>
</head>

<body>
<?php
// if the form has been submitted, display result
if (isset($result)) {
  echo '<ol>';
  foreach ($result as $item) {
    echo "<strong><li>$item</li></strong>";
    }
  echo '</ol>';
  }
?>
<form action="" method="post" enctype="multipart/form-data" name="multiUpload" id="multiUpload">
    <p>
        <label for="image1">File 1:</label>
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
        <input type="file" name="image[]" id="image1" />
    </p>
    <p>
        <label for="image2">File 2:</label>
        <input type="file" name="image[]" id="image2" />
    </p>
    <p>
        <input name="upload" type="submit" id="upload" value="Upload files" />
    </p>
</form>
</body>
</html>

Ideally, uploads should be restricted to registered and trusted users, so the upload form should be in a password-protected part of your site. Also, the upload folder does not need to be inside your site root, so locate it in a private directory whenever possible unless you want uploaded material to be displayed immediately in your web pages.

 Replace spaces in filenames with underscores or hyphens.

原文地址:https://www.cnblogs.com/youxin/p/2644949.html