2011-10-29 84 views
1

EDITED來澄清問題。一個文件上傳表單,它將變量傳遞給主要的html

在哪裏我想:裏面的index.html

  1. 的文件上傳表單。 (完成)
  2. 表單提交給PHP文件。 (完成)
  3. PHP文件將文件移動到正確的位置。 (完成)
  4. index.html被重新載入,PHP退出。 (完成)
  5. index.html從PHP獲取上傳文件的位置以便稍後使用它。 (撤消)

我不知道,我怎麼給從PHP參數回index.html的,或可問題是我不明白,怎麼PHP和HTML交換信息。

所以問題是,這種功能是否可以用Ajax編寫,這樣我就不需要「走出」我的index.html。

我有這種形式我的HTML中:

<form method="post" enctype="multipart/form-data" action="uploader.php"> 
<input type="file" name="uploadedfile"/> 
<input type="submit" name="submit" class="button" value="Submit"></button> 
</form> 

並調用PHP,看起來是這樣的:

<?php 
$target_path = "uploads/"; 
$target_path = $target_path . ($_FILES["uploadedfile"]["name"]); 
if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_path)) { 
echo "Success!" 
} else{ 
echo "There was an error uploading the file, please try again!"; 
} 
header('Location: http://localhost/index.html'); 
exit(); 
?> 

按下提交後,文件正確上傳到服務器。

+2

你能澄清這個問題嗎? – svinto

+0

這是線圈型問題 – leon

+0

除非您澄清,否則您的問題將被關閉。 – Nasreddine

回答

0

您可以將您的index.html文件更改爲一個php文件,以便它可以嵌入一些PHP代碼,然後執行如下所示的操作。

的index.php

<form method="post" enctype="multipart/form-data" action="uploader.php"> 
<input type="file" name="uploadedfile"/> 
<input type="submit" name="submit" class="button" value="Submit"></button> 
</form> 

<?php 
if($_POST['target']){ 
    //Do stuff with the target 
} 
?> 

uploader.php

<?php 
$target_path = "uploads/"; 
$target_path = $target_path . ($_FILES["uploadedfile"]["name"]); 
if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_path)) { 
echo "Success!" 
} else{ 
echo "There was an error uploading the file, please try again!"; 
} 

//The following code POSTs data to index.php 
$params = array('http' => array(
      'method' => 'POST', 
      'content' => array('target' => $target_path) 
     )); 
$ctx = stream_context_create($params); 
$fp = @fopen('index.php', 'rb', false, $ctx); 
if (!$fp) { 
    throw new Exception("Problem with index.php, $php_errormsg"); 
} 
$response = @stream_get_contents($fp); 
if ($response === false) { 
    throw new Exception("Problem reading data from $url, $php_errormsg"); 
} 
return $response; 
?> 

希望這給你一些想法。

+0

感謝您的回答!我測試過,但我卡在uploader.php,我無法回到index.php。我想返回應引導回到index.php,但不知何故它不。 – Geolassi