Home php教程 php手册 php中用文本文件做数据库的实现方法

php中用文本文件做数据库的实现方法

Jun 13, 2016 pm 12:29 PM
php for by Do accomplish according to database document text method of experience structure

按我的经验,本人认为,以下列文件结构为最优: 
---------------------------------------------------------------------- 
文件扩展名:.php 
 die('ACCESS DENIED!');?> 
email=ask4more@13.net & nickname=redfox & realname=阿鼎 & url=http://NetNote.oso.com.cn & ... 
... 
---------------------------------------------------------------------- 
    也许大家都看出来了,以.php做扩展名,并且文件的第一行是 die('ACCESS DENIED!');?>,这样就有效的阻止了对数据文件的非法访问。文件的第二行的格式都是:  变量名1=值1 & 变量名2=值2 & ... 
    提出所有的变量很简单,就是用函数 parse_str(); 
例如: 
 
$theline="email=ask4more@13.net&nickname=redfox&realname=阿鼎&url=http://NetNote.oso.com.cn"; 
parse_str($theline);//分离出变量$email,$nickname,$realname,$url 
echo "I am $nickname,my real name is $realname
"; 
echo "welcome to visit my website:$url
"; 
echo "email me at:$email"; 
?> 
运行结果: 
I am redfox,my real name is 阿鼎 
welcome to visit my website:http://NetNote.oso.com.cn 
email me at:ask4more@13.net  

    因此,本文约定,数据文本结构为: 
---------------------------------------- 
 die('ACCESS DENIED!');?> 
变量名1=值1 & 变量名2=值2 & ... 

文件扩展名: .php 
---------------------------------------- 

    真正的数据从第二行开始。好了,用这样的文件结构就可以很容易的实现GuestBook,BBS,甚至是社区的数据处理了:)我的主页“网络便签” http://netnote.oso.com.cn ,就是这样实现的。 
    为了方便广大网友,我编了几个函数,下面将作出必要的解释。当然你可以随便的修改和挎贝,但你必须保证功能的完整性。请将下面的代码存为 textfun.inc (当然取其它的名字也是一样的),在你要使用的文件的开始部分加入一行语句,你就可以使用我为你编的函数了。 
下面一共一个db对象,一个函数p2row(); 

-------------textfun.inc---------------- 
 
class db{ 
  var $dbfile; 
  function createdb($dbName){ 
    $f=$dbName; 
    $this->$dbfile=$f; 
    $headInfo="\n"; 
    $fp=fopen($f,"w"); 
    fputs($fp,$headInfo); 
    fclose($fp); 
    chmod($f,0777);//修改文件的模式,在Unix下也可用 
    return(1); 
  } 
  function opendb($f){ 
    $this->$dbfile=$f; 
    if(file_exists($f)){ 
      return true; 
    }else{ 
      $this->createdb($f); 
    } 
  } 
  function insertline($info){ 
    $fields=explode("|",$info); 
    while(list($key,$val)=each($fields)){ 
      $therow.="$val=\$".$val."&"; 
      $var1.="\$".$val.","; 
    } 
    $var1.='$tail'; 
    eval("global $var1;"); //为了取得环境变量 
    eval("\$therow=\"$therow\";"); 
    $fp=fopen($this->$dbfile,"a"); 
    fputs($fp,"$therow\n"); 
    fclose($fp); 
  } 
  function readall($f){ 
    if(file_exists($f)){ 
      $this->$dbfile=$f; 
      $rows=file($f); 
      for($i=1;$i        $temp[]=$rows[$i]; 
      } 
      return $temp; 
    } 
  } 
  //以倒序的方式读入所有的数据行 
  function revread($f){ 
    if(file_exists($f)){ 
      $this->$dbfile=$f; 
      $rows=file($f); 
      $d=count($rows); 
      $j=$d-1; 
      for($i=0;$i        if($i          $temprow=$rows[$i]; 
          $rows[$i]=$rows[$j]; 
          $rows[$j]=$temprow; 
          $j--; 
        } 
      } 
      for($i=0;$i        $temp[]=$rows[$i]; 
      } 
      return $temp; 
    } 
  } 

