2011-10-25 40 views
-2

我正在嘗試做一些簡單的表單驗證,確保輸入的內容不超過某個字符數限制,但似乎無法使其工作。當我嘗試運行此代碼:PHP include()問題

$str = "?id="; 
$id = $_POST['ID']; 

if (strlen($_POST['fname']) > 1) { 
    $message = "Character cannot be more than..."; 
    include 'edit.php' . $str . $id; 
    exit(); 
} 

我得到這個錯誤:

Warning: include(edit.php?id=97) [function.include]: failed to open stream: No such file or directory in /Applications/MAMP/htdocs/update.php on line 15 

Warning: include() [function.include]: Failed opening 'edit.php?id=97' for inclusion (include_path='.:/Applications/MAMP/bin/php/php5.3.6/lib/php') in /Applications/MAMP/htdocs/update.php on line 15 

從我一直在讀什麼,它實際上是要找的文件edit.php?id=97,而不是尋找edit.php和追加ID。我不知道該怎麼做。有什麼建議麼?提前致謝。

+0

什麼是'$ str'和'$ id'值是多少? –

+0

^id = and 97 ... –

+0

爲什麼你在提問之前不會閱讀[documentation](http://php.net/manual/en/function.include.php)? 'Example#3 include()through HTTP' – Peter

回答

1

你不能包含你想要的文件。嘗試刪除?id=x部分,它應該仍然有效。

4

包含文件只是一個文件,它不是一個HTTP請求,因此GET參數在該上下文中沒有意義。如果需要,您可以訪問$id$str

可以通過HTTP包括(以有效的協議字符串),如果你的php.ini有它啓用(allow_url_include,默認禁用),但我不會推薦它。

+0

最佳答案+1。 – mpen

+0

+1有禮貌且樂於助人。 – Peter

2

您不能include一個具有HTTP查詢參數的本地文件。

在猜測,我會說你想要做一個頭重定向

header(sprintf('Location: http://your-domain.com/edit.php?id=%d', $id)); 
exit; 

這且不說,我覺得它更容易按照此工作流程處理表單時:

  1. GET表單頁面。表單行爲是相同的頁面
  2. POST表單數據。檢測POST方法並驗證結果
  3. 如果有效,重定向到成功頁面。如果不符合,通知/標誌重新顯示形式
+0

如果他這樣做,他也必須同時傳遞'$ message'。此外,這可能是有用的:http://ca2.php.net/manual/en/function。http-build-query.php – mpen

+0

@Mark,是對的,這個問題是錯誤的:) –

+0

@Mark可以使用一個flash-messenger模式(一次性會話消息),但如前所述,我更喜歡處理表單處理同樣的文件,並且如果無效則重新顯示,這將使'$ message'可用。 – Phil

0

如果你真的想這樣做的......

if (strlen($_POST['fname']) > 1) { 
    $message = "Character cannot be more than..."; 
    echo file_get_contents('http://example.com/edit.php'.$str.$id.'&message='.$message); 
    exit(); 
} 

但嘗試像這樣...

if (strlen($_POST['fname']) > 1) { 
    $message = "Character cannot be more than..."; 
    include_once 'edit.php'; 
    exit(); 
} 

或告訴我們你真正想做什麼...

+0

沒有工作。我需要它回到顯示id所持內容的頁面。第一個叫它,但不會顯示錯誤消息($ message)。 – thelos999

+0

@ thelos999,如果你在'edit.php'中'echo $ _GET ['message']',它現在可以工作...... –

0

在您的收錄文件中:

include('edit.php'); 

內edit.php的:

$id = $_POST['id']; 
+1

變量已經通過了(實際上來自edit.php的代碼被傳遞給父腳本),不需要那樣做。 –

+1

認爲它會使edit.php更加可重用,而不是通過包含腳本來設置id變量。 –