2011-06-07 91 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

相关问题