I learned PHP-about session_start ()

Source: Internet
Author: User
Tags php session tmp folder

Session_start (), which has been solved for four days. in fact, there are a lot of solutions on the Internet, and many people in the Forum can answer such questions. But in the end, I still run the PHP code on my friend's computer. After confirming that there is no error, and then through a friend's PHP. INI to compare, find out the different places, and then the modification is successful. the current situation is that there is still a warning that the warning is: session_start () [function. session-start]: cannot send session cookie-headers already sent in C:/PHP/phpdesigner_output_tmp.php on line 2, but the code can run successfully, $ _ the value of session can be passed to other pages, so I will not modify other items (not compared yet ). the last sigh is that it is difficult for a person to write a program based on interest!

Now let's talk about my own problems. When I find session_start () on the Internet, some posts mentioned that I want to modify session. save_path = C:/tmp and session. cookie_path =/
The two paths are C:/tmp and then a folder is added. however, the problem is that session. the value of cookie_path should be =/I am ashamed that I still don't understand what the value is.

In fact, the session_start () issue still needs to be resolved. put_buffery = on or modified to 4096 or session_start () followed by ob_start (); cache-limiter =; null, and whether Apache cache is enabled, but it does not help me. the following is a summary of some questions about session_start () that I found when I found the answer to the question. I would like to summarize it myself, now I posted this brother's article (not asked him, if one day the author feels disagree, please contact me) http://cmpford.bokee.com/

Session highlights

For the PHP session function, there is always no suitable answer, especially some errors, and there are some no error results. The most terrible thing is the latter, which has always been difficult for many beginners. Some veterans are sometimes confused. This article provides a brief summary of these issues for your reference.

1.
Error Message
Warning: cannot send session cookie-headers already sent
Warning: cannot send session cache limiter-headers already sent
Analysis and Solutions
The reason for this problem is that when you use session_start () in the program, the actual HTML content is output. Maybe you said, I didn't. I just echo or print a message. Sorry, the output produced by your echo or print statement is the actual HTML content output. The solution to this problem is to tune your session_start () to the first line of the program.

2.
Error Message
Warning: open (F:/689phpsessiondatasess_66a39376b873f4daecf239891edc98b5, o_rdwr) failed
Analysis and Solution
This error occurs generally because the session. save_path item in your php. INI is not set. The solution is to set session. save_path and session. cookie_path
Session_save_path = C: EMP
Session. cookie_path = C: EMP
Create a temp directory under the C: directory.

3.
Error Message
Warning: trying to destroy uninitialized session in
Analysis and Solution
Generally, you directly call the session_destroy () function. Many friends think that the session_destroy () function can run independently, but it is not. The solution is to enable the session function with session_start () before you call the session_destroy () function.

4. Question: How can I obtain the ID of the current session?
The simplest method is:
Echo Sid;
You will find.

5. problem: My program has no output before calling the header function, although I include a config. PHP file, but in config. there is no output in the PHP file. Why does the session still report the same error as Question 1? Is it because I used session_start () before the header?
A: Maybe you have carefully checked your PHP program. There is no output before header () is referenced, and there is no output in your include file! But are you using the mouse key?> What about the mobile check after the conclusion of this PHP code? Then you will find in?> There is a blank line or space behind this. If you delete these blank lines or spaces, the problem is solved.
Note: If this problem occurs, PHP 4.1.2 is later than php4.1.2 and has not been tested.

6. Q: How can I use session to restrict logon to other pages after I use session to log on to the home page...
A: The simplest method is
Session_start ();
If (! Session_registered (& apos; login & apos;) │ $ login! = True ){
Echo "You have not logged on ";
Exit;
}

7. q: I used session_register () to register the session variable. However, when I use the header or Javascript redirection statement, on the following page, but I cannot access the variable value registered by the session. How can this problem be solved?
Program segment of the problem:
Session_start ();
$ OK = & apos; Love You & apos ;;
Session_register (& apos; OK & apos ;);
Header ("Location: Next. php ");
?>

Next. php
Session_start ();
Echo $ OK;
?>

Solution:
When you use the header function or window. after the location function, the session variables registered on the previous page will be easily lost. There is still no detailed answer to this question.
But there are solutions. As shown below
Header ("Location: Next. php "."? ". Sid );
When you jump to the next page, use the current session ID as a parameter and upload it to the next page.

