


Use the Thinkphp framework to develop mobile interfaces, thinkphp framework interface_PHP tutorial
Use Thinkphp framework to develop mobile interface, thinkphp framework interface
Option 1: Provide api interface to native APP
When using the TP framework, the file name placed in the common folder is called function.php
<?php /** * Created by zhangkx * Email: zkx520tnhb@163.com * Date: 2015/8/1 * Time: 23:15 */ /*************************** api开发辅助函数 **********************/ /** * @param null $msg 返回正确的提示信息 * @param flag success CURD 操作成功 * @param array $data 具体返回信息 * Function descript: 返回带参数,标志信息,提示信息的json 数组 * */ function returnApiSuccess($msg = null,$data = array()){ $result = array( 'flag' => 'Success', 'msg' => $msg, 'data' =>$data ); print json_encode($result); } /** * @param null $msg 返回具体错误的提示信息 * @param flag success CURD 操作失败 * Function descript:返回标志信息 ‘Error',和提示信息的json 数组 */ function returnApiError($msg = null){ $result = array( 'flag' => 'Error', 'msg' => $msg, ); print json_encode($result); } /** * @param null $msg 返回具体错误的提示信息 * @param flag success CURD 操作失败 * Function descript:返回标志信息 ‘Error',和提示信息,当前系统繁忙,请稍后重试; */ function returnApiErrorExample(){ $result = array( 'flag' => 'Error', 'msg' => '当前系统繁忙,请稍后重试!', ); print json_encode($result); } /** * @param null $data * @return array|mixed|null * Function descript: 过滤post提交的参数; * */ function checkDataPost($data = null){ if(!empty($data)){ $data = explode(',',$data); foreach($data as $k=>$v){ if((!isset($_POST[$k]))||(empty($_POST[$k]))){ if($_POST[$k]!==0 && $_POST[$k]!=='0'){ returnApiError($k.'值为空!'); } } } unset($data); $data = I('post.'); unset($data['_URL_'],$data['token']); return $data; } } /** * @param null $data * @return array|mixed|null * Function descript: 过滤get提交的参数; * */ function checkDataGet($data = null){ if(!empty($data)){ $data = explode(',',$data); foreach($data as $k=>$v){ if((!isset($_GET[$k]))||(empty($_GET[$k]))){ if($_GET[$k]!==0 && $_GET[$k]!=='0'){ returnApiError($k.'值为空!'); } } } unset($data); $data = I('get.'); unset($data['_URL_'],$data['token']); return $data; } }
Query the detailed information of a single fruit
/** * 发布模块 * * 获取信息单个果品详细信息 * */ public function getMyReleaseInfo(){ //检查是否通过post方法得到数据 checkdataPost('id'); $where['id'] = $_POST['id']; $field[] = 'id,fruit_name,high_price,low_price,address,size,weight,fruit_pic,remark'; $releaseInfo = $this->release_obj->findRelease($where,$field); $releaseInfo['remark'] = mb_substr($releaseInfo['remark'],0,49,'utf-8').'...'; //多张图地址按逗号截取字符串,截取后如果存在空数组则需要过滤掉 $releaseInfo['fruit_pic'] = array_filter(explode(',', $releaseInfo['fruit_pic'])); $fruit_pic = $releaseInfo['fruit_pic'];unset($releaseInfo['fruit_pic']); //为图片添加存储路径 foreach($fruit_pic as $k=>$v ){ $releaseInfo['fruit_pic'][] = 'http://'.$_SERVER['HTTP_HOST'].'/Uploads/Release/'.$v; } if($releaseInfo){ returnApiSuccess('',$releaseInfo); }else{ returnApiError( '什么也没查到(+_+)!'); } }
model of findRelease() method
/** * 查询一条数据 */ public function findRelease($where,$field){ if($where['status'] == '' || empty($where['status'])){ $where['status'] = array('neq','9'); } $result = $this->where($where)->field($field)->find(); return $result; }
Data received by the app (after decoding json)
{ "flag": "success", "message": "", "responseList": { "id": "2", "fruit_name": "苹果", "high_price": "8.0", "low_price": "5.0", "address": "天津小白楼水果市场", "size": "2.0", "weight": "2.0", "remark": "急需...", "fruit_pic": [ "http://fruit.txunda.com/Uploads/Release/201508/55599e7514815.png", "http://fruit.txunda.com/Uploads/Release/201508/554f2dc45b526.jpg" ] } }
Data received by the app (native json string)
Copy code The code is as follows:
{"flag":"success","message":"","responseList":{"id":"2","fruit_name":"u82f9u679c","high_price":"8.0","low_price":" 5.0","address":"u5929u6d25u5c0fu767du697cu6c34u679cu5e02u573a","size":"2.0","weight":"2.0","remark":"u6025u9700...","fruit_pic":["http://fruit. txunda.com/Uploads/Release/201508/55599e7514815.png","http://fruit.txunda.com/Uploads/Release/201508/554f2dc45b526.jpg"]}}
Option 2: In addition, we can also use ThinkPHP to automatically switch theme templates for mobile access, so that mobile access can also be achieved
ThinkPHP's template theme mechanism, if it is only on PC, you only need to modify the DEFAULT_THEME (the new version of the template theme is empty by default, which means the template theme function is not enabled) configuration item, you can easily switch between multiple template themes.
But for mobile and PC, you may design completely different theme styles and provide different rendering methods for different sources. One of the more popular methods is "responsive design", but in my case Speaking from experience, it is not that easy to achieve a complete "responsive design", and solving compatibility issues is also a difficult problem. If it is a large site, such as Taobao, Baidu, Paipai, etc., responsive design will definitely not be able to meet the needs. , but a separate mobile website needs to be provided for mobile users.
ThinkPHP is completely doable and quite simple. Just like TPM's intelligent template switching engine, it only needs to judge and process the source.
1. Add ismobile() to {project/Common/common.php}
function ismobile() { // 如果有HTTP_X_WAP_PROFILE则一定是移动设备 if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) return true; //此条摘自TPM智能切换模板引擎,适合TPM开发 if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT']) return true; //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息 if (isset ($_SERVER['HTTP_VIA'])) //找不到为flase,否则为true return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false; //判断手机发送的客户端标志,兼容性有待提高 if (isset ($_SERVER['HTTP_USER_AGENT'])) { $clientkeywords = array( 'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile' ); //从HTTP_USER_AGENT中查找手机浏览器的关键字 if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) { return true; } } //协议法,因为有可能不准确,放到最后判断 if (isset ($_SERVER['HTTP_ACCEPT'])) { // 如果只支持wml并且不支持html那一定是移动设备 // 如果支持wml和html但是wml在html之前则是移动设备 if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) { return true; } } return false; }
2. Create a CommonAction.php in {Project/Lib/}. If your project has a public controller, there is no need to create it, just add it directly.
Class CommonAction extends Action{ Public function _initialize(){ //移动设备浏览,则切换模板 if (ismobile()) { //设置默认默认主题为 Mobile C('DEFAULT_THEME','Mobile'); } //............你的更多代码....... } }
Mobile access can be achieved through the above two methods, one is native and the other is pseudo-native. Friends, please choose according to your own project needs.

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.


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

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor
