PHP图像上传的自定义名称和覆盖

时间:2013-09-25 22:13:55

标签: php

在我的网站上,用户的用户名可以用PHP显示为

<?=$c->username?>

我需要将图片另存为

<?=$c->username?>.png

我还需要正确的图像才能打开。当尝试上传另一个具有相同名称的图像时,它只会出错。

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("/example/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "/example/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "/example/". $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?> 

1 个答案:

答案 0 :(得分:0)

move_uploaded_file已经做了你想做的事。

错误很可能是由于您正在写入绝对路径,即写入文件系统根目录中名为“example”的目录而不是子目录当前Web服务器根目录中的“example”。

此外,您可以准备一系列允许的类型,并使用in_array检查:

$allowed_types = array('image/gif', 'image/jpeg', ...);

if ((in_array($_FILES['file']['type'], $allowed_types)
    && ...) {
    ...

另一件值得做的事情是定义一些变量,这样你就可以确保始终使用相同的值,因为你只需要分配一次。如果您在变量名称中输入拼写错误,您将收到通知,而如果您输入路径或忘记在修改后忘记更新其中一个实例,则可能会出现无法和/或难以诊断的错误。

$destination_dir = './example/'; // Also, note the "." at the beginning

// SECURITY: do not trust the name supplied by the user! At least use basename().
$basename = basename($_FILES["file"]["name"]);

if (!is_dir($destination_dir)) {
    trigger_error("Destination dir {$destination_dir} is not writeable", E_USER_ERROR);
    die();
}

if (file_exists($destination_file = $destination_dir . $basename)) {
  echo "{$basename} already exists";
} else {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  $destination_file);
  echo "Stored in: {$destination_file}";
}

在您的情况下,您希望以<?= $c->username ?>.png将其加载回浏览器的方式保存图片

为此你需要两件事:文件路径和图像格式,它必须是PNG。在告诉浏览器您发送PNG后发送JPEG可能不起作用(某些浏览器会自动识别格式,其他浏览器不会)。您可能还希望将图像调整为特定大小。

所以你应该这样做:

// We ignore the $basename supplied by the user, using its username.
// **I assume that you know how to retrieve $c at this point.**
$basename = $c->username . '.png';

$destination_file = $destination_dir . $basename;

if ('image/png' == $_FILES['file']['type']) {
    // No need to do anything, except perhaps resizing.
    move_uploaded_file($_FILES["file"]["tmp_name"], $destination_file);
} else {
    // Problem. The file is not PNG.
    $temp_file = $destination_file . '.tmp';
    move_uploaded_file($_FILES["file"]["tmp_name"], $temp_file);
    $image_data = file_get_contents($temp_file);
    unlink($temp_file);

    // Now we have image data as a string.
    $gd = ImageCreateFromString($image_data);

    // Save it as PNG.
    ImagePNG($gd, $destination_file);
    ImageDestroy($gd);
}

// Optional resize.
if (false) {
    list($w, $h) = getImageSize($destination_file);

    // Fit it into a 64x64 square.
    $W = 64;
    $H = 64;
    if (($w != $W) || ($h != $H)) {
        $bad  = ImageCreateFromPNG($destination_file);
        $good = ImageCreateTrueColor($W, $H);

        $bgnd = ImageColorAllocate($good, 255, 255, 255); // White background
        ImageFilledRectangle($good, 0, 0, $W, $H, $bgnd);

        // if the image is too wide, it will become $W-wide and <= $H tall.
        // So it will have an empty strip top and bottom.
        if ($w > $W*$h/$H) {
            $ww = $W;
            $hh = $ww * $h / $w;
            $xx = 0;
            $yy = floor(($H - $hh)/2);
        } else {
            // It will be $H tall, and l.o.e. than $W wide
            $hh = $H;
            $ww = $hh * $w / $h;
            $xx = floor(($W - $ww)/2);
            $yy = 0;
        }
        ImageCopyResampled($good, $bad,
            $xx, $yy, 0, 0,
           $ww, $hh, $w, $h
        );

        // Save modified image.
        ImageDestroy($bad);
        ImagePNG($good, $destination_file);
        ImageDestroy($good);
    }
}