我在将文件从HTML上传到基于PHP的Web服务器时遇到了一些问题。 以下是我的HTML代码。我相信没有问题。
<html>
<body>
<form action="upload.php" method="post"
enctype="multipart/form-data" action="2.2.2.cgi">
<input type="file" name="file" id="file" size="35"><br>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</body>
</html>
PHP代码:
<?php
define ('MAX_FILE_SIZE', 1000000);
$permitted = array('image/gif', 'image/jpeg', 'image/png', 'image/pjpeg', 'text/plain');
if ($_FILES['file']['type'] == $permitted
&& $_FILES['file']['size'] > 0
&& $_FILES['file']['size'] <= MAX_FILE_SIZE) {
move_uploaded_file($_FILES, $uploadedfile);
echo ('<img src="'.$uploadedfile'" />');
}
?>
我无法弄清楚如何让它在PHP中运行。我一直在尝试几种不同的方式,上面的代码只是我最近的绝望尝试,试图将值存储到一个新的变量中。我想做的是以下几点:
任何形式的提示或帮助都将不胜感激。谢谢!
PS。它不会上线,因此目前任何安全问题都无关紧要。
答案 0 :(得分:2)
奥莱特。完全测试并评论了一段代码。
<强> upload.php的强>
define ('MAX_FILE_SIZE', 1000000);
$permitted = array('image/gif', 'image/jpeg', 'image/png', 'image/pjpeg', 'text/plain'); //Set array of permittet filetypes
$error = true; //Define an error boolean variable
$filetype = ""; //Just define it empty.
foreach( $permitted as $key => $value ) //Run through all permitted filetypes
{
if( $_FILES['file']['type'] == $value ) //If this filetype is actually permitted
{
$error = false; //Yay! We can go through
$filetype = explode("/",$_FILES['file']['type']); //Save the filetype and explode it into an array at /
$filetype = $filetype[0]; //Take the first part. Image/text etc and stomp it into the filetype variable
}
}
if ($_FILES['file']['size'] > 0 && $_FILES['file']['size'] <= MAX_FILE_SIZE) //Check for the size
{
if( $error == false ) //If the file is permitted
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); //Move the file from the temporary position till a new one.
if( $filetype == "image" ) //If the filetype is image, show it!
{
echo '<img src="upload/'.$_FILES["file"]["name"].'">';
}
elseif($filetype == "text") //If its text, print it.
{
echo nl2br( file_get_contents("upload/".$_FILES["file"]["name"]) );
}
}
else
{
echo "Not permitted filetype.";
}
}
else
{
echo "File is too large.";
}
与此表单一起使用 的 form.html 强>
<form action="upload.php" method="post"
enctype="multipart/form-data" action="upload.php">
<input type="file" name="file" id="file" size="35"><br>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</body>
</html>