Summary of using custom routes in PHP
Introduction
I have a website written in PHP, which is similar to a personal test site. I designed it independently. I made all possible design and programming mistakes in the process, and I also learned a lot. It also prompted me to learn PHP and MySQL. Whenever I learn a new technology or web practice, I think my website will benefit from it. As you can imagine, it's not very readable. Testing websites often perform poorly in terms of code readability and maintainability, especially when you learn a programming language just for some necessary functionality, which is how I have been learning PHP.
Since I learned about ASP.NET MVC, I have been thinking about how to implement this MVC pattern on this website. I love everything about this whole concept, especially the routing. But I don't want to reconstruct the existing framework of the entire website for this purpose. I am worried that in this way, most of the existing code will become like a foreign object, beyond my control and understanding. The website already had a blog built on WordPress. Modifying the template to make it look like a complete site was like drawing graffiti on a huge wall. It was a mess.
What then? Not long ago, I learned some knowledge about REST API for my daily work. Is there a best way to learn this? I know a website that would benefit from this. After reading some articles on the Internet about applying RESTful API in PHP environment, I learned about .htaccess file. Now that I know how to build routing in PHP, I might be able to implement a small, simple MVC model of my own design on a test site.
Imagination
The key to building custom routing in PHP is to add a .htaccess file, please see below
Detailed implementation:
I added a new "API" folder in the website folder directory, and created a new .htaccess file in it. The content was referenced from a text written by Corey Maynard.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?request=$1 [QSA,NC,L]
Long story short, with this configuration, all requests starting with "www.yoursite.com/api/" or pointing to a non-existent file or path will be redirected to the index.php file. The $1 variable value represents the URL address of the request. The "request" variable name is also easy to understand and can be easily obtained using the $_REQUEST['request'] command.
In addition, the index.php file and the .htaccess file are at the same access level.
Possible problems?
In fact, you may not have enabled the specified module yet.
In the WampServer environment, I need to enable the corresponding module to support local operation. One method is to click the tray icon to enter the "Apache" directory, select rewrite_module in the "Apache modules" list, and then restart all services. Another method is to edit the httpd.conf file and uncomment the following configuration
#LoadModule rewrite_module modules/mod_rewrite.so
I think one of the next things I want to do is make a few self-test pages for the site so I can make sure the person responsible for the site hasn't changed anything. This may sound paranoid and ridiculous, but then again, I need to temporarily add the "set names latin2;" configuration to view the data imported from the database.
If you want to verify that the above configuration is enabled on the server, you can use this code:
echo in_array('mod_rewrite', apache_get_modules());
What’s next?
At this point I have gained some important knowledge that allows me to build a new MVC framework for my website. Working with the new framework was much better than using the existing solution, largely due to the extensive knowledge it gave me in applying the MVC pattern. Since all the code is my own personal work, there are no consumable components.
Go ahead and create a REST API for my website. Now I can essentially pull the database logic out of the web interface.
Useful Links
If you want to know how I found the solution, here is the website I gained my knowledge from http://coreymaynard.com/blog/creating-a-restful-api-with-php/
Translation link: http://www.codeceo.com/article/custom-routing-in-php.html
Original English text: Custom routing in PHP


Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


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

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
