PHP - 从客户端上传文件到服务器

时间:2014-11-15 10:00:47

标签: php file-upload

我需要知道如何从客户端PC获取文件(.txt或其他)并将其上传到我拥有所需网站的服务器上的某个目录,而不是将此文件作为附件发送电子邮件(但这不再是问题)。这必须通过PHP函数完成。请问有人帮帮我吗?

1 个答案:

答案 0 :(得分:0)

表格内容:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
    <form action="sendEmail.php" method="post" name="mainform" enctype="multipart/form-data">
    <table width="500" border="0" cellpadding="5" cellspacing="5">
    <tr>
        <th>To Email</th>
        <td><input name="toEmail" type="text"></td>
    </tr>

    <tr>
        <th>Subject</th>
        <td><input name="fieldSubject" type="text" id="fieldSubject"></td>
    </tr>
    <tr>
      <th>Attach Your File</th>
      <td><input name="attachment" type="file"></td>
    </tr>
    <tr>
        <td colspan="2" style="text-align:center;"><input type="submit" name="Submit" value="Send File"></td>
    </tr>
    </table>
    </form>
</body>
</html>

要处理的脚本:

<?php
$to = $_POST['toEmail'];
$subject = $_POST['fieldSubject']; 

// Get file info
$tmpName = $_FILES['attachment']['tmp_name']; 
$fileType = $_FILES['attachment']['type']; 
$fileName = $_FILES['attachment']['name']; 

if (file($tmpName)) { 
  $file = fopen($tmpName,'rb'); 
  $data = fread($file,filesize($tmpName)); 
  fclose($file); 

  $randomVal = md5(time()); 
  $mimeBoundary = "==Multipart_Boundary_x{$randomVal}x"; 

  $headers = "From: $fromName"; 

  $headers .= "\nMIME-Version: 1.0\n"; 
  $headers .= "Content-Type: multipart/mixed;\n" ;
  $headers .= " boundary=\"{$mimeBoundary}\""; 

  $message = "This is test email\n\n";
  $data = base64_encode($data); 
} 

$result = mail ("$to", "$subject", "$message", "$headers"); 

if($result){
  echo "A email has been sent to: $to";
 }
else{
  echo "Error while sending email";
}