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


Custom Name And Overwriting For PHP Image Upload

在我的网站上,用户的用户名可以在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";
  }
?> 

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);
    }
}