我在linux上运行xampp。的index.php
<form class="well" action="upload.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="file">Select a file to upload</label>
<input type="file" name="file">
<p class="help-block">Only jpg, jpeg, png, wav, mp3, wav and mp4 files are allowed.</p>
</div>
<input type="submit" class="btn btn-lg btn-primary" value="Upload">
</form>
upload.php的
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
$size = $_FILES['file']['size'];
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
switch ($error) {
case UPLOAD_ERR_OK:
$valid = true;
//validate file extensions
if ( !in_array($ext, array('jpg','jpeg','png','mp3', 'mp4', 'wav', 'webm')) ) {
$valid = false;
$response = 'Invalid file extension.';
}
//validate file size
/*if ( $size/1024/1024 > 2 ) {
$valid = false;
$response = 'File size is exceeding maximum allowed size.';
}*/
//upload file
if ($valid) {
$targetPath = 'uploads/';
move_uploaded_file($tmpName,$targetPath);
header( 'Location: index.php' ) ;
exit;
}
break;
case UPLOAD_ERR_INI_SIZE:
$response = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
$response = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$response = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$response = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$response = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.';
break;
case UPLOAD_ERR_CANT_WRITE:
$response = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
break;
case UPLOAD_ERR_EXTENSION:
$response = 'File upload stopped by extension. Introduced in PHP 5.2.0.';
break;
default:
$response = 'Unknown error';
break;
}
echo $response;
}
?>
Phpinfo:文件上传,最大文件大小128M。 uploads
文件夹为空,它位于脚本所在的根目录中,没有显示错误,脚本似乎没有错误
答案 0 :(得分:1)
您应该检查move_uploaded_file
的返回值。
if ($valid)
{
$targetPath = 'uploads/';
if(move_uploaded_file($tmpName,$targetPath))
{
header( 'Location: index.php' ) ;
exit;
}
else
{
$response = 'Moving the file to the target directory failed.';
}
}
如果这会给您一个错误,请使用$targetPath
的绝对路径。
编辑:您还需要包含要用作目标的文件名,而不仅仅是目录。所以将代码更改为:
if(move_uploaded_file($tmpName, $targetPath . $name))
{
答案 1 :(得分:0)
所以你需要到达你想要访问的文件夹。我有一段时间没想到同样的问题。我找到的解决方案是使用$ targetpath执行此操作:
您需要获取网络服务器路径,为此,您需要使用dirname(__FILE__)
功能。取决于您将在文件路径中走多远。例如,我需要访问文件夹“nydemo1 / bilder / images / folders /”然后我需要这个文件路径变量:
dirname(dirname(dirname(__FILE__))
//因为这是3个文件夹
希望这有帮助