1.I don't really understand the XSS attack part. htmlentities() is useful only when you're trying to render HTML input to client's browser, correct? so when data flows out from the server into client? Suppose I never manipulate browser's DOM (because all server response are in text form), is it safe to say that my web app is immune to XSS attack?
If you are rendering text/html then you are vulnerable. The point is that someone could put HTML into a string, so when you echo it you're unintentionally adding to the DOM.
2. as for SQL injection and mysql_real_escape_string(), I thought escaping and wrapping the input string from user input is enough? I just do 4 things to achieve this objective :
1. change all single quotes to \'
2. change all backslash to double backslash
3. change all double quotes to \"
4. wrap strings in single quotes
If the order is 1,3,2,4 (or 3,1,2,4) then that's great, but it doesn't account for Unicode characters. But really, would you rather have a few calls to str_replace() that you have to manage by yourself, or one call to mysql_real_escape_string(). Putting aside the "use prepared statements" argument for a minute, of course.
Depending on the regeneration, possibly. Hypothetically a malicious eavesdropper could hijack a user's session so you still have to (do what you can to) protect yourself against that (by including information in the session that can more-or-less identify a user's computer and/or browser).