【问题标题】:Adding GD file resize and rename to php image upload script将GD文件调整大小和重命名为php图像上传脚本
【发布时间】:2011-06-11 06:35:22
【问题描述】:

我有这个脚本,它允许上传图片,然后将指针存储在数据库中,指向文件系统上的文件。我从另一个 StackOverflow 问题中得到了这个脚本,它几乎完成了我需要的所有事情,除了两件事。 我需要的第一件事是能够调整图像的大小,我刚刚阅读的第二部分是重命名文件以防止用户错误等。

这里是上传文件,它从用户输入表单中获取表单数据并将数据写入 DB 并将图片写入图像目录。

 <?php

//This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("dbName") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>

【问题讨论】:

  • 你的问题到底是什么?
  • 拜托,拜托,了解准备好的语句和绑定变量。就目前而言,您的脚本对“SQL 注入”攻击是开放的。
  • 请注意,如果不使用 mysql_real_escape_string,您的代码将非常不安全。您只需要更改 $name=$_POST['nameMember']; 这样的行到 $name=mysql_real_escape_string($_POST['nameMember']);使其更加安全。
  • 嗯,我还在学习 php 和 mysql,这是我为自己设定的任务。通过使用示例,我学得最好。自发布以来,我发现此脚本存在可用性问题,例如,它不将文件类型限制为 .gif、.jpg 和 .png 文件。但是它确实向我展示了如何将文件引用粘贴到数据库中

标签: php mysql image


【解决方案1】:

关于调整大小,这里有一篇文章解释了如何使用 GD 将图像调整为任意大小。它具有裁剪或信箱选项以适应目标纵横比。

http://www.spotlesswebdesign.com/blog.php?id=1

对于文件名,只需将文件重命名为随机 ID,并确保您尚未使用该 ID。

do {
    $filename = uniqid().'jpg';
} while (file_exists('image/path/'.$filename);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-22
    • 2010-11-03
    • 2015-05-27
    • 1970-01-01
    • 2012-08-12
    • 2018-09-23
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多