我尝试从html表单上传文件,以便文件转到特定文件夹,并将路径上传到数据库。 数据库部分工作正常,但文件不会转到我的目标文件夹。 我将文件夹权限设置为777,并在我的php.ini文件中,file_uploads = on。
<?php
require 'config.php';
$connection = new mysqli($servername, $username, $password, $db);
foreach ($_FILES['upload']['name'] as $key => $name) {
if( move_uploaded_file($_FILES['upload']['name'][$key], '/upload_test/' .
$name)){
echo "Uploaded";
} else {
echo "Debug ", print_r($_FILES);
};
$path = '/upload_test/' . $name;
mysqli_query($connection, "insert into docs (path) values ('$path')");
}
?>
<script src="addInput.js" type="text/javascript"></script>
<form method="POST" action="upload.php" enctype="multipart/form-data">
<div id="dynamicInput">
<input type="file" name="upload[]" multiple><input type="button"
value="+" onClick="addInput('dynamicInput');">
</div>
<input type="submit" value="Upload">
</form>
当我尝试上传时,请返回:
Debug: Array(
[upload] => Array(
[name] => Array([0] => test.docx)
[type] => Array([0] => application/vnd.openxmlformats-officedocument.wordprocessingml.document)
[tmp_name] => Array([0] => /tmp/phputnLek)
[error] => Array([0] => 0)
[size] => Array([0] => 12551)
)
)
答案 0 :(得分:2)
根据您的评论,您似乎正在尝试上传到错误的目录:
if (move_uploaded_file($_FILES['upload']['tmp_name'][$key], '/upload_test/' . $name)) {
请注意,路径'/upload_test/' . $name
位于文件系统的根目录中,因为它以斜杠/
开头。
如果要将文件移动到相对于当前运行脚本的目录,则需要:
if (move_uploaded_file($_FILES['upload']['tmp_name'][$key], 'upload_test/' . $name)) {
^ relative to the current path
由于相对路径往往会导致混淆,您还可以设置变量以定义相对于文件系统根目录的网站根目录,或使用php提供的值$_SERVER['DOCUMENT_ROOT']
。
例如:
define('WEBROOT', '/var/www/html');
...
if (move_uploaded_file($_FILES['upload']['tmp_name'][$key],
WEBROOT . '/multiple_file_upload/upload_test/' . $name)) {
或:
if (move_uploaded_file($_FILES['upload']['tmp_name'][$key],
$_SERVER['DOCUMENT_ROOT'] . '/multiple_file_upload/upload_test/' . $name)) {
答案 1 :(得分:1)
您必须将临时文件移动到新目的地!在您的情况下,您尝试将原始文件名移动到目标文件夹。
应该这样做......
move_uploaded_file($_FILES['upload']['tmp_name'][$key], '/upload_test/' . $name);