简体   繁体   English

文件上传到服务器上的文件夹,但在数据库表中更新时没有 Sql 注入?

[英]Files Uploading to Folder on Server but no Sql Injection on update in the Database Table?

The code i have used is uploading to the desired folder on the server correctly, but is not updating the columns in the Table at all?我使用的代码正确上传到服务器上所需的文件夹,但根本没有更新表中的列? I don't want to use INSERT INTO as i,m trying to inject into a particular ROW.我不想使用 INSERT INTO,因为我试图注入特定的行。 the row being the username selected on upload with the file.该行是上传文件时选择的用户名。 Can anybody help?有人可以帮忙吗?

Here is the HTML form code -这是 HTML 表单代码 -

      <form name= "admin_upload" class="sign-in-htm" id="upload" 
      action="/php/upload.php" method="post" enctype="multipart/form- 
      data">
      <div class="group">
      <label for="user" class="label">Enter Company or Employer Name: 
      </label>
      <input id="username" name="username" type="text" class="input">
      </div>
      <br>
      <div class="group">
      <label for="attachment" class="label">Upload Test Result PDF: 
      </label>
      <input id="attachment" multiple name="files[]" 
      accept=".doc,.docx,.pdf" type="file" class="input">
      </div>
      <br>

      <button class="btn btn-primary btn-submit" name="submit" 
      value="submit" input type="submit">Submit Results</button>
  </form>

Here is the PHP code -这是PHP代码-

      if(isset($_POST["submit"]))
      {
      $statusMsg = $errorMsg = $updateValuesSQL = $errorUpload = 
      $errorUploadType = '';
      if(!empty(array_filter($_FILES['files']['name']))){
      foreach($_FILES['files']['name'] as $key=>$val){
        // File upload path
        $fileName = basename($_FILES['files']['name'][$key]);
        $targetFilePath = $targetDir . $fileName;

        // Check whether file type is valid
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
        if(in_array($fileType, $allowTypes)){
            // Upload file to server
            if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], 
      $targetFilePath)){
                // Image db insert sql
                $updateValuesSQL .= "('".$fileName."'),";
            }else{
                $errorUpload .= $_FILES['files']['name'][$key].', ';
            }
        }else{
            $errorUploadType .= $_FILES['files']['name'][$key].', ';
        }
      }
      echo $_POST['username'];      
      if(isset($_POST['username'])){
      $username = $_POST['username'];
      }


      if(!empty($updateValuesSQL)){
        $updateValuesSQL = trim($updateValuesSQL,',');
        // Insert image file name into database
       $update = $link->$sql =("UPDATE users SET file_name = 
      '$updateValuesSQL' WHERE username = '$username'");

I am not getting any error messages and i have it set to return to the page if successful which is happening.我没有收到任何错误消息,如果成功,我将其设置为返回页面。 Any ideas what i am doing wrong?任何想法我做错了什么?

I had a little play around as the above was vulnerable and, IMO, a little hard to read.我玩了一下,因为上面的内容很脆弱,而且 IMO 有点难以阅读。 I hope the following will help - it does work OK我希望以下内容会有所帮助 - 它确实可以正常工作

<?php

    /* assumed that you will replace this with your connection */
    require 'db.php';

?>
<?php

    $output=[]; //  log all actions & results to display to user if required


    if( isset( $_POST['submit'], $_POST['username'] ) && !empty( $_FILES['files'] ) ){

        function uploaderror( $error ){ 
            switch( $error ) { 
                case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
                case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
                case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
                case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
                case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
                case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
                case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
                default: return "Unknown upload error";
            }
        }

        /*************************************/
        /*       EDIT AS APPROPRIATE         */
        /*************************************/

        $targetDir='c:/temp/fileuploads/stack/';







        $username=$_POST['username'];
        $files=(object)$_FILES[ 'files' ];
        $allowed_exts=array('doc','docx','pdf');
        $col=[];    //  store the names of each file successfully uploaded - to be used in the sql update statement





        /* iterate through all uploaded files */
        foreach( $files->name as $i => $void ){
            try{
                $name = $files->name[$i];
                $size = $files->size[$i];
                $type = $files->type[$i];
                $tmp  = $files->tmp_name[$i];
                $error= $files->error[$i];

                if( $error == UPLOAD_ERR_OK ){

                    /* is this filetype permitted? */
                    $ext = pathinfo( $name, PATHINFO_EXTENSION );
                    if( is_uploaded_file( $tmp ) ){

                        if( in_array( $ext, $allowed_exts ) ){

                            /* store the uploaded file */
                            $target = $targetDir . $name;
                            $bytes = move_uploaded_file( $tmp, $target );

                            /* store the file name */
                            $col[]=$name;


                            $message=$bytes > 0 ? sprintf( 'The file "%s" has been uploaded.', $name ) : sprintf( 'There was a problem uploading "%s".', $name );
                            throw new Exception( $message );
                        } else {
                            throw new Exception( sprintf( 'Invalid filetype detected: %s', $ext ) );
                        }
                    } else {
                        throw new Exception( 'Warning: Possible file upload attack!' );
                    }
                } else {
                    throw new Exception( sprintf('Error: %d - %s', $error, uploaderror( $error ) ) );
                }
            }catch( Exception $e ){
                $output[]=$e->getMessage();
                continue;
            }
        }



        if( !empty( $col ) ){

            /* create the comma separated list of filenames to be used in the sql */
            $filenames = implode( ',', $col );

            /* create the prepared statement and make the bindings */
            $sql='update `users` set `file_name`=? where `username`=?';
            $stmt=$link->prepare( $sql );
            $stmt->bind_param('ss', $filenames, $username );

            /* execute the query */
            $result = $stmt->execute();
            $rows = $stmt->affected_rows;
            $stmt->close();

            /* log result & finish */
            $output[]=sprintf('Operation completed: %d rows updated, %d files uploaded, status: %s', $rows, count( $col ), $result );
        }
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>upload</title>
    </head>
    <body>
        <!--

            action='/php/upload.php' 

        -->
        <form name='admin_upload' class='sign-in-htm' action='' method='post' enctype='multipart/form-data'>
            <div class='group'>
                <label for='user' class='label'>Enter Company or Employer Name:</label>
                <input id='username' name='username' type='text' class='input' required>
            </div>
            <br>
            <div class='group'>
                <label for='attachment' class='label'>Upload Test Result PDF:</label>
                <input id='attachment' multiple name='files[]' accept='.doc,.docx,.pdf' type='file' class='input' />
            </div>
            <br>
            <button class='btn btn-primary btn-submit' name='submit' value='submit' input type='submit'>Submit Results</button>
            <?php

                if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $output ) ){
                    printf('<pre>%s</pre>',print_r($output,true));
                }

            ?>
        </form>
    </body>
</html>

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

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