Setcookie()函数介于<head>和</ head>之间还是在body部分?

I have website with almost 200 pages, all pages are accessable only by a valid logged-in user. I am using php cookie in my pages to store username and password of user. All protected pages of my site have a setcookie() function in the body section :

<body>
<?php
setcookie("user","value","time");
 ?>
</body>

This works fine.

So ,My question is : Is body section of a page right place for setting cookie? or should I always use setcookie() before the html tag or inbetween head and /head?

Before the HTML tag always, in case the following is TL;DR.

"Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace." - From the manual

The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers.

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name "user", a variable is automatically created called $user, containing the cookie value.

Note: The setcookie() function must appear BEFORE the <html> tag.

Source from W3Schools

Sample code

<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

You must call setcookie() function before your script sends any output to browser. Since cookies are sent using http header. It is not safe to set users password in cookie. You should store user password in database using a strong hashing algo like BCrypt. And your setcookie format should be like this setcookie("cookiename", "cookievalue", time()+8000, "/", ".yourdomain.com", 0, 1);

Set httponly to true to prevent javascript access to your cookie and use a leading . dot before your domain name. The leading . will prevent access your cookie from any other domain like coolyourdomain.com , thisisyourdomain.com or so.