search
HomeBackend DevelopmentPHP TutorialPHP+XML making a simple guestbook graphic tutorial_PHP tutorial

PHP+XML making a simple guestbook graphic tutorial_PHP tutorial

Jul 21, 2016 pm 03:42 PM
uploadmakereleasebackGraphics and textpicturepasswordTutorialshowmessageLog inofSimpleenterpage

1. 留言显示页面

2. 发布留言,并允许上传图片

3. 输入密码登录后可以删除留言。

1. 文件目录

 

upfile是保存上传图片的目录。

2. 主要界面

(1)首页,显示留言页面

 

 

 

(2)发表留言页面

 

3. XML文档格式,名称为data.xml

 

各字段的含义不多说,各元素的值看起来有点怪,是因为我使用了base64_encode对字符串进行了编码。

 

4 主要页面代码

(1)add.php

此页只是纯粹的HTML代码

action="saveadd.php" enctype="multipart/form-data" method="post" name="myform" onsubmit="return go(this)">

 
  
  
 
 
  
  
 
 
  
  
 
 
  
  
 
 
  
  
 
 
  
 
作者
标题
表情
   
   PHP+XML making a simple guestbook graphic tutorial_PHP tutorial
  
内容
截图

(2)savadd.php

用于保存留言信息

if(!$_POST["author"] || !$_POST["content"]) 
{
 echo "\n";
 echo "你没有填写留言姓名或内容,2秒钟返回首页";
 exit();
}else{
 $imgflag=0;   //用于判断是否需要上传图片
 function random($length)   //此函数用于生成一个随机的图片文件名(不含扩展名),以防止与现有图片重复
 {
  $hash = 'IMG-';
  $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
  $max = strlen($chars) - 1; 
  for($i = 0; $i   {
   $hash .= $chars[mt_rand(0, $max)];
  }
  return $hash;
 }

 function fileext($filename)   //此函数用于获取上传文件的扩展名
 {
  return substr(strrchr($filename, '.'), 1);
 }
 

 if($_FILES["upfile"]["name"]!=""){
  $uploaddir="upfile/";   //图片保存路径
  $type=array("jpg","gif","bmp","jpeg","png");   //允许上传的文件类型

  if(!in_array(strtolower(fileext($_FILES['upfile']['name'])),$type))   //如果上传的文件的扩展名不符合要求
  {
   echo "\n";
   $text=implode(",",$type);
   echo "您只能上传以下类型文件: ",$text,"
";
   exit();
  }
  else
  {
   $filename=explode(".",$_FILES['upfile']['name']);
   do
   {
    $filename[0]=random(10);
    $randname=implode(".",$filename);     //得到的最终随机生成的文件名(连同扩展名)
    $uploadfile=$uploaddir.$randname;
   } while(file_exists($uploadfile));

   if (move_uploaded_file($_FILES['upfile']['tmp_name'],$uploadfile)){   //保存上传的图片到upfile文件夹
    echo "上传图片成功";
    $imgflag=1;
   }
   else{
    echo "上传图片失败!";
    $imgflag=0;
   }

  }
 }

//获取其他表单域

 $author=base64_encode($_POST["author"]);  
 $content=base64_encode(ereg_replace("\r\n","
",$_POST["content"]));
 $smiles=base64_encode($_POST["smiles"]);
 if($_POST["title"]){
  $title=base64_encode($_POST["title"]);
 }else{
  $title=base64_encode("无标题");
 }
 $addtime=date("Y-m-d");
 if($imgflag==1){  //如果有上传图片
  $photo=base64_encode($randname);
 }else{  //否则将photo元素的值设置为NONE
  $photo="NONE";
 }

 $dom=new DOMDocument('1.0','gb2312');   //指定XML的格式
 $dom->load("data.xml");     //加载
 $root=$dom->getElementsByTagName("messages");   //获取根节点
 $root=$root->item(0);       
 $last_id=$root->lastChild->firstChild->nodeValue;  //获取最后一个message的第一个子节点(即id节点)的值
 $id=$last_id+1;  //新增消息的id
 settype($id,"string");  //将其转换为字符型


 $message=$root->appendChild(new DOMElement('message'));  //添加message节点
 $el_id=$message->appendChild(new DOMElement('id'));  //添加message节点的各个子节点
 $el_id->appendChild($dom->createTextNode($id));

 $el_author=$message->appendChild(new DOMElement('author'));
 $el_author->appendChild($dom->createTextNode($author));

 $el_title=$message->appendChild(new DOMElement('title'));
 $el_title->appendChild($dom->createTextNode($title));

 $el_smiles=$message->appendChild(new DOMElement('smiles'));
 $el_smiles->appendChild($dom->createTextNode($smiles));

 $el_content=$message->appendChild(new DOMElement('content'));
 $el_content->appendChild($dom->createTextNode($content));

 $el_addtime=$message->appendChild(new DOMElement('addtime'));
 $el_addtime->appendChild($dom->createTextNode($addtime));

 $el_photo=$message->appendChild(new DOMElement('photo'));
 $el_photo->appendChild($dom->createTextNode($photo));

 $dom->save("data.xml");  //保存XML


 echo "\n";
 echo "谢谢您的留言,2秒钟返回首页";

}
?>

(3)index.php

本页面用于显示留言信息

添加留言

$dom=new DOMDocument('1.0','gb2312');   
$dom->load("data.xml");       //加载
$root=$dom->getElementsByTagName("messages"); 
$root=$root->item(0);      
$message=$root->getElementsByTagName("message");   //获取所有message节点

$message_count=$message->length;   //计算有多少条留言
echo "当前共有".$message_count."条留言";

if($message_count==0){
 echo "暂时没有留言\n";
}else{
?>


 for($i=$message_count-1;$i>=0;$i--)    //我们需要对留言按倒序排列
 {
  $msg=$message->item($i);

  foreach($msg->childNodes as $child)   //message节点的各个子节点
  {
   if($child->nodeName=="id")
   {
    $id=$child->nodeValue;
   }
   if($child->nodeName=="author")
   {
    $author=$child->nodeValue;
   }
   if($child->nodeName=="title")
   {
    $title=$child->nodeValue;
   }
   if($child->nodeName=="smiles")
   {
    $smiles=$child->nodeValue;
   }
   if($child->nodeName=="content")
   {
    $content=$child->nodeValue;
   }
   if($child->nodeName=="photo")
   {
    $photo=$child->nodeValue;
   }
   if($child->nodeName=="addtime")
   {
    $addtime=$child->nodeValue;
   }

  }
  echo "";
  echo "";
  echo "";
  if($photo!="NONE")
  {
   echo "";
  }
 }
?>
}
?>
";
  echo $id.".PHP+XML making a simple guestbook graphic tutorial_PHP tutorial".base64_decode($title)." - ".base64_decode($author)." [".$addtime."] ";  
  if(isset($_SESSION["password"]) && $_SESSION["password"]!="")  //如果输入了密码显示删除链接
  {
   echo "[删除]";
  }
  echo "
".base64_decode($content)."
PHP+XML making a simple guestbook graphic tutorial_PHP tutorial

 if(isset($_SESSION["password"]) && $_SESSION["password"]!=""){
?>

退出管理

 
}else{
?>

登陆管理

 
}
?>

 

(4) 删除留言

if(isset($_SESSION["password"]) && $_SESSION["password"]!="")
{

$dom=new DOMDocument;
$dom->load("data.xml");
$root=$dom->getElementsByTagName("messages");
$root= $root->item(0);
foreach($root->childNodes as $msg)
{
if($msg->firstChild->nodeValue==$_GET[" id"]) //If the value of the id child node of the message node is equal to the id to be deleted
{
$photo=$msg->lastChild->nodeValue;
if($photo! ="NONE"){ //If the message contains pictures, the pictures should also be deleted
$photo_path="upfile/".base64_decode($photo);
$flag=unlink($photo_path);
if($flag){
echo "Picture deleted successfully
";
}
}

$root->removeChild($msg);
break;
}
}
$dom->save("data.xml");


?>

Delete message successfully, return to homepage in 2 seconds

}else {
?>
You are not logged in yet, return to the login page in 2 seconds

}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320900.htmlTechArticle1. Message display page 2. Post a message and allow uploading of pictures 3. You can delete the message after logging in with your password. 1. File directory upfile is the directory where uploaded images are saved. 2. Main interface (...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.