php 用php上传文件并将路径保存到sql
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2879266/
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
upload file with php and save path to sql
提问by alecnash
Does anyone know any good tutorial on how to upload a file with php and save the files path to a sql server?
有谁知道有关如何使用 php 上传文件并将文件路径保存到 sql server 的任何好的教程?
回答by BalusC
To upload a file you need at least a HTML POST form with multipart/form-dataencoding. Therein you put an input type="file"field to browse the file and a submit button to submit the form.
要上传文件,您至少需要一个带有multipart/form-data编码的 HTML POST 表单。在其中放置一个input type="file"字段来浏览文件和一个提交按钮来提交表单。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
In the upload.phpthe uploaded file is accesible by $_FILESwith the field name as key.
在upload.php上传的文件中,$_FILES以字段名称为关键字可以访问。
$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:
您需要使用 将其移动到永久位置move_uploaded_file(),否则它会丢失:
$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) . "')";
// ...
回答by Ben
From http://www.w3schools.com/php/php_file_upload.asp
来自http://www.w3schools.com/php/php_file_upload.asp
HTML
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
<?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.
请注意,要上传文件,您需要指定保存文件的路径。如果您保存文件,您已经知道它的路径。

