Session handling is a key concept in PHP that enables user information to be persisted across all the pages of a website or app. In this post, you'll learn the basics of session handling in PHP. Show
We'll start with an explanation of how sessions work and how they are related to cookies. Then we'll look at a few code snippets that demonstrate how to work with sessions. You'll learn how to create and destroy sessions, and how to change session variables. Cookies vs. Session VariablesNot sure if you need cookies or session variables? Session variables are a way to store data about a user in a database and retrieve it later. Cookies are a way to store data about a user on the user's computer. Session variables are typically used in applications that need to keep track of a user's activity. Cookies are typically used in applications that need to store information about a user for a single site. You can also learn about session variables in my post on using cookies in PHP.
What Is a Session in PHP?A session is a mechanism to persist information across different web pages to identify users as they navigate a site or app. Are you wondering why sessions are needed for a website? To see why sessions are necessary, we have to go back and see how the HTTP protocol is designed to work. The HTTP protocol is a stateless protocol, which means that there's no way a server can remember a specific user between multiple requests. For example, when you access a web page, the server is just responsible for providing the contents of the requested page. So when you access other pages of the same website, the web server interprets each and every request separately, as if they were unrelated to one another. There's no way for the server to know that each request originated from the same user. The following diagram depicts the HTTP protocol in a nutshell. In this model, if you wanted to display user-specific information, you'd have to authenticate a user in each request. Imagine if you had to type your username and password on every page that displayed your profile information! Yes, it would be cumbersome and not practical at all, and that's where sessions come into the picture. A session allows you to share information across different pages of a single site or app—thus it helps maintain state. This lets the server know that all requests originate from the same user, thus allowing the site to display user-specific information and preferences. Login Flow With Sessions and CookiesLet's quickly go through a common login flow for a website to understand what happens behind the scenes.
In this way, the user data is preserved across multiple requests, and the user is kept logged in throughout a session. The following diagram depicts how the HTTP protocol works with sessions. Now that you've seen a brief introduction to how sessions work, we'll create a few practical examples to demonstrate how to create and manipulate session variables. How to Start a SessionIn this section, we’ll discuss how to start a session in PHP. Whenever you want to deal with session variables, you need to make sure that a session is already started. There are a couple of ways you can start a session in PHP. Use the 353 FunctionThis is the method that you'll see most often, where a session is started by the 353 function. 1 <?php
2 // start a session
3 session_start(); 4 5 // manipulate session variables
<?php
0<?php
1The important thing is that the 353 function must be called at the beginning of the script, before any output is sent to the browser. Otherwise, you’ll encounter the infamous 356 error. Automatically Start a SessionIf there’s a need to use sessions throughout your application, you can also opt in to starting a session automatically without using the 353 function. There’s a configuration option in the php.ini file which allows you to start a session automatically for every request— 358. By default, it’s set to 359, and you can set it to 360 to enable the auto startup functionality. 1 <?php
3On the other hand, if you don’t have access to the php.ini file, and you're using the Apache web server, you could also set this variable using the .htaccess file. 1 <?php
5If you add the above line in the .htaccess file, that should start a session automatically in your PHP application. How to Get a Session IdAs we discussed earlier, the server creates a unique number for every new session. If you want to get a session id, you can use the 361 function, as shown in the following snippet. 1 <?php
2 session_start(); 3 21 4 <?php
1That should give you the current session id. The 361 function is interesting in that it can also take one argument—a session id. If you want to replace the system-generated session id with your own, you can supply it to the first argument of the 361 function. 1 <?php
2 27 3 session_start(); 4 <?php
1It’s important to note that the 361 function must be placed before the 353 call when you want to start a session with a custom session id. How to Create Session VariablesIn this section, we’ll explore how to initialize session variables in PHP. As we discussed earlier, once a session is started, the 352 super-global array is initialized with the corresponding session information. By default, it’s initialized with a blank array, and you can store more information by using a key-value pair. Let’s go through the following example script that demonstrates how to initialize session variables. 1 <?php
2 // start a session
3 session_start(); 4 5 31 <?php
033 34 35 36 38 39 session_start();0 session_start();1 session_start();2 session_start();3 session_start();4 <?php
1As you can see, we’ve started a session at the beginning of the script using the 353 function. Following that, we’ve initialized a couple of session variables. Finally, we’ve accessed those variables using the 352 super-global. When you store the data in a session using the 352 super-global, it’s eventually stored in a corresponding session file on the server which was created when the session was started. In this way, the session data is shared across multiple requests. As we discussed, the session information is shared across requests, and thus the session variables initialized on one page can be accessed from other pages as well, until the session expires. Generally, a session expires when the browser is closed. How to Modify and Delete Session VariablesYou can modify or delete session variables created earlier in the application in the same way as for regular PHP variables. Let’s see how to modify the session variables. 1 <?php
2 session_start(); 3 4 43 5 45 <?php
047 34 49 36 1 38 45 session_start();0 5 session_start();2 49 session_start();4 50 51 52 <?php
1In the above script, we’ve checked if the 370 variable is set in the first place. If it’s not set, we’ll set it to 360, otherwise we’ll increment it by 360. So, you if refresh this page multiple times, you should see that the counter is incremented by one every time! On the other hand, if you would like to delete a session variable, you can use the 373 function, as shown in the following snippet. 1 <?php
2 // start a session
3 session_start(); 4 5 // manipulate session variables
3<?php
033 34 36 // manipulate session variables
938 <?php
01session_start();0 <?php
1Thus, you can no longer access the 374 variable as it’s deleted by the 373 function. So that’s how you can alter the session information. How to Destroy a SessionIn this section, we’ll see how you could destroy a session. In the previous section, we discussed the 373 function, which is used if you want to delete specific session variables. On the other hand, if you want to delete all session-related data at once, you can use the 377 function. The 377 function deletes everything that’s stored in the current session. Having said that, it doesn't unset global variables associated with the session or unset the session cookie. So if you're using the 377 function to log a user out, you must unset the 352 variable and unset the session cookie as well. Thus, the recommended way to destroy a session completely is: 1 <?php
2 // start a session
3 session_start(); 4 5 <?php
13<?php
034 <?php
1736 <?php
1938 <?php
21session_start();0 <?php
23session_start();2 49 session_start();4 50 <?php
2952 <?php
1Session HandlersSo far, we've discussed how you can perform different operations with session variables. In this section, we'll discuss what a session handler is and how you can use it. A PHP session handler is a mechanism which instructs PHP how it should manage sessions. The default session handler is a file system, and it means that PHP stores sessions on the disk. Basically, it's a small file on the server which is associated with the unique session id. It's the same id which is stored in a session cookie on the client browser. The default session handler in PHP provides you with all the features that are needed, but sometimes you want to store sessions differently. For example, you might want to manage sessions in a database, Redis, or some other storage. In this case, you need to implement a custom session handler which overrides the default behavior. To understand how custom session handlers work, we'll briefly discuss how you can implement a database session handler which manages sessions in a MySQL database. How to Implement a Database Session HandlerIn the PHP session lifecycle, there are different stages like open, read, write, and close. Additionally, there are two more stages: destroy and garbage collection. So when you implement a custom session handler, you have to handle each of these stages to manage the session data properly. There are two ways you could implement a custom session handler, Either you could define callback functions for different stages in the session lifecycle or you could write a class which implements the 381 interface. In both cases, you need to use the 382 function to initialize your custom session handler. In our case, we’ll use the 381 interface implementation. In our example, we’re going to store sessions in the MySQL database. So let’s create a table which stores the session data by using the following snippet. 1 <?php
332 <?php
353 <?php
374 <?php
395 <?php
41<?php
0<?php
43Next, let’s see how our custom database session handler looks: 1 <?php
2 <?php
473 45 4 <?php
515 <?php
0<?php
5434 <?php
5636 <?php
5838 <?php
60session_start();0 session_start();2 <?php
63session_start();4 <?php
5650 <?php
6752 <?php
69<?php
70<?php
71<?php
72<?php
73<?php
74<?php
75<?php
76<?php
60<?php
78<?php
79<?php
80<?php
81<?php
56<?php
83<?php
84<?php
85<?php
86<?php
87<?php
88<?php
89<?php
90<?php
91<?php
92<?php
93<?php
94<?php
95<?php
96<?php
97<?php
98<?php
99200 201 202 203 204 <?php
75206 <?php
60208 209 210 211 <?php
56213 <?php
84215 216 217 218 219 <?php
90221 <?php
96223 224 <?php
69226 201 228 <?php
73230 <?php
75232 <?php
60234 235 236 237 <?php
56239 <?php
84241 242 243 <?php
88245 <?php
90247 <?php
96249 250 <?php
69252 201 254 <?php
73256 <?php
75258 <?php
60260 261 262 263 <?php
56265 266 267 268 <?php
84270 271 272 273 274 <?php
90276 <?php
96278 279 <?php
69281 201 283 <?php
73285 <?php
75287 <?php
60289 290 291 292 <?php
56294 295 296 <?php
60298 49 Our custom session handler class 384 implements the 381 interface. Thus, it must implement methods that are declared in the 381 interface. We'll look at these methods one by one to understand how each one works. 1 <?php
542 <?php
563 <?php
584 <?php
60First, to use this code, make sure to replace the 387, 388, and other placeholders with actual values in the 389 method. 1 <?php
632 <?php
563 <?php
674 <?php
695 <?php
71<?php
0<?php
7334 <?php
7536 <?php
60When the session is started, the 390 method is called. It returns 391 if the database connection was successful. If there was any problem setting up the database connection, it returns 392. 1 <?php
802 <?php
563 <?php
844 <?php
865 <?php
88<?php
0<?php
9034 <?php
9236 <?php
9438 <?php
96session_start();0 session_start();2 <?php
99session_start();4 201 50 203 52 <?php
75<?php
70<?php
60Next, PHP calls the 393 method to read the session data. The 393 method receives the session id as the first argument. We’ll check if there’s any entry available for this session id in the 395 table. If it exists, we’ll return the session data; otherwise, an empty string will be returned. 1 210 2 <?php
563 <?php
844 216 5 218 <?php
0<?php
9034 <?php
9636 38 <?php
69session_start();0 201 session_start();2 <?php
73session_start();4 <?php
7550 <?php
60When PHP needs to save or close a session, it calls the 396 method. It’s used to write the session data in a database. We’ve used the 397 syntax to make sure that if an entry exists, it will be updated; otherwise, it’ll be inserted. 1 291 2 <?php
563 295 4 <?php
60The 398 method is called after the session 396 method has been called. It works similar to a destructor in classes. In our case, there is nothing particular that needs to be done in the 398 method. 1 236 2 <?php
563 <?php
844 242 5 <?php
88<?php
0<?php
9034 <?php
9636 38 <?php
69session_start();0 201 session_start();2 <?php
73session_start();4 <?php
7550 <?php
60The session_start();01 method is called when the session is destroyed with either the 377 or session_start();03 function. In this method, the session data is deleted from a database if it exists. 1 262 2 <?php
563 266 4 5 <?php
84<?php
0271 34 273 36 <?php
9038 <?php
96session_start();0 session_start();2 <?php
69session_start();4 201 50 <?php
7352 <?php
75<?php
70<?php
60When PHP runs the garbage collector periodically, the session_start();04 method is called. The session_start();05 variable holds the value of the session_start();06 configuration option in the php.ini file. In this method, we’ll delete all sessions that are expired as a part of the garbage collection process. Using the MySQL Session Handler ClassNow, let’s see how to use the 384 handler class. 1 340 2 342 3 session_start(); 4 346 As you can see, we just need to initialize the 384 class and pass it to the 382 function to instruct PHP that it needs to use the 384 class for session management. Next, we’ve called the 353 function to start a session. Finally, we’ve initialized a session variable for testing purposes. If everything goes well, you should see the session entry in the session_start();12 table as shown in the following screenshot. And with that, you’ve created a working custom session handler which manages sessions in a database! ConclusionIn this article, we’ve explored the basics of session handling in PHP. It’s a key concept which allows you to persist information across web pages. In the first half of the article, we discussed the basic concepts of sessions, and later on we created a few PHP examples to demonstrate how you could create and destroy sessions as well as manipulating session variables. Bagaimana cara memanggil function?Cara Memanggil/Eksekusi Fungsi
Kita bisa memanggil fungsi di dalam kode Javascript dengan menuliskan nama fungsinya seperti ini: namaFungsi(); Contoh: // membuat fungsi function sayHello(){ console.log("Hello World!"); } // memanggil fungsi sayHello() // maka akan menghasilkan -> Hello World!
Bagaimana langkah pemanggilan fungsi dalam PHP?Membuat fungsi pada PHP dapat dilakukan dengan mudah, yaitu (1) menuliskan keyword function  (2) kemudian diikuti dengan nama fungsi (3) diikuti dengan tanda kurung ()  sebagai tempat argumen, (4) kemudian diikuti dengan kurung kurawa {} sebagi block statement yang akan dijalankan ketika fungsi dipanggil.
Apa fungsi function PHP?Fungsi (atau Function) di bahasa pemograman adalah kode program yang dirancang untuk menyelesaikan sebuah tugas tertentu, dan merupakan bagian dari program utama. Kita dapat membuat fungsi sendiri, atau menggunakan fungsi yang dibuat oleh programmer lain.
Jelaskan apa yang dimaksud dengan function?Fungsi (function) adalah sub modul atau sub program yang dibuat untuk menyelesaikan hal tertentu. Fungsi memiliki nama dan dalam ANSI/C, diimplementasi untuk hal-hal yang khusus dan dapat dipanggil berkali-kali (berulang) dalam program.
|