upload file with php and save path to sql

前端 未结 2 1651
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 03:37

Does anyone know any good tutorial on how to upload a file with php and save the files path to a sql server?

相关标签:
2条回答
  • 2020-12-06 04:05

    From http://www.w3schools.com/php/php_file_upload.asp

    HTML

    <html>
    <body>
    
    <form action="upload_file.php" method="post"
    enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" /> 
    <br />
    <input type="submit" name="submit" value="Submit" />
    </form>
    
    </body>
    </html>
    

    PHP

    <?php
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {   
        if (file_exists("upload/" . $_FILES["file"]["name"]))
          {
          echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; //<- This is it
          }
        }
    ?>
    

    Note that to upload the file you need to specify the path to save the file. If you save the file you already know it path.

    0 讨论(0)
  • 2020-12-06 04:23

    To upload a file you need at least a HTML POST form with multipart/form-data encoding. Therein you put an input type="file" field to browse the file and a submit button to submit the form.

    <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit">
    </form>
    

    In the upload.php the uploaded file is accesible by $_FILES with the field name as key.

    $file = $_FILES['file'];
    

    You can get its name as follows:

    $name = $file['name'];
    

    You need to move it to a permanent location using move_uploaded_file(), else it will get lost:

    $path = "/uploads/" . basename($name);
    if (move_uploaded_file($file['tmp_name'], $path)) {
        // Move succeed.
    } else {
        // Move failed. Possible duplicate?
    }
    

    You can store the path in database the usual way:

    $sql = "INSERT INTO file (path) VALUES ('" . mysqli_real_escape_string($path) . "')";
    // ...
    
    0 讨论(0)
提交回复
热议问题