帮我用php写一个上传代码
时间: 2023-06-05 11:07:21 浏览: 59
好的,我可以提供一些有用的代码作为参考,但可能需要更多的具体细节,请务必检查代码并进行必要的修改以满足您的具体需求。以下是一个基本的文件上传功能的PHP代码示例:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
<?php
if(isset($_POST["submit"])) {
$target_dir = "uploads/"; // 设置上传目的地
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// 检查文件是否已存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// 检查文件大小是否符合要求
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// 检查文件类型是否符合要求
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 检查是否出现任何错误
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// 如果没有错误,就开始上传
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
请注意,这仅仅是一个基本的代码示例,可以上传照片、音乐、视频甚至是任何文件。请根据您的特定需求进行修改。