使用一个表单同时上传文本和图片,使用PHP将存储路径和文本存入数据库

4

我已经在过去的一周里一直在研究这段代码,它让我很困惑。我在各个论坛上搜索了很久,但只能找到关于这个特定主题的很少信息。

我想使用一个表单来上传文本和图片。 图像被上传到目录(upload /),而图像路径和文本被插入到数据库表(upgrade.Testimonials)中。 索引、上传者php和上传文件夹都存在于www.mywebsite.com/testimonials中。

执行表单后,我收到了“Connected to $ftp_server, for user $USERNAME SAVED Stored in: upload/”,但没有上传照片,并且存储在数据库中的路径没有标题。 但是,所有其他信息都已成功提交到数据库。

我用TextWrangler打开了file_upload.php,但它没有给我任何错误。 使用Godaddy托管。

除了对SQL注入的重大漏洞之外,为什么我无法上传图像!?

这是我到目前为止所拥有的,请帮忙!

file_upload.php

       <?php
if(isset($_POST['add']))
{
$dbhost = '';
$dbuser = '';
$dbpass = '';
$db_name = 'upgrade';
$tbl_name = 'Testimonials';
$ftp_user = '';
$ftp_pass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("$db_name")or die("cannot select DB");


$ftp_server = "";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
// login with username and password
$login_result = ftp_login($ftp_conn, $ftp_user, $ftp_pass);


// check connection
if ((!$ftp_conn) || (!$login_result)) {
       echo "FTP connection has failed!";
       echo "Attempted to connect to $ftp_server for user $ftp_user";
       exit;
   } else {
       echo "Connected to $ftp_server, for user $ftp_user";
 }


$Fname = $_POST['fname'];
$Email = $_POST['email'];
$Content = $_POST['content'];
$filePath="http://www.mywebsite.com/testimonials/upload/" . $_FILES["file"]["name"];
$Type = $_POST['type'];

 if ($_FILES["file"]["error"] > 0)
  {
     echo "Error: NO CHOSEN FILE <br />";
     echo"INSERT TO DATABASE FAILED";
   }
   else
   {
     move_uploaded_file($_FILES["file"]["tmp_name"], __DIR__ . "/upload/" . $_FILES["file"]["name"]);
     echo"SAVED<br>";



$query_image = "INSERT INTO $tbl_name (fname, email, content, image,type, submission_date) VALUES ('$Fname','$Email','$Content','$filePath','$Type',curdate())";
if(mysql_query($query_image))
{
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
}



?>

来自INDEX.php的表单。
<form method="post"  enctype="multipart/form-data" action="/testimonials/file_upload.php">
<table>
<tr>
<td width="250">Name</td>
<td>
<input name="fname" type="text" id="fname" /><br />
</td>
</tr>
<tr>
<td width="250">Email: (will not be publicized)</td>
<td>
<input name="email" type="text" id="email" /><br />
</td>
</tr>
<tr>
<td width="250">Client Type</td>
<td id="mainselection">
<select name="type" id="type">
    <option></option>
    <option value="Residential">Residential</option>
    <option value="Business">Business</option>

</select>
</td>
</tr>
<tr>
<td width="250">Comments</td>
<td>
<textarea id="content" name="content" rows="10" cols="50" style="border-style:groove;box-shadow: 4px 4px 4px 4px #888888;"placeholder="Please describe your experience"></textarea>
</td>
</tr>
<tr>
<td width="250">Image</td>
<td>
<input name="image" type="file" id="file">
</td>
</tr>

<tr>
<td width="250"> </td>
<td>
<input name="add" type="submit" id="add" value="Add Testimonial">
</td>
</tr>
</table>
</form>

你的上传文件夹可写吗?你能将权限更改为777吗?但是不要在生产环境中使用777,我记不清了,但我认为666应该足够进行写操作。 - engvrdr
@engvrdr FileZilla不让我更改权限,明天我会打电话给Godaddy。你们看到代码有什么问题吗? - Kate Obrien
@kateobrein 我认为这不是最好的方法,但应该可以工作。你可以看一下gd扩展并重新创建图像。你的代码托管在Windows服务器上吗? - engvrdr
@engvrdr 刚刚联系了Godaddy并更改了权限,现在我遇到了500错误。如果我删除enctype="multipart/form-data",500错误就会消失,但我仍然得到“文件未上传”的自报告。我的主机是Windows,使用Plesk面板。 - Kate Obrien
请你检查一下路径是否正确? 或者如果你的file_upload.php文件在testimonials文件夹中,你可以使用 __DIR__."/upload/"; 来获取完整路径。 - engvrdr
@engvrdr 请查看我上面帖子中对PHP所做的修改。现在我收到的信息是“连接到$ftp_server,用户为$username,已保存到:upload/”。但是在上传文件夹中没有存储任何图像,路径中也没有标题,只有目录前缀。(将enctype重新添加到表单中) - Kate Obrien
2个回答

2
解决方案: 下面是可行的代码:将文件/图像上传到FTP目录,在数据库表中存储路径,存储当前日期和来自表单的文本,全部使用一个表单提交。
我在网上搜索了几周,以找到一种简洁的方式来同时提交所有这些信息到数据库的一行中。最终只能将它们拼凑在一起,现在分享给大家。

For beginners: 1)Create 2 files in your html daw. Index.php and file_upload.php. Index will be where you put your html, the file_upload.php file is where you add the php code. Php files usually start with

The ID row must be set to primary key and INT. The rest should be set to Varchar with a specific amount of characters (your choosing).

4)Create upload folder at same location as index.php and file_upload.php. Be sure and add file permissions to upload folder to prohibit or allow public edits.

5) switch out 'http://www.yourwebsite.com/directory' in my code with your website and page directory.

In the following case, upgrade is the database name, and Testimonials is the table name.

file_upload.php

<?php
if(isset($_POST['add']))
{
$dbhost = '';
$dbuser = '';
$dbpass = '';
$db_name = 'upgrade';
$tbl_name = 'Testimonials';
$ftp_user = '';
$ftp_pass = '';
$ftp_server = "";

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("$db_name")or die("cannot select DB");




$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
// login with username and password
$login_result = ftp_login($ftp_conn, $ftp_user, $ftp_pass);


// check connection
if ((!$ftp_conn) || (!$login_result)) {
       echo "FTP connection has failed!";
       echo "Attempted to connect to $ftp_server for user $ftp_user";
       exit;
   } else {
       echo "Connected to $ftp_server, for user $ftp_user";
   }


$Fname = $_POST['fname'];
$Email = $_POST['email'];
$Content = $_POST['content'];
$Type = $_POST['type'];
$uploadDir = 'http://www.yourwebsite.com/directory/'.'upload/'; 
$fileName = $_FILES['image']['name'];
$filePath = $uploadDir . $fileName;

if(move_uploaded_file($_FILES["image"]["tmp_name"],"upload/".$_FILES["image"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "INSERT INTO $tbl_name(fname,email,content,image,type,submission_date) VALUES ('$Fname','$Email','$Content','$filePath','$Type',curdate())";
if(mysql_query($query_image))
{
echo "Stored in: " . "upload/" . $_FILES["image"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
else{echo 'File not uploaded';}

}





?>

THE FORM

<form method="post"  enctype="multipart/form-data" action="/testimonials/file_upload.php">
<table>
<tr>
<td width="250">Name</td>
<td>
<input name="fname" type="text" id="fname" /><br />
</td>
</tr>
<tr>
<td width="250">Email: (will not be publicized)</td>
<td>
<input name="email" type="text" id="email" /><br />
</td>
</tr>
<tr>
<td width="250">Client Type</td>
<td id="mainselection">
<select name="type" id="type">
    <option></option>
    <option value="Residential">Residential</option>
    <option value="Business">Business</option>

</select>
</td>
</tr>
<tr>
<td width="250">Comments</td>
<td>
<textarea id="content" name="content" rows="10" cols="50" style="border-style:groove;box-shadow: 4px 4px 4px 4px #888888;"placeholder="Please describe your experience"></textarea>
</td>
</tr>
<tr>
<td width="250">Image</td>
<td>
<input name="image" type="file" id="file">
</td>
</tr>

<tr>
<td width="250"> </td>
<td>
<input name="add" type="submit" id="add" value="Add Testimonial">
</td>
</tr>
</table>
</form>

thanks to @engvrdr


0

做了类似这样的事情:

HTML:

 <?php
include '../controllers/session.php';

//get new add space
$querysps="INSERT INTO `advertisements`( `advertname`, `active`) VALUES ('',0);
";

require('../../database.php');
$statement = $db->prepare($querysps);
$statement->execute();
//$dummyadd = $statement->fetchAll();
$statement->closeCursor();

$newspace=$db->lastInsertId();

//echo $newspace;
?>
<?php include 'includes/navigation.php';?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        Dashboard
        <small>Advertisements</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="index.php"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">View Advertisements</li>
      </ol>



    <ul class="">
        <li><!-- search form -->
        <form action="?" method="get">

  <div class="input-group custom-search-form">
    <?php 
     // echo '<label>Live Search:</label>';
      $search = isset($_POST['get']) ? $_POST['get'] : '';
      echo '<input type="text" class="form-control" placeholder="Search Adds" onkeyup="showResultfs(this.value)" name="search" value="' .$search .'" /><span class="input-group-btn">
                                <button class="btn btn-default" href="?reset" type="button">
                                    <i class="fa fa-search"></i>
                                </button>';
      echo ' <a class="btn tdn" href="?reset"><b>Clear</b> </a>';
      echo '<br />';
      //echo '<input type="submit" name="submit" value="Submit" />';
     // echo '<label>No JavaScript</label>';
      echo '<br /><br />';
    ?>
  </div>    
</form>
</li>
</ul>

      <?php 

                               if(empty($notifmsg)==true){

                               }else{
                               echo " <div class=\"alert alert-success alert-dismissable\">
                                <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">X</button>
                                ".$notifmsg."
                               </div>";
                               }

    ?>


    </section>

     <section class="content">

      <div class="row">


        <div class="col-md-12">
          <!-- Custom Tabs -->







          <div class="box box-info">
            <div class="box-header with-border">
              <h3 class="box-title">Create Add</h3>
            </div>
            <!-- /.box-header -->
            <!-- form start -->
            <form action="../controllers/addmaker.php" method="post" enctype="multipart/form-data" class="form-horizontal">
              <div class="box-body">
              <input type="hidden" name="addid" value="<?php echo $newspace;?>">
                <div class="form-group">
                  <label for="inputEmail3" class="col-sm-2 control-label">Add Name</label>

                  <div class="col-sm-10">
                    <input type="text" class="form-control" name="addname" id="inputEmail3" required placeholder="Add name">
                  </div>
                </div>

                <div class="form-group">
                  <label for="inputPassword3" class="col-sm-2 control-label">Air To</label>

                  <div class="col-sm-10">
                    <input type="date" class="form-control" name="airto" required id="inputPassword3" placeholder="">
                  </div>
                </div>

                 <div class="form-group">
                  <label for="inputPassword3" class="col-sm-2 control-label">Add Picture</label>

                  <div class="col-sm-10">
                    <input class="btn btn-primary btn-sm" type="file" id="file" name="file" required accept="image/jpeg" >
                  </div>
                </div>

                <div class="form-group">
                  <div class="col-sm-offset-2 col-sm-10">

                  </div>
                </div>
              </div>
              <!-- /.box-body -->
              <div class="box-footer">
                <button type="clear" class="btn btn-default">Clear</button>
                <!--  <button type="submit" class="btn btn-info pull-right">Create Add</button> -->
                <input type="submit" name="submit" class="btn btn-info pull-right" value="submit" />
              </div>
              <!-- /.box-footer -->
            </form>
          </div>





















          </div>
        <!-- /.col -->


      </div>

    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->


  <?php include 'includes/footer.php'?>




   <script type="text/javascript">
    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
        history.pushState(null, null, document.URL);
    });
    </script>


    <script type="text/javascript">
  function showResultfs(str)
  {
    if (str.length==0)
    {
      document.getElementById("livesearchfs").innerHTML="";
      // document.getElementById("livesearch").style.border="0px";
      return;
    }
    if (window.XMLHttpRequest)
    {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }else{  // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        document.getElementById("livesearchfs").innerHTML=xmlhttp.responseText;
        // document.getElementById("livesearch").style.border="1px solid #A5ACB2";
      }
    }
    // xmlhttp.open("GET","db-results.php?q="+str,true);
    xmlhttp.open("POST","../controllers/fs-results.php?q="+str,true);
    xmlhttp.send();
  }
</script>

<!-- jQuery 2.2.3 -->
<script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="../bootstrap/js/bootstrap.min.js"></script>
<!-- FastClick -->
<script src="../plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="../dist/js/app.min.js"></script>
<!-- Sparkline -->
<script src="../plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="../plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="../plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- SlimScroll 1.3.0 -->
<script src="../plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- ChartJS 1.0.1 -->
<script src="../plugins/chartjs/Chart.min.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="../dist/js/pages/dashboard2.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="../dist/js/demo.js"></script>
</body>
</html>

PHP脚本:

<?php
include 'session.php';

$addid=$_POST['addid'];
$addname=$_POST['addname'];
$airto=$_POST['airto'];
$newDate = date('Y-m-d H:i:s', strtotime($airto));


$query="UPDATE `advertisements` SET `advertname`='$addname',`aituntill`='$newDate',`active`=1 WHERE `advertid`=$addid";
echo $query."<br>";


saveadddata($query);
handlepic($addid);











function saveadddata($query){
    require '../../database.php';
    $statement = $db->prepare($query);
    $statement->execute();
    $statement->closeCursor();
}


function handlepic($addid){
    echo "In pic maker"."<br>";
    if (isset($_POST['submit'])==true)
    {
        echo "If passed"."<br>";
        $userid=$addid;
        $filename = $_FILES["file"]["name"];
        $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
        $file_ext = substr($filename, strripos($filename, '.')); // get file name
        $filesize = $_FILES["file"]["size"];
        $allowed_file_types = array('.doc','.docx','.rtf','.pdf','.jpg','.jpeg');
        $pathholder="../../adds/img/".$userid;
        echo $pathholder."<br>";
        if (in_array($file_ext,$allowed_file_types) && ($filesize < 5000000))
        {

            //$pathholder="Ruerenamed";
            if (!file_exists($pathholder)) {
                mkdir($pathholder, 0777, true);
            }


            //make new directory

            //mkdir("$pathholder");
            // Rename file
            $newfilename = $userid . $file_ext;

            //      if (file_exists("uploads/" . $newfilename))
                //      {
                //          // file already exists error
                //          echo "You have already uploaded this file.";
                //      }
            //      else
                //      {
            move_uploaded_file($_FILES["file"]["tmp_name"], "$pathholder/" . $newfilename);
            //echo "File ".$pathholder."/".$newfilename." uploaded successfully.";
            $_SESSION['serverFeedback']="Advertisement created! ";
            header("Location: ../pages/index.php");
            //include 'ownerprofile.php';
            //}
        }
        elseif (empty($file_basename))
        {
            $newfilename = $userid.".jpg";
            //$pathholder="Ruerenamed";
            // file selection error

            if (!file_exists($pathholder)) {
                mkdir($pathholder, 0777, true);
            }


            $file = '../../defaultpictures/me.jpg';
            $newfile = $pathholder."/".$newfilename;

            if (!copy($file, $newfile)) {
                //  echo "failed to copy". $file."into ". $newfile;
            }else{
                //  echo "copied ".$file ."into ". $newfile;
            }

            //echo "Please select a file to upload.";
            $_SESSION['serverFeedback']="Advertisement created with default! ";
            header("Location: ../pages/index.php");
            //include 'ownerprofile.php';
        }
        elseif ($filesize > 5000000)
        {
            // file size error
            //echo "The file you are trying to upload is too large.";
            $_SESSION['serverFeedback']="Advertisement picture is too large to upload! ";
            header("Location: ../pages/index.php");
            //include 'ownerprofile.php';
        }
        else
        {
            // file type error
            //echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
            unlink($_FILES["file"]["tmp_name"]);
            $_SESSION['serverFeedback']="Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
            header("Location: ../pages/index.php");
            //include 'ownerprofile.php';
        }
    }else {
        echo "If failed"."<br>";

    }
}
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接