2016-01-22 40 views
1

我做了一個表格,我希望用戶提交作爲整個PDF保存在服務器上。我一直在試圖讓一個PHP腳本,來處理在文件基本上,我已經從學校W3拍攝的榜樣,努力去適應它:處理PDF格式提交作爲整個pdf使用PHP

<?php 
$file = file_get_contents("php://input"); 
$target_dir = "uploads/"; 
$target_file = $target_dir . basename($file); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
// Check if $uploadOk is set to 0 by an error 
if ($uploadOk == 0) { 
    echo "Sorry, your file was not uploaded."; 
// if everything is ok, try to upload file 
} else { 
    if (move_uploaded_file($file, $target_file)) { 
     echo "The file ". basename($file). " has been uploaded."; 
    } else { 
     echo "Sorry, there was an error uploading your file."; 
    } 
} 
?> 

但是,它不工作。我收到第二條錯誤消息:「對不起,上傳文件時出現錯誤。」

我對PHP相當陌生,將不勝感激一些幫助。

謝謝!

更新:所有的文檔和示例都涉及來自HTML表單的POST數據,因此每個輸入字段名稱都是已知的。我的PDF使用隨機名生成服務器端,所以我必須修改這些示例。我做了這個一個與HTML表單的工作:

<?php 
foreach ($_FILES as $name => $value) 
$target_dir = "uploads/"; 
$target_file = $target_dir . basename($_FILES[$name]["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
move_uploaded_file($_FILES[$name]["tmp_name"], $target_file) 
?> 

然而,當我使用的Adobe Acrobat PDF格式本身提交,我得到了一系列錯誤:

http://localhost/save.php[22/01/2016 20:23:05] 
Notice: Undefined variable: name in C:\xampp\htdocs\save.php on line 4 
Notice: Undefined index: in C:\xampp\htdocs\save.php on line 4 
Notice: Undefined variable: target_dir in C:\xampp\htdocs\save.php on line 4 
Notice: Undefined variable: name in C:\xampp\htdocs\save.php on line 7 
Notice: Undefined index: in C:\xampp\htdocs\save.php on line 7 

雖然我的腳本上傳文件從HTML表單不需要知道輸入字段名稱(在文檔示例中總是已知),我很高興它從PDF本身提交時不起作用。

有誰知道這是爲什麼?

+1

看起來您正在混合上傳文件的兩種方法,並且完全不執行任何操作。只需使用文檔中的示例:http://php.net/manual/en/features.file-upload.post-method.php –

回答

0

如果您通過發送整個文檔提交PDF表格,您只需將原始發佈數據作爲文檔數據。沒有單獨的帖子字段,但是:

$fileContent = file_get_contents("php://input"); 

...就夠了。您現在已經在$ fileContent中擁有整個PDF文檔。所以保存這個(驗證後!),你就完成了。