php 用一种形式上传文本和图像,用PHP将路径和文本存储在数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23798732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:57:13  来源:igfitidea点击:

Upload Text and Image with one form, storing path and text in database with PHP

phpimageformstextpath

提问by Kate Obrien

I've been working on this code for the last week and its racking my brain. I've searched on forums high and low and can only find very little on this specific subject.

上周我一直在研究这个代码,它绞尽脑汁。我在论坛上搜索了很多,但在这个特定主题上只能找到很少的东西。

I want to use a form to upload Text and images. Images get uploaded to directory (upload/), while image path and text is INSERTed INTO database table (upgrade.Testimonials). The index, uploader php, and upload folder all exist at www.mywebsite.com/testimonials

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

UPON EXECUTING THE FORM I RECEIVE A "Connected to $ftp_server, for user $USERNAME SAVED Stored in: upload/" BUT NO PHOTO IS UPLOADED AND THE PATH STORED IN DB HAS NO TITLE. BUT ALL OTHER INFORMATION IS SUBMITTED TO DATABASE FINE.

执行表单后,我收到“已连接到 $ftp_server,用户 $USERNAME 已保存存储在:upload/”但没有上传照片,并且存储在数据库中的路径没有标题。但所有其他信息都提交给数据库。

I've opened it the file_upload.php in TextWrangler and it doesn't give me any errors. Hosting with Godaddy.

我已经在 TextWrangler 中打开了 file_upload.php,它没有给我任何错误。与 Godaddy 一起主持。

Other than NY major vulnerability to SQL Injection, why am i not able to upload the images!?

除了纽约 SQL 注入的重大漏洞,为什么我无法上传图片!?

Here is what I have so far, please help!

以上是我目前的情况,请大家帮帮忙!

file_upload.php

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';
}
}
}



?>

The Form from INDEX.php

来自 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>

回答by Kate Obrien

Solved: Below is working code to; Upload File/image to ftp directory, store the path in database table, store current date, and text from form ALL FROM ONE FORM.

解决:以下是工作代码;将文件/图像上传到 ftp 目录,将路径存储在数据库表中,存储当前日期和表单中的文本 ALL FROM ONE FORM。

I searched for weeks online looking for a concise way to submit all this information on one row in the db, simultaneously. Could only piece it together, here it is for you guys.

我在网上搜索了数周,寻找一种简洁的方法来同时在数据库的一行中提交所有这些信息。只能拼凑起来,这里是给你们的。

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

对于初学者:1)在你的 html daw 中创建 2 个文件。Index.php 和 file_upload.php。索引将是您放置 html 的位置,file_upload.php 文件是您添加 php 代码的位置。PHP文件通常以

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).

ID 行必须设置为主键和 INT。其余的应该设置为具有特定数量字符(您选择)的 Varchar。

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.

4) 在与 index.php 和 file_upload.php 相同的位置创建上传文件夹。确保并添加文件权限到上传文件夹以禁止或允许公开编辑。

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

5)在我的代码中使用您的网站和页面目录切换出“ http://www.yourwebsite.com/directory”。

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

在以下情况下,upgrade 是数据库名称,Testimonials 是表名称。

file_upload.php

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

感谢@engvrdr

回答by Mwangi Thiga

Did something of the kind:

做了这样的事情:

HTML :

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>

The PHP Script:

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>";

    }
}
?>