Home Backend Development PHP Tutorial Implementation method of using text files as database in PHP_PHP tutorial

Implementation method of using text files as database in PHP_PHP tutorial

Jul 21, 2016 pm 03:52 PM
php for by Do accomplish according to database document text method of experience structure

Based on my experience, I think the following file structure is optimal:
---------------------------------- ---------------------------------------
File extension: .php

email=ask4more@13.net & nickname=redfox & realname=A Ding & url=http://NetNote.oso.com.cn & ...
...
----------------------------------------- --------------------------------
Maybe everyone can see that it uses .php as the extension, and The first line of the file is , which effectively prevents illegal access to the data file. The format of the second line of the file is: Variable name 1 = value 1 & Variable name 2 = value 2 &...
Proposing all variables is very simple, just use the function parse_str();
For example:
$theline="email=ask4more@13.net&nickname=redfox&realname=A Ding&url=http://NetNote.oso.com.cn";
parse_str($theline);// Separate the variables $email, $nickname, $realname, $url
echo "I am $nickname,my real name is $realname
";
echo "welcome to visit my website:$urlecho "email me at:$email";
?>
Operating results:
I am redfox,my real name is A Ding
welcome to visit my website: http://NetNote.oso.com.cn
email me at:ask4more@13.net

Therefore, this article agrees that the data text structure is:
-------- --------------------------------

Variable name 1 = value 1 & Variable name 2 = value 2 &...

File extension: .php
-------------------------- --------------------------

The real data starts from the second line. Well, using such a file structure, you can easily implement GuestBook, BBS, and even community data processing:) My homepage "Netnote" http://netnote.oso.com.cn is implemented in this way. .
In order to facilitate the majority of netizens, I have compiled several functions, and the necessary explanations will be made below. Of course you can modify and implement it as you like, but you must ensure the integrity of the functionality. Please save the following code as textfun.inc (of course, other names are the same), and add a line of statement at the beginning of the file you want to use, you You can use the function I compiled for you.
There is a db object and a function p2row(); ---
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);//Modify the file mode, also available under 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;"); //To obtain environment variables
eval("$ therow="$therow";");
$fp=fopen($this->$dbfile,"a");
fputs($fp,"$therow");
fclose( $fp);
}
function readall($f){
if(file_exists($f)){
$this->$dbfile=$f;
$rows= file($f);
for($i=1;$i $temp[]=$rows[$i];
}
Return $temp;
}
}
//Read all data lines in reverse order
function revread($f){
if(file_exists($f)){
$this->$dbfile=$f;
$rows=file($f);
$d=count($rows);
$j=$d-1;
for($i=0;$i<$d;$i++){
if($i<$j){
$temprow=$rows[$i];
$rows[ $i]=$rows[$j];
$rows[$j]=$temprow;
$j--; $i $temp[]=$rows[$i];
}
return $temp;
}
}

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

//Format the paragraph text into one line of text for convenience Storage
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;
}
?>
—————————————————————————————————————————————————————— It is our customized data object for this article, including six methods: createdb(), opendb(), insertline(), readall().revread(), close();

db->createdb( string filename)
Usage example: include("textfun.inc");
$mydb=new db;
$mydb->createdb("UserInfo.php");
?>
This method creates a file UserInfo.php, the first line is

db->opendb(string filename)
Usage example: include("textfun.inc");
$mydb=new db;
$mydb->opendb("UserInfo.php");
?>
This method "opens" the data file UserInfo.php in append mode. If this file does not exist, it will be created.
Therefore, this method can replace the createdb() method. (But don’t delete the createdb() function in class db{ } :P)

db->insertline(string VarString)
Usage example: include( "textfun.inc");
$theline="email=ask4more@13.net&nickname=redfox&realname=A Ding&url=http://NetNote.oso.com.cn";
parse_str($theline); //Construct environment variables
$mydb=new db;
$mydb->opendb("UserInfo.php");
$mydb->insertline("nickname|realname|email|url" );
?>
db->insertline() can separate the corresponding environment variables from a string in the form of "nickname|realname|email|url" and store them in the form agreed in this article document. When passing in the parameters of insertline(), you must use "|" to connect the environment variable names into a string. There is no limit to the number, but do not add "$" in front. Well, it must be in the form of "nickname|realname" |email|url" such a string :~)

array db->readall(string filename)
Usage example: include("textfun.inc");
$mydb=new db;
$allrec=$mydb->readall("UserInfo.php");
?>
readall() method returns the first row except the first row (), with each row corresponding to an element of the array.

array db->revread(string filename)
Usage example: include("textfun.inc");
$mydb=new db;
$ allrec=$mydb->revread("UserInfo.php");
?>
revread() method reads in reverse order except the first line (), returns an array. This is especially useful when we are writing guest books etc.

void db->close()
Close the db object.

Okay, now we will use the db object to compile the simplest guestbook. 
---------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下调试通过!

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/318817.htmlTechArticle按我的经验,本人认为,以下列文件结构为最优: ---------------------------------------------------------------------- 文件扩展名:.php ?die('ACCESSDENIED!'...
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)

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,

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 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.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

See all articles