0

我正在尝试创建一个图库系统,该系统在表中为每个图像创建条目,允许脚本检索具有特定值的所有图像。目前我已经设法让文件上传工作,尽管它没有将文件名和画廊 ID 输入到我的表中 - 它根本没有创建一行。下面是代码,任何帮助都会很棒:)!尽管文件上传之类的东西并不是我的强项,但我已经搞砸了一些事情。

<?php
require "common.php";
$con = mysql_connect("localhost","$username","$password");
mysql_select_db("$dbname", $con);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$id = $_GET['id'];
$query2 = mysql_query("SELECT id,title,date FROM galleries WHERE id = $id");
    if (!$query2) {
        echo 'Could not run query: ' . mysql_error();
        exit;
}
$row = mysql_fetch_row($query2);
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& 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("../galleries/images/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "../galleries/images/" . $_FILES["file"]["name"]);
      $file = '["file"]["name"]';
      $sql="INSERT INTO images (url, gallery)
        VALUES
  ('$_POST[$file]','$_POST[$id]')";
  header("Location: ../../../gallery.php?id=" . $row[0]); 
  die("Redirecting to: admin.php"); 
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>
4

1 回答 1

0

问题是您在执行查询之前重定向并终止脚本:

$sql="INSERT INTO images (url, gallery)
        VALUES
         ('$_POST[$file]','$_POST[$id]')";
header("Location: ../../../gallery.php?id=" . $row[0]); 
die("Redirecting to: admin.php");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ nothing after this gets executed
if (!mysql_query($sql,$con))
     ^^^^^^^^^^^^^^^^^^^^^^ this query will never run
   ...

你真的应该切换到 PDO(或 mysqli)和准备好的语句以避免 sql 注入问题。

于 2013-03-06T18:30:52.407 回答