2011-06-07 95 views
2

假設我有一個包含兩個輸入字段,標題和評論的表單。在用戶填充這兩個字段並提交數據後,會自動創建一個頁面,其中包含用戶鍵入的標題和註釋,位於根目錄的文件夾中,例如www.root.com/page/將包含自動生成頁面。如何在用戶通過PHP填寫表單後自動生成頁面?

更新:

我想表單數據被髮送到一個SQL錶行與自動生成網頁的網址是相同的SQL行作爲標題和評論英寸

我該如何通過PHP來做到這一點?

+2

到目前爲止你有什麼? – alex 2011-06-07 06:06:47

+0

你可以這樣做,但通常你會將值存儲在數據庫中,然後在加載頁面時獲取它們。除非你有想寫出文件的實際理由。 – mpen 2011-06-07 06:41:27

回答

5
<?php 
//Template for basic page 
$template = <<<EOD 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title><!--TITLE--></title> 
</head> 

<body> 
<!--COMMENT--> 
</body> 
</html> 
EOD; 

//handle the posted form 
if(isset($_POST['title'])&&isset($_POST['comment'])){ 
    //replace the areas of the template with the posted values 
    $page = str_replace('<!--TITLE-->',htmlentities($_POST['title']),$template); 
    $page = str_replace('<!--COMMENT-->',htmlentities($_POST['comment']),$page); 
    //create a name for the new page 
    $pagename = md5($_POST['title']).'.html'; 

    //db connect & select 
    $db=mysql_connect('localhost','user','pass'); 
    mysql_select_db('yourdb'); 

    //check if page already exists 
    $result = mysql_query('SELECT pagename from yourtable WHERE url="'.mysql_real_escape_string($pagename).'"'); 
    if(mysql_num_rows($result)>=1){ 
     $notice = '<p>Page already created <b>./pages/'.$pagename.'</b></p>'; 
    }else{ 
     //inset new page into db 
     mysql_query('INSERT into yourtable (`id`,`title`,`comment`,`url`)VALUES("", 
     "'.mysql_real_escape_string(htmlentities($_POST['title'])).'", 
     "'.mysql_real_escape_string(htmlentities($_POST['comment'])).'", 
     "'.$pagename.'")'); 
     //put the created content to file 
     file_put_contents('./pages/'.$pagename,$page); 
     //make a notice to show the user 
     $notice = '<p>New Page created <b>./pages/'.$pagename.'</b></p>'; 
    } 
} 
?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Language" content="en-gb"> 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Make page example</title> 
</head> 

<body> 
<?php 
//if the notice is set then display it 
if(isset($notice)){echo $notice;} ?> 
<form method="POST" action=""> 
    <p>Title:<input type="text" name="title" size="31"></p> 
    <p>Comment:</p> 
    <p><textarea rows="5" name="comment" cols="21"></textarea></p> 
    <p><input type="submit" value="Submit"></p> 
</form> 
</body> 
</html> 
+0

我想要將表單數據發送到SQL錶行,並將自動生成的頁面的url與標題和註釋放在同一個SQL行中。 – user701510 2011-06-07 06:48:14

+0

它說在你的問題? – 2011-06-07 06:50:46

+0

對不起,我只記得把它放進去! – user701510 2011-06-07 06:53:39

相關問題