PHP $ _FILES [“fileToUpload”] [“tmp_name”]

时间:2015-03-17 07:25:09

标签: php post compression

如何将$_FILES["fileToUpload"]["tmp_name"]转换为要在move_uploaded_file中使用的变量?

这有效:

  $filename = compress_image(($_FILES["fileToUpload"]["tmp_name"]), $url, 30);

但我想尝试这样的事情:

  $filename = compress_image($images, $url, 30);

但是,当它在上面时它不起作用。

我开始的另一个选择是:

  file_put_contents($target_file , $image);

在这种情况下,图像被正确地命名为目录,但图像总是被破坏。

澄清:

需要将($ _FILES [" fileToUpload"] [" tmp_name"])转换为

的变量
    ob_start(); echo imagejpeg($image,null,30); 
    $image =ob_get_clean(); 
    ob_end_clean();
     $image = addslashes($image); 

我需要使用$ image来保存到目录。 $ image已成功存储到mysql中。我已经尝试过编码,并在$ image上解码,但仍然没有运气。

1 个答案:

答案 0 :(得分:0)

让我一步一步解释问题:

一塌糊涂从这一行开始:

$image = imagecreatefromstring(file_get_contents($_FILES['fileToUpload']['tmp_name']));

问题:

  • 绝不使用临时文件进行处理;首先move_uploaded_file()首先将上传的文件移至永久地点
  • 不需要使用file_get_contents();您可以使用imagecreatefromjpeg()(以及其他格式,如GIF,PNG等)来替换imagecreatefromstring(file_get_contents())内容

以下是您的compress_image()功能:

function compress_image($source_url, $destination_url, $quality) {
    $info = getimagesize($source_url);
    if ($info['mime'] == 'image/jpeg')  {
        $image = imagecreatefromjpeg($source_url);
    } elseif ($info['mime'] == 'image/gif') {
        $image = imagecreatefromgif($source_url);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source_url);
    }
    imagejpeg($image, $destination_url, $quality);
    return $destination_url;
}

问题:

  • 如果MIME不是上述内容,则imagejpeg()将失败(但您没有提供它;请始终检查函数的返回值)
  • 你没有检查$destination_url是否可写&是否存在

接下来,假设compress_image()效果很好并返回$destination_url并在路径中创建了有效的JPEG,以下代码会导致更多问题:

$sql = "INSERT INTO fffdf (`user_id`,`imit`) VALUES ('9','$image')";
if (mysqli_query($conn, $sql)) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

问题:

  • 为什么要将$image直接保存到数据库中?将图像数据存储在DB中是一种非常糟糕的做法。改为尽可能保存路径
  • $image此处无法访问; $image的范围保留在函数compress_image()中,因此$image仍包含compress_image()之前的值,除非您在压缩函数中使用global $image;(不建议)。通过引用将$image作为函数参数传递:

    function compress_image(&amp; $ image,$ destination_url,$ quality)

如果您将图像数据存储在$source_url中,则不需要$image

希望以上有所帮助。

相关问题