8. How to pass an array in a session
Session_register (& apos; Data & apos ;);
$ DATA = array (1, 2, 4 );

The method is to first register and then assign a value.

9. Question 9: Can I access the session value in the format of $ http_get_vars [& apos; ** & apos?

A: Yes. You can use the following global array to access sessions to enhance web page security.
$ Http_session_vars
$ _ Session
Routine:
Session_start ();
$ Username = & apos; stangly. Wrong & apos ;;
Session_register (& apos; username & apos ;);

Echo $ http_session_vars [& apos; username & apos;];
Echo & apos;
& Apos ;;
Echo $ _ session [& apos; username & apos;];
?>
Refer to this routine to modify your own program.

Question 10: What is the difference between session_unregister () and session_destroy?
Session_unregister () function is mainly used to describe the current sion. (translated from php.net)

Routine:
If (isset ($ _ cookie [session_name ()]) {
Session_start ();
Session_destroy ();
Unset ($ _ cookie [session_name ()]);
}

The above is a common problem for new users. The details may not be clear, and errors may inevitably occur. Please give them some advice.

 

Session configuration in PHP

Today, the debugging program encountered a session setting problem. This article is good on the Internet for your reference.
Reproduced from travel Forum http: // www/lvxing.net

First open the php. ini file and find the part of the session: (the semicolon is followed by a comment)

[Session]
; Handler used to store/retrieve data.
Session. save_handler = files; this is the session method. The default files are enough to store files.

; Argument passed to save_handler. In the case of files, this is the path where data files are stored.
Session. save_path =/tmp; this is the session storage path. For example, if you are a drive C:/tmp, the default value is C:/tmp. Therefore, if the following error occurs) failed ", you can modify this path, or create a tmp folder under the root directory.

; Whether to use cookies.
Session. use_cookies = 1; sessionid transmission method. The default value is Cookie. We recommend that you use

; Name of the session (used as Cookie name ).
Session. Name = PHPSESSID; the name of sessionid, which is stored in the cookie. Avoid the same name.

; Initialize Session on request startup.
Session. auto_start = 0; Whether to automatically start the session. The default value is no and does not need to be modified.

; Lifetime in seconds of cookie or, if 0, until browser is restarted.
Session. cookie_lifetime = 0; cookie survival time of sessionid. 0 indicates that the browser is closed.

; The path for which the cookie is valid.
Session. cookie_path =/; Cookie Path of sessionid, which does not need to be modified

; The domain for which the cookie is valid.
Session. cookie_domain =; cookie domain name of sessionid, which does not need to be modified

; Handler used to serialize data. php is the standard serializer of PHP.
Session. serialize_handler = PHP; Save the default file name suffix of data, no need to modify

; Percentual probability that the & apos; garbage collection & apos; process is started on every session initialization.
Session. gc_probability = 1

; After this number of seconds, stored data will be seen as & apos; garbage & apos; and cleaned up by the garbage collection process.
Session. gc_maxlifetime = 1440; session file retention time

; Check HTTP Referer to invalidate externally stored URLs containing IDs.
Session. referer_check =; how many bytes to read from the file.
Session. entropy_length = 0; specified here to create the session ID.
Session. entropy_file =; Session. entropy_length = 16; Session. entropy_file =/dev/urandom

; Set to {nocache, private, public} to determine HTTP caching aspects.
Session. cache_limiter = nocache; document expires after n minutes.
Session. cache_expire = 180; use transient SID support if enabled by compiling with -- enable-trans-Sid.
Session. use_trans_sid = 1 url_rewriter.tags = "A = href, Area = href, frame = SRC, input = SRC, form = fakeentry "====================================== ========================================
How long is the session lifecycle?

1. When the browser ends, its lifecycle also ends, but the file still exists in/tmp/(sess _???)
2. The sessionid will be re-allocated when you re-open the browser next time. If you use session_id () to bring back the previous ID,
Then the sess _???, Retrieve all the previously set parameters
3. You can modify the remaining time of the session file in PHP. ini. session. gc_maxlifetime = 1440; after this number of seconds, stored
; Data will be seen as & apos; garbage & apos; and
; Cleaned up by the GC process is 1440 seconds by default, 24 minutes
========================================================== ======================================

How to use an infinite life cycle session
Added session support in php4.0 to facilitate many of our programs, such as shopping cart!
In many forums, sessions are also used to process user login and record user names and passwords so that users do not have to enter their usernames and passwords every time! However, the life cycle of a general session is limited. If the user closes the browser, the session variable cannot be saved! So how can we achieve the permanent life of the session?
As you know, sessions are stored on the server side. You can obtain the user's file based on the sessionid provided by the client, read the file, and obtain the variable value, sessionid can use the cookie of the client or QUERY_STRING of the http1.1 protocol (that is, the "?" To the server, and then the server reads the session directory ......

To realize the permanent life of a session, first you need to know about the session settings of PHP. ini (open the php. ini file, in the "[session]" Section ):
1. session. use_cookies: The default value is "1", which indicates that sessionid is transmitted using cookies, and QUERY_STRING is used for transmission;
2. session. Name: the name of the variable stored by sessionid, which may be cookie or QUERY_STRING. The default value is PHPSESSID ";
3. session. cookie_lifetime: This indicates the time when sessionid is stored in the cookie on the client. The default value is 0, indicating that the session ID will be voided as soon as the browser closes the session ID ...... This is why the session cannot be used permanently!
4. session. gc_maxlifetime: the time when session data is stored on the server. If this time is exceeded, the session data is automatically deleted!
There are still a lot of settings, but this is related to this article. The following describes the principles and steps for using permanent sessions.

As mentioned above, the server reads session data through sessionid, but generally the sessionid sent by the browser does not exist after the browser is closed. Therefore, we only need to manually set the sessionid and save it, no ......
If you have operation permissions on the server, it is very easy to set up, but you only need to perform the following steps:
1. Set "session. use_cookies" to 1. Enable the cookie to store the sessionid. However, the default value is 1, which generally does not need to be modified;
2. Change "session. cookie_lifetime" to positive infinity (of course there are no positive infinity parameters, but there is no difference between 999999999 and positive infinity );
3. Set "session. gc_maxlifetime" to the same time as "session. cookie_lifetime;
After setting, open the editor and enter the following code:
Bytes ------------------------------------------------------------------------------------

<? PHP session_start ();
Session_register (& apos; count & apos ;);
$ Count ++;
Echo $ count;
?>
Bytes ------------------------------------------------------------------------------------
Save it as "session_check.php", open "session_check.php" in the browser, check whether "1" is displayed, close the browser, and then access "session_check.php" in the browser ", if "2" is displayed, congratulations. You have succeeded. If it fails, check your previous settings.

However, if you do not have the server operation permission, it is quite troublesome. You need to rewrite the sessionid through the PHP program to save session data permanently. Check the php.net function manual and you can see the "session_id" function: If no parameter is set, the current sessionid is returned. If a parameter is set, the current sessionid will be set to the given value ......
You can use the permanent cookie and the "session_id" function to save the permanent session data!
However, for convenience, we need to know the "session. name ", but generally users do not have the permission to view the server's PHP. INI settings, but PHP provides a very good function "phpinfo", which can be used to view almost all PHP information!
Bytes ------------------------------------------------------------------------------------


Bytes ------------------------------------------------------------------------------------
Open the editor, enter the above code, and then run the program in the browser. The PHP information is displayed, as shown in 1 ). There is a "session. Name" parameter (as shown in the figure). This is the server "session. Name" we need. It is usually "PHPSESSID ".
After recording the sessionid name, we can store session data permanently!
Open the editor and enter the following code:
Bytes ------------------------------------------------------------------------------------
Session_start (); // start the session
Session_register (& apos; count & apos;); // register the session variable count
If (isset ($ PHPSESSID )){
Session_id ($ PHPSESSID );
} // If $ PHPSESSID is set, the sessionid is assigned to $ PHPSESSID. Otherwise, the sessionid is generated.
$ PHPSESSID = session_id (); // obtain the current sessionid
$ Count ++; // variable count plus 1
Setcookie (& apos; PHPSESSID & apos;, $ PHPSESSID, time () + 3156000); // store the sessionid to the cookie
Echo $ count; // display the value of the session variable count
?>
Bytes ------------------------------------------------------------------------------------

After saving the session, check whether sessionid is successfully saved by using the same method as the one with the server permissions.
Postscript:
In fact, the real permanent storage is impossible, because the cookie storage time is limited, and the server space is limited ......
However, the above method is sufficient for some sites that need to be stored for a long time! For other session applications, you can
For more information, see zphp.com.
Finally, the author's debugging environment: windows98digext (SE) + Apache + PhP 4.04.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.