PHP:如何处理上传 2 个文件和输出


PHP: How to handle uploading 2 files and output

美好的一天!

首先要说的是我刚刚开始学习PHP,所以请放轻松...

基本上,我有一个表格,允许用户上传 2 张图像(以及填写其他字段(。 提交时,表单调用一个PHP文件(下面的代码(,该文件基本上将详细信息添加到数据库中并将图像上传到文件服务器。 这对于我想要完成的工作来说效果很好。 我遇到问题的地方是确认消息。

由于我有 2 个

单独的上传字段,所以我基本上有 2 个 if 语句来确认两个文件已正确上传。 我想简化一下,所以我真的只需要显示 1 条确认消息。

关于如何简化它的任何想法? 我认为代码将看起来两个文件是否都成功上传,如果是这样,则回显"x",否则回显"y"。 我对move_uploaded_file函数不太熟悉,所以我不确定我是否可以在那里使用 AND 语句...... 任何想法将不胜感激。

//This is the directory where images will be saved
$target = "path/";
$target = $target . basename($_FILES[controlcreative][name]);
$target2 = "path/";
$target2 = $target2 . basename($_FILES[winnercreative][name]);
$pic=($_FILES['controlcreative']['name']);
$pic2=($_FILES['winnercreative']['name']);
$con=mysqli_connect();
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$sql="INSERT INTO experiments (vertical, pagetype, pagename, primarykpitype, primarykpilift, primarysignificant, testobjective, takeawayone, optimizationtype, controlcreative, winnercreative)
VALUES
('$_POST[vertical]','$_POST[pagetype]','$_POST[pagename]','$_POST[primarykpitype]','$_POST[primarykpilift]','$_POST[primarysignificant]','$_POST[testobjective]','$_POST[takeawayone]','$_POST[optimizationtype]','$pic','$pic2')";
if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

//Writes the photo to the server
if(move_uploaded_file($_FILES[controlcreative][tmp_name], $target))
{
//Tells you if its all ok
echo "The file ". basename($_FILES[controlcreative][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.";
}
//Writes the photo to the server
if(move_uploaded_file($_FILES[winnercreative][tmp_name], $target2))
{
//Tells you if its all ok
echo "The file ". basename($_FILES[winnercreative][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.";
}

mysqli_close($con);

我会遍历$_FILES,这可能会为您节省一些代码并设置错误标志

$error = false;
foreach($_FILES as $name => $file)
{
    $target = '/path/to/destination/' . $file['name'];
    if(!move_uploaded_file($file['tmp_name'], $target)) $error = true;
}

然后

if(!$error) echo 'All files uploaded';