PHP基础开发代码示例~
最近打算重拾PHP来开发一些小型应用,很久没用PHP了,有些语法都生疏了,今天上午写了三个例子,基本上把之前的PHP复习了一下。
基础语法操作:
<?php //输出的方式测试echo '###################输出测试################<br>';echo '测试输出1(单引号)<br>';echo "测试塑出2(双引号)<br>";?>='测试输出3(=表达式)<br>'?> echo '测试输出4(单个表达式)<br>'; ?><?php //类型echo '###################类型测试################<br>';$testInt = 1;$testStr = "字符串";$testFloat = 1.23;$testBoolean = false; //false/true:如果转换成字符串则为空/"1",转换成整型则为0/1$testArray = array("first"=>1,2,3,4,5);$testStr2 = $testStr; //testStr修改,testStr2不会修改$testStr3 = &$testStr; //testStr修改,testStr3也会修改echo '整型:'.$testInt.'<br>';echo '字符串型:'.$testStr.'<br>';$testStr = '字符串修改了';echo '字符串型修改后:'.$testStr.'<br>';echo '字符串型修改后(2):'.$testStr2.'<br>';echo '字符串型修改后(3):'.$testStr3.'<br>';echo '浮点型:'.$testFloat.'<br>';echo '布尔型:'.(int)$testBoolean.'<br>';echo '数组测试(1):'.$testArray[0].'<br>';echo '数组测试(2):'.$testArray['first'].'<br>';print_r($testArray);echo '<br>';foreach ($testArray as $i => $value) { echo '数组迭代结果:'.$i."->".$value."<br>";}//IO操作echo '##################IO操作####################<br>';echo '读取该文件的内容:<br>';$theFileName = "test_base.php"; //文件名称或者全路径$handle = fopen ($theFileName, "rb");$contents = fread ($handle, filesize ($theFileName));fclose ($handle); echo '<div style="border:1px solid #aaa;color:blue;"><pre class="brush:php;toolbar:false">'.htmlspecialchars($contents).'
数据库的处理:
<?php //四种引用方式//require 'test_base.php'; //无条件的引用,报错会终止应用,引用的文件只处理一次//require_once 'test_base.php'; //无条件的引用,报错会终止应用,引用的文件只处理一次并只显示一次//include 'test_base.php'; //可有条件的引用,报错不会终止应用,引用的文件处理多次//include_once 'test_base.php'; //可有条件的引用,报错不会终止应用,引用的文件处理多次但只显示一次//数据库的测试$hostname = '192.168.1.6'; /*数据库服务器访问地址*/$username = 'root'; /*数据库用户帐号*/$password = 'root'; /*数据库密码*/$database = 'phptest'; /*数据库名称*/$databaseCharset = 'GBK'; /*数据库编码,防止插入中文乱码和报错*///获取请求信息$actionSubmit = $_REQUEST['submit'];$reqTheType = $_REQUEST['theType'];if($reqTheType == null || $reqTheType == '') { $reqTheType = '1';}echo '请求信息:'.$actionSubmit."|".$reqTheType.'<br>';if($actionSubmit != null && $actionSubmit != '') { if($reqTheType == '1') { testSearch(); } if($reqTheType == '2') { testInsert(); testSearch(); } if($reqTheType == '3') { testUpdate(); testSearch(); }}/** * 数据库查询 * Enter description here ... */function testSearch() { echo '查询数据<br>'; global $hostname,$username,$password,$database,$databaseCharset; $currentConn = null; $currentConn = mysql_connect ( $hostname, $username, $password ); mysql_select_db ( $database ); mysql_query("set names charset ".$databaseCharset); mysql_query("set names ".$databaseCharset); $result = mysql_query ( "select * from e_user" ); //查询动作返回的是result结果集 while ( $row = mysql_fetch_object ( $result ) ) { echo $row->uri . "\t" . ($row->username) . "<br>"; } mysql_free_result ( $result ); mysql_close ( $currentConn );}/** * 数据库数据添加 * Enter description here ... */function testInsert() { global $hostname,$username,$password,$database,$databaseCharset; $insertSql = "insert into e_user(uri,username,password) values"; $insertSql .= "("; $insertSql .= "'".generateId()."','测试用户','123456'"; $insertSql .= ")"; $currentConn = null; $currentConn = mysql_connect ( $hostname, $username, $password ); mysql_select_db ( $database ); mysql_query("set names charset ".$databaseCharset); mysql_query("set names ".$databaseCharset); echo '添加数据'.$insertSql.'<br>'; $result = mysql_query($insertSql); //插入动作返回的是boolean if(!$result) { die('Error: ' . mysql_error()); } mysql_close ( $currentConn );}/** * 数据库修改 * Enter description here ... */function testUpdate() { global $hostname,$username,$password,$database,$databaseCharset; $updateSql = "update e_user"; $updateSql .= " set username='修改后的用户名称' where uri = '001'"; $currentConn = null; $currentConn = mysql_connect ( $hostname, $username, $password ); mysql_select_db ( $database ); mysql_query("set names charset ".$databaseCharset); mysql_query("set names ".$databaseCharset); echo '修改数据'.$updateSql.'<br>'; $result = mysql_query($updateSql); //插入动作返回的是boolean if(!$result) { die('Error: ' . mysql_error()); } mysql_close ( $currentConn );}/** * 自动生成ID号 * @param unknown_type $count */function generateId($count = 6) { $resultId = ''; for($i=0;$i
面向对象编程:
<?php //基础的抽象用户类abstract class BaseUser { protected $flag = 0; abstract function showInfo();}//接口类interface Module { function start(); function stop();}//测试PHP类和对象class MyUser extends BaseUser implements Module { /*成员变量*/ private $uri = ''; private $type = ''; protected $username = ''; public $password = ''; /*静态变量*/ const USER_TYPE_NORMAL = "normal"; /*构造函数*/ function __construct($uri = '',$username = '', $password = '') { $this->uri = $uri; $this->username = $username; $this->password = $password; $this->flag = '100'; $this->type = self::USER_TYPE_NORMAL; } /*测试静态函数的处理*/ static function testStatic() { //$this->username = 'static'; //该方法是错误的,静态方法中只能操作静态变量 return self::USER_TYPE_NORMAL; } /*get set 方法用于管理内部的字段属性*/ public function getUri() { return $this->uri; } public function getUsername() { return $this->username; } public function getPassword() { return $this->password; } public function setUri($uri) { $this->uri = $uri; } public function setUsername($username) { $this->username = $username; } public function setPassword($password) { $this->password = $password; } public function getType() { return $this->type; } public function setType($type) { $this->type = $type; } /*实现底层的抽象方法*/ function showInfo() { echo '我是MyUser对象.'; } //实现接口方法 public function start() { echo '启动MyUser对象....'; } //实现接口方法 public function stop() { echo '停止MyUser对象....'; }}//扩展自MyUser的类class MyExtendUser extends MyUser implements Module { /*覆盖父类的构造函数*/ function __construct($uri = '',$username = '', $password = '') { //调用父类的构造函数 parent::__construct($uri,$username,$password); //实现自己的一些初始化动作 $this->flag = '200'; } /*覆盖父类的getUsername方法*/ public function getUsername() { return '继承自MyUser,'.$this->username; } //实现接口方法 public function start() { echo '启动MyExtendUser对象....'; } //实现接口方法 public function stop() { echo '停止MyExtendUser对象....'; }}//测试用户对象$theUserObj = new MyUser('001','测试用户1','123');echo '用户名称:'.$theUserObj->getUsername().'<br>';print_r($theUserObj);echo '<br>';echo '测试静态函数1:'.$theUserObj->testStatic().'<br>';echo '测试静态函数2:'.MyUser::testStatic().'<br>';echo '测试实现的接口:';$theUserObj->start();echo '<br>';//测试继承$theUserObj2 = new MyExtendUser('002','测试用户2','123');echo '用户名称2(继承):'.$theUserObj2->getUsername().'<br>';print_r($theUserObj2);echo '<br>';echo '测试实现的接口2:';$theUserObj2->start();echo '<br>';?>

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
