標籤:mysql php
上篇文章中講到,story.php中的表單提交之後的頁面是story_submit.php,我們就看一下story_submit.php是如何完成文章的發表的
老樣子,先上代碼:
<?php# add / modify story recordinclude_once('include_fns.php');$handle = db_connect();$headline = $_REQUEST['headline'];$page = $_REQUEST['page'];$time = time();if ((isset($_FILES['html']['name']) && (dirname($_FILES['html']['type']) == 'text') &&is_uploaded_file($_FILES['html']['tmp_name']) )) {// if user upload some files, then set the content of the files as the story_text$story_text = file_get_contents($_FILES['html']['tmp_name']);}else{$story_text = $_REQUEST['story_text'];}$story_text = addslashes($story_text);if (isset($_REQUEST['story']) && $_REQUEST['story']!='') {# it's an update$story = $_REQUEST['story'];$query = "update stories set headline = '$headline', story_text = '$story_text', page = '$page', modified = $time where id = $story";}else{// it's a new story$query = "insert into stories (headline,story_text,page,writer,created,modified) values ('$headline','$story_text','$page','".$_SESSION['auth_user']."', $time,$time)";}$result = mysql_query($query);if (!$result) {# code...echo "There was a database error when executing <pre>$query</pre>";echo mysql_error();exit; }if ((isset($_FILES['picture']['name']) && is_uploaded_file($_FILES['picture']['tmp_name']))) {# there is uploaded pictureif (!isset($_REQUEST['story']) || $_REQUEST['story']=='') {$story = mysql_insert_id($handle);// mysql_insert_id return the auto generated id used in the last query}$type = basename($_FILES['picture']['type']);switch ($type) {case 'jpeg':case 'pjpeg':case 'png':case 'jpg':$filename = "images/$story.jpg";move_uploaded_file($_FILES['picture']['tmp_name'], '../'.$filename);$query = "update stories set picture = '$filename' where id = $story";$result = mysql_query($query);break;default:echo 'Invalid picture format:'.$_FILES['picture']['type'];break;}}else{// there is no image file to upload or didn't get the file's infoecho 'Possible file upload attack:';echo "filename '".$_FILES['picture']['tmp_name']."'.";}header('Location: '.$_REQUEST['destination']);?>
我們還是先從整體捋一遍代碼:
第7,8行
這兩個變數都是從上一個頁面story.php提交表單中擷取的參數
第9行
time函數返回的是時間戳記
11-18行
這部分代碼返回的是上傳的html檔案的內容
第20行
這裡用到了php中發送text內容到資料庫的一個函數:addslashes,作用是在一些特定的符號前面加上/ 符號,特定的符號有‘, ‘‘ , nul, \等,
例如:
然後我在搜尋這個函數是,發現了另外的方法mysql_escape_string,
22-39行
根據傳入的參數中有沒有story來判斷是更新還是新添加的story,這裡之前我們也有提到了。
50-75行
是標準的php上傳檔案的步驟,可以試著記一下
注意第54行,是得到自增序列的下一個欄位
最後第82行
我們上一篇blog裡面有提到過,在form提交了兩個hidden的參數,其中一個是destination,其實就是writer.php頁面了。
好了,基本上這個頁面沒有什麼特別難的地方。
我們在來看更簡單的 delete_story.php
通過check_permission函數來確定目前使用者是否有修改的許可權,如果有,就把當前的文章刪除。
check_permission是在user_auth_fns.php檔案中
好了,文章的修改和建立部分我們都全部介紹完了,下一篇blog,我們來介紹publish相關的3個檔案
一步一步教你用PHP+MySql搭建網站 No.5 圖片上傳、故事刪除