  function close(){ 
  $this=$nothing; 
  } 


//把段落文本格式化为一行文本,便于存储 
function p2row($t){   
  $t=nl2br(stripslashes(htmlspecialchars($t))); 
  for($i=0;$i    $c=substr($t,$i,1); 
    if(ord($c)==10) $c=" "; 
      $tempstr.=$c; 
    } 
    return $tempstr; 
  } 
?> 
---------------------------------- 

    db是我们自定义的本文数据对象,包括六个方法:createdb(),opendb(),insertline(),readall().revread(),close(); 

db->createdb(string filename) 
用法例: 
    include("textfun.inc"); 
    $mydb=new db; 
           $mydb->createdb("UserInfo.php");     
    ?> 
这个方法创建了一个文件UserInfo.php,首行是 die('ACCESS DENIED!');?> 

db->opendb(string filename) 
用法例: 
    include("textfun.inc"); 
    $mydb=new db; 
           $mydb->opendb("UserInfo.php"); 
    ?> 
这个方法以追加模式“打开”了数据文件UserInfo.php,如果这个文件不存在,则被创建。 
    因此,这个方法可以取代createdb()方法。(但千万别删了class db{  }里面的createdb()函数哦:P) 

db->insertline(string VarString) 
用法例: 
    include("textfun.inc"); 
    $theline="email=ask4more@13.net&nickname=redfox&realname=阿鼎&url=http://NetNote.oso.com.cn"; 
    parse_str($theline);//构造环境变量 
    $mydb=new db; 
           $mydb->opendb("UserInfo.php"); 
    $mydb->insertline("nickname|realname|email|url"); 
    ?> 
db->insertline()可以将形如"nickname|realname|email|url"的字符串,分离出相应的环境变量,并以本文约定的形式存入文件。 传入insertline()的参数,一定要用“|”把环境变量名连成字符串,个数不限,但千万别在前面加"$"哦,嗯,就是要形如"nickname|realname|email|url"这样的字符串  :~) 

array db->readall(string filename) 
用法例: 
    include("textfun.inc"); 
    $mydb=new db; 
    $allrec=$mydb->readall("UserInfo.php"); 
    ?> 
readall()方法返回除首行( die('ACCESS DENIED!');?>)外所有数据的数组,每行对应于数组的一个元素。 

array db->revread(string filename) 
用法例: 
    include("textfun.inc"); 
    $mydb=new db; 
    $allrec=$mydb->revread("UserInfo.php"); 
    ?> 
revread()方法以倒序方式读入除首行( die('ACCESS DENIED!');?>)外所有数据,返回数组。这对我们在编留言本等时候尤为有用。 

void db->close() 
        关闭db对象。 

好了,我们现在就用db对象编一个最简单的留言本。 
---------guestbook.php------------ 
我的留言本

 


NickName:
 
E-Mail:
 
Homepage:
 
Message:

 
 

 
 
include("textfun.inc"); 
if($Submit){ 
  $thetime=date("Y-m-d h:m:s A"); 
  $message=p2row($message); 
  $mydb=new db; 
  $mydb->opendb("msg.php"); 
  $mydb->insertline("nickname|email|url|message|thetime"); 

  //以下读出所有的数据 
  $allrecs=$mydb->revread("msg.php"); 
  while(list($key,$theline)=each($allrecs)){ 
    parse_str($theline); 
    ?> 
    ">
 
    URL:">
 
    Message:

 
     
  } 
  $mydb->close(); 

?> 
----------------------------- 
好了,虽然这个留言本不是很美观,但主要是为了举例说明db对象的用法~:) 
本文在WIN98+PWS+PHP4下调试通过!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles