在php中仅上传doc和pdf文件
Posted
技术标签:
【中文标题】在php中仅上传doc和pdf文件【英文标题】:upload only doc and pdf file in php 【发布时间】:2014-04-19 16:02:45 【问题描述】:在下面的代码中,它正在上传所有文件类型,但我只需要 doc 和 pdf 文件
我尝试了以下代码来限制上传文件,但它不起作用
我只想上传 doc 和 pdf 文件帮助我的朋友们,我知道该怎么做吗
<?php
if(isset($_POST['name']))
$name=$email=$phone=$uploadresume="";
$nameErr=$emailErr=$phoneErr=$uploadresumeErr="";
function test_input($data)
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
if ($_SERVER['REQUEST_METHOD']=="POST")
$valid=true;
//name validaton
if(empty($_POST["name"]))
$nameErr="* Name is Required";
$valid=false;
else
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
$nameErr = " Only letters and white space allowed";
$valid=false;
//Email Address validaton
if(empty($_POST["email"]))
$emailErr="* Email is Required";
$valid=false;
else
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
$emailErr=" Enter a valid Email ID";
$valid=false;
//Mobile no validaton
if(empty($_POST["phone"]))
$phoneErr="* Mobile no is Required";
$valid=false;
else
$phone=test_input($_POST["phone"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]0,2?\d3[\)\]\s-]0,2?\d3[\s-]?\d4$/i",$phone))
$phoneErr="*Enter a valid contact no";
$valid=false;
if(empty($_FILES["filename"]['type']))
$uploadresumeErr="* Upload Your Resume";
$valid=false;
else
$_FILES["filename"]['type'] = 'application/pdf';
$_FILES["filename"]['type'] = 'application/msword';
$uploadresume=test_input($_POST["filename"]);
if($valid)
$to = "ex@example.co.in";
// Change this to your site admin email
$from = "$_POST[email]";
$subject = "Applied for DataEntry FROM $_POST[name] ";
//Begin HTML Email Message where you need to change the activation URL inside
// Get all the values from input
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
// Now Generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// Now Store the file information to a variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
// Now here we setting up the message of the mail
$message = "
\n\n Applied For DataEntry
\n\n Name: $name
\n\n Email: $email_address
\n\n Phone: $phone";
// Check if the upload succeded, the file will exist
if (file_exists($tmp_name))
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name))
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
// Now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"$mime_boundary\"";
// Next, we'll build the message body note that we insert two dashes in front of the MIME boundary when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--$mime_boundary\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
$message .= "--$mime_boundary\n" .
"Content-Type: $type;\n" .
" name=\"$file_name\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"$fileatt_name\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--$mime_boundary--\n";
// Thats all.. Now we need to send this mail... :)
if (@mail($to, $subject, $message, $headers))
?>
<div>
<center>
<h1>Your Data Has been submitted we will contact you soon !!</h1>
</center>
</div>
<?php
else
?>
<div>
<center>
<h1>Error !! Unable to send yor data..</h1>
</center>
</div>
<?php
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/>
<?php echo $nameErr?> <br />
<br />
<label>Email-ID:</label>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/>
<?php echo $emailErr?> <br />
<br />
<label>Phone No:</label>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>
<?php echo $phoneErr?> <br />
<br />
<label for="tele">upload Resume</label>
<input type="file" name="filename" id="tele"/>
<?php echo $uploadresumeErr?> <br />
<br />
<input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>
【问题讨论】:
为什么你在不同的帐户下提出同样的问题? @YourCommonSense 我可以知道你想说什么吗?if(empty($_FILES["filename"]['name'])) $uploadresumeErr="* Upload Your Resume"; $valid=false; else $fname_arr = explode('.',$_FILES["filename"]['name']); $fileext = $fname_arr[count($fname_arr)-1]; $ext_arr = array('doc','pdf'); if(in_array($fileext,$ext_arr)) $uploadresume=test_input($_POST["filename"]); else $uploadresumeErr="* Upload only doc or pdf files."; $valid=false;
这段代码解决的问题
【参考方案1】:
index.php
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br/>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
上传文件.php
<?php
$allowedExts = array("pdf", "doc");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if (($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/doc")
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts))
if ($_FILES["file"]["error"] > 0)
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
else
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
echo $_FILES["file"]["name"] . " already exists. ";
else
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
else
echo "Invalid file";
?>
【讨论】:
【参考方案2】:已经有一些关于同一主题的问题。我会再次发布答案,我想......
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['TMP_NAME']);
switch ($mime)
case 'image/jpeg':
case 'application/pdf':
case etc....:
default:
die("Unknown/not permitted file type");
来源:Upload DOC or PDF using PHP
【讨论】:
【参考方案3】:注意:这个简单的解决方案主要在使用 codeigniter 框架时有效
$config['upload_path'] = './uploads/;
$config['allowed_types'] = 'pdf,doc,docx';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['file_name'] = round(100,99); //make your file name random
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('file_name'))
print $this->upload->data();
else
print $this->upload->display_errors();
【讨论】:
以上是关于在php中仅上传doc和pdf文件的主要内容,如果未能解决你的问题,请参考以下文章
我有这个用于上传文件的代码,我想只允许 PDF、DOC、DOCX
asp.net 中怎么把上传在服务器上的doc.xls文件转换成PDF
在 PHP (LAMP) 中创建文档(PDF、DOC、XLS 等)的缩略图预览