简体   繁体   English

文件或图像上传php问题

[英]file or image upload php problem

I having problems with the download code of this script, I have modified it and added other features to it that work. 我对该脚本的下载代码有疑问,我对其进行了修改并向其添加了其他功能。 Just the download part of the script does not work, I will provide the full code for all the files. 只是脚本的下载部分不起作用,我将提供所有文件的完整代码。

upload.php upload.php

<?php
require_once 'dbc.php';
page_protect();

$client_ID = mysql_query("SELECT id
    FROM clients WHERE user_name='".$_SESSION['user_name']."'")or die(mysql_error());
$client_ID = mysql_fetch_array($client_ID);
$client_ID = $client_ID['id'];


$uploadDir = 'uploads/';

if(isset($_POST['upload']))
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$filePath = $uploadDir . $fileName;

$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}

$hostname_conndb = "localhost";
$database_conndb = "uploads";
$username_conndb = "root";
$password_conndb = "";
$conndb = mysql_connect($hostname_conndb, $username_conndb, $password_conndb) or trigger_error(mysql_error(),E_USER_ERROR);

if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
} 

$date = date('Y-m-d H:i:s');

$sql = "INSERT INTO upload2 (name, client, size, type, path, date ) ".
"VALUES ('$fileName', '$client_ID', '$fileSize', '$fileType', '$filePath', '$date')";
mysql_select_db($database_conndb, $conndb);
$result = mysql_query($sql, $conndb) or die(mysql_error());

echo "<br>File $fileName uploaded<br>";

}
?>
<html>
<head>
<title>Download File From MySQL</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="styles.css" rel="stylesheet" type="text/css">
</head>

<body>
<?php
$hostname_conndb = "localhost";
$database_conndb = "uploads";
$username_conndb = "root";
$password_conndb = "";
$conndb = mysql_connect($hostname_conndb, $username_conndb, $password_conndb) or trigger_error(mysql_error(),E_USER_ERROR);

$sql = "SELECT * FROM upload2 WHERE client='".$client_ID."' ORDER BY date DESC";
mysql_select_db($database_conndb, $conndb);
$result = mysql_query($sql, $conndb) or die(mysql_error());
$rows = mysql_fetch_assoc($result);
$total_rows = mysql_num_rows($result);
?>
Welcome <?php echo $_SESSION['user_name'];?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr> 
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"> 
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>

<?php if($total_rows > 0) { ?>
          <table border="0" cellpadding="0" cellspacing="0" id="tbl_repeat">
        <tr>
          <th scope="col">FIle/Image Name</th>
          <th scope="col" style="width:15%">Date</th>
          <th scope="col" style="width:10%">Size</th>
          <th scope="col" style="width:10%">Download</th>
        </tr>
        <?php do { ?>
        <tr>
          <td><?php echo $rows['name']; ?></td>
          <td><?php echo $rows['date']; ?></td>
          <td><?php echo $rows['size']; ?></td>
          <td><a href="downloads.php?id=<?php echo $rows['id']; ?>">Download</a></td>
        </tr>
        <?php } while($rows = mysql_fetch_assoc($result)); ?>
      </table> 
      <?php } else { echo "<p class="warn">Sorry there are no records available.</p>"; } ?>
<p><br />
  <a href="logout.php">Logout </a></p>
</body>
</html>

This code works fine. 此代码可以正常工作。 The download code is: downloads.php 下载代码为:downloads.php

<?php
require_once 'dbc.php';
page_protect();

$client_ID = mysql_query("SELECT id
    FROM clients WHERE user_name='".$_SESSION['user_name']."'")or die(mysql_error());
$client_ID = mysql_fetch_array($client_ID);
$client_ID = $client_ID['id'];


$uploadDir = 'uploads/';

if(isset($_POST['upload']))
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$filePath = $uploadDir . $fileName;

$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}

$hostname_conndb = "localhost";
$database_conndb = "uploads";
$username_conndb = "root";
$password_conndb = "qaasim11";
$conndb = mysql_connect($hostname_conndb, $username_conndb, $password_conndb) or trigger_error(mysql_error(),E_USER_ERROR);

if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
} 

$date = date('Y-m-d H:i:s');

$sql = "INSERT INTO upload2 (name, client, size, type, path, date ) ".
"VALUES ('$fileName', '$client_ID', '$fileSize', '$fileType', '$filePath', '$date')";
mysql_select_db($database_conndb, $conndb);
$result = mysql_query($sql, $conndb) or die(mysql_error());

echo "<br>File $fileName uploaded<br>";

}
?>

<html>
<head>
<title>Download File From MySQL</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="styles.css" rel="stylesheet" type="text/css">
</head>

<body>
<?php
$hostname_conndb = "localhost";
$database_conndb = "uploads";
$username_conndb = "root";
$password_conndb = "";
$conndb = mysql_connect($hostname_conndb, $username_conndb, $password_conndb) or trigger_error(mysql_error(),E_USER_ERROR);

$sql = "SELECT * FROM upload2 WHERE client='".$client_ID."' ORDER BY date DESC";
mysql_select_db($database_conndb, $conndb);
$result = mysql_query($sql, $conndb) or die(mysql_error());
$rows = mysql_fetch_assoc($result);
$total_rows = mysql_num_rows($result);
?>
Welcome <?php echo $_SESSION['user_name'];?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr> 
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"> 
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>

<?php if($total_rows > 0) { ?>
          <table border="0" cellpadding="0" cellspacing="0" id="tbl_repeat">
        <tr>
          <th scope="col">FIle/Image Name</th>
          <th scope="col" style="width:15%">Date</th>
          <th scope="col" style="width:10%">Size</th>
          <th scope="col" style="width:10%">Download</th>
        </tr>
        <?php do { ?>
        <tr>
          <td><?php echo $rows['name']; ?></td>
          <td><?php echo $rows['date']; ?></td>
          <td><?php echo $rows['size']; ?></td>
          <td><a href="downloads.php?id=<?php echo $rows['id']; ?>">Download</a></td>
        </tr>
        <?php } while($rows = mysql_fetch_assoc($result)); ?>
      </table> 
      <?php } else { echo "<p class="warn">Sorry there are no records available.</p>"; } ?>
<p><br />
  <a href="logout.php">Logout </a></p>
</body>
</html>

Also this the code for my database: 这也是我数据库的代码:

CREATE TABLE IF NOT EXISTS `upload2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`client` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`type` varchar(30) NOT NULL,
`size` int(11) NOT NULL,
`path` varchar(60) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Dumping data for table `upload2`
--

INSERT INTO `upload2` (`id`, `client`, `name`, `type`, `size`, `path`, `date`) VALUES
(1, 1, 'back.gif', 'image/gif', 1997, 'uploads/back.gif', '2010-09-19 12:17:05'); 

When i click the download link in upload.php i get the following error Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in downloads.php on line 17 the fileis non exist in 当我单击upload.php中的下载链接时,出现以下错误警告:mysql_fetch_array():提供的参数不是downloads.php中第17行上的有效MySQL结果资源,该文件不存在于

I am not sure if the code works to download files/images if this error was not their as I cannot figure out how to fix this pronlem. 我不确定如果不是此错误,代码是否可以下载文件/图像,因为我不知道如何解决此问题。

You don't connect to database for the first query (to get $client_ID ) 您不连接到数据库进行第一个查询(获取$client_ID

$hostname_conndb = "localhost";
$database_conndb = "uploads";
$username_conndb = "root";
$password_conndb = "qaasim11";
$conndb = mysql_connect($hostname_conndb, $username_conndb, $password_conndb) or trigger_error(mysql_error(),E_USER_ERROR);

$client_ID = mysql_query("SELECT id
    FROM clients WHERE user_name='".$_SESSION['user_name']."'")or die(mysql_error());
$client_ID = mysql_fetch_array($client_ID);
$client_ID = $client_ID['id'];

Some things to consider: 要考虑的一些事情:

  1. Checking if a POST field is set is not the proper way to check if as POST was actually performed - it's entirely possible you may rename the field at some point and forget to change the if() , or the field is not submitted for some reason. 检查是否设置了POST字段不是检查是否实际执行POST的正确方法-完全有可能在某个时候重命名该字段而忘记更改if() ,或者由于某种原因未提交该字段。 A foolproof check is if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... } . 一个简单的检查是if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... } That will be true anytime the script is executed in response to a POST request, regardless of what fields (if any) were submitted. 每当响应POST请求执行脚本时,无论提交了什么字段(如果有),都是如此。
  2. You blindly assume the upload was successful, without checking for any of the MANY reasons an upload could fail (connection dies, file too large, out of disk space, etc...). 您盲目地认为上传成功,而没有检查上传失败的许多原因(连接中断,文件太大,磁盘空间不足等)。 The ['error'] parameter in the $_FILES array is there for a reason. $ _FILES数组中的['error']参数是有原因的。 if ($_FILES['somefile']['error'] === UPLOAD_ERR_OK) { ... upload was successful ... }
  3. You don't sanitize the ['name'] parameter and blindly use it as part of the path in move_uploaded_file() . 您无需清理['name']参数,并盲目地将其用作move_uploaded_file()路径的一部分。 The name is COMPLETELY under control of the user, so a malicious user can easily name their file ../../../../../../windows/system32/kernel32.dll and your script will happily attempt to kill your machine 该名称是完全由用户控制的,因此恶意用户可以轻松地将其文件命名为../../../../../../windows/system32/kernel32.dll ,您的脚本将很乐意尝试杀死你的机器
  4. You don't check for file collisions, which follows from point 3). 从第3点开始,您无需检查文件冲突。 You blindly overwrite any file of the same name. 您会盲目覆盖任何同名文件。
  5. Without any kind of upload completion checking, you then attempt to save the data into a database. 如果不进行任何类型的上载完成检查,则尝试将数据保存到数据库中。 You use addslashes() on $filePath and $fileName, but you don't do the same for $fileType - that's the MIME type as provided BY THE CLIENT - so again it's fully under control of the user, and a malicious one can therefore easily perform an SQL injection attack. 您在$ filePath和$ fileName上使用了addslashes() ,但对$fileType却没有做同样的$fileType -这是客户端提供的MIME类型-因此,它再次受到用户的完全控制,因此,恶意代码可以完全由用户控制轻松执行SQL注入攻击。
  6. You're connecting to your database as the root user. 您将以root用户身份连接到数据库。 This is horribly bad practice. 这是非常糟糕的做法。 Create a dedicated account and grant it only "insert" privileges. 创建一个专用帐户,并仅授予其“插入”权限。 A simple web application almost never requires create/drop/alter privileges, but this is what you're exposing to the world by using the root account. 一个简单的Web应用程序几乎几乎不需要创建/删除/更改特权,但这就是您通过使用root帐户向世人展示的内容。 Combined with the SQL injection hole, and you've handed your database (and most likely the rest of your server) to an attacker on a silver platter. 结合SQL注入漏洞,您已经将数据库(很可能是服务器的其余部分)移交给了一块银盘上的攻击者。

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

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