步骤1
该脚本将允许您使用 PHP 将文件从浏览器上传到主机。我们需要做的第一件事是创建一个 HTML 表单,允许人们选择他们想要上传的文件。
<form enctype="multipart/form-data" action="upload.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
此表单将数据发送到文件“upload.php”,这是我们接下来将创建的文件以实际上传文件。
第2步
实际的文件上传非常简单:
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
这段非常小的代码将上传您的 HTML 表单发送给它的文件。
The first line $target = "upload/"; is where we assign the folder that files will be uploaded to. As you can see in the second line, this folder is relative to the upload.php file. So for example, if your file was at www.yours.com/files/upload.php then it would
将文件上传到 www.yours.com/files/upload/yourfile.gif。请务必记住创建此文件夹!拥有777个权利
第三步
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
假设您没有更改我们 HTML 表单中的表单字段(因此仍然命名为已上传),这将检查文件的大小。如果文件大于 350k,则会给出文件太大的错误,我们将 $ok 设置为 0。
如果您愿意,可以通过将 350000 更改为不同的数字来将此行更改为更大或更小的尺寸。或者,如果您不关心文件大小,请忽略这些行
We are not using $ok=1; at the moment but we will later in the tutorial.
We then move the uploaded file to where it belongs using move_uploaded_file (). This places it in the directory we specified at the beginning of our script. If this fails the user is given an error message, otherwise they are told that the file has been uploaded.
放在一起
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
//This is our size condition
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
?>
显然,如果您允许文件上传,您就会让自己对上传许多不受欢迎的东西的人开放。一项预防措施是不允许他们上传任何可能包含恶意代码的 php、html、cgi 等文件。这提供了更多的安全性,但不确定防火。