Home > Backend Development > PHP Tutorial > PHP optimizes the use of session

PHP optimizes the use of session

WBOY
Release: 2016-08-08 09:27:13
Original
1634 people have browsed it

php's session extension can store session data in any container, as long as the container implements the interface in php_session.h:

typedef struct ps_module_struct {
	const char *s_name;
	int (*s_open)(PS_OPEN_ARGS);
	int (*s_close)(PS_CLOSE_ARGS);
	int (*s_read)(PS_READ_ARGS);
	int (*s_write)(PS_WRITE_ARGS);
	int (*s_destroy)(PS_DESTROY_ARGS);
	int (*s_gc)(PS_GC_ARGS);
	char *(*s_create_sid)(PS_CREATE_SID_ARGS);
} ps_module;
Copy after login

If session.auto_start = 1 is defined in php.ini, the session extension will be used during the request initialization phase (rinit ) will call s_open and s_read data.
If session_start() is called in the php page (only the first call takes effect), the session extension will also call s_open and s_read data.
But for some pages that do not involve session data, reading session data will cause a waste of performance, such as disk operations or network operations.
So we need to find a way to treat pages involving session data and pages that do not involve session data differently, but the processing code needs to be consistent.
The idea is to remove session.auto_start = 1 and change it to session.auto_start = 0 and delay calling session_start() for requests without session_name in the cookie.
If there is no session_name in the cookie, the session extension will be automatically generated when session_start() is called. A session_id and send the Set-Cookie header. The header information should be output before the page outputs the content or the page content should be put into the output buffer to delay the output.
The final implementation is as follows:
auto_prepend_file:

<?php
if (isset($_COOKIE[session_name()])) {
	define('SESSION_STARTED', true);
	@session_start();
} else {
	ob_start();
}
Copy after login

auto_append_file:
<?php
if (!defined('SESSION_STARTED') && $_SESSION) {
	$session_copy = $_SESSION;
	@session_start();
	if (!$_SESSION) {
		$_SESSION = $session_copy;
	}
	ob_end_flush();
}
Copy after login

The above introduces the use of PHP session optimization, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template