简体   繁体   English

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

[英]Custom Name And Overwriting For PHP Image Upload

On my website, the user's username can be displayed in PHP as 在我的网站上,用户的用户名可以在PHP中显示为

<?=$c->username?>

I need the image to be saved as 我需要将图像另存为

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

I also need image over righting to be on. 我还需要在正上方打开图像。 When the trying to upload another image with the same name, it will simply error out. 当尝试上传具有相同名称的另一张图片时,它只会出错。

<?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 already does what you want. move_uploaded_file已经满足您的要求。

The error is most likely caused by the fact that you're writing to an absolute path , ie, to a directory called "example" in the root of the file system, instead of a subdirectory "example" in the current web server's root. 该错误很可能是由于您正在写入绝对路径 (即,文件系统根目录中的名为“ example”的目录)而不是当前Web服务器根目录中的子目录“ example”的事实所致。

Also, you could prepare an array of allowed types and check with in_array : 另外,您可以准备允许类型的数组,并使用in_array检查:

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

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

Another thing worth doing is defining some variables so that you can be sure of always using the same values, as you only assign them once. 值得做的另一件事是定义一些变量,这样您就可以确保始终使用相同的值,因为您只需分配一次即可。 If you make a typo in the variable name you'll get a notice, while if you typo a path or forget to update one of several instances after a modification, you risk a silent and/or difficult-to-diagnose error. 如果您在变量名中输入错误,则会收到通知,而如果您输入路径错误或在修改后忘记更新多个实例之一,则可能会出现无提示和/或难以诊断的错误。

$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}";
}

In your case you want the picture to be saved in such a way that <?= $c->username ?>.png loads it back in a browser . 在您的情况下,您希望以<?= $c->username ?>.png的方式将图片保存在浏览器中

For this you need two things: the file path and the image format, which has to be PNG. 为此,您需要做两件事:文件路径和图像格式,必须为PNG。 Sending a JPEG after telling the browser you're sending a PNG might not work (some browsers will auto-recognize the format, other won't). 在告诉浏览器您要发送PNG后发送JPEG可能无法正常工作(某些浏览器会自动识别格式,而其他浏览器则不会)。 You might also want to fit the image into a specific size. 您可能还需要将图像调整为特定大小。

So you should do something like this: 因此,您应该执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM