Just for #1 -- 3-legged authorization using Authorization Code flow.
When your application exchanges the authorization code for an access token, you want to be sure that the OAuth flow which resulted in the authorization code provided was actually initiated by the legitimate user. So, before the client application kicks off the OAuth flow by redirecting the user to the provider, the client application creates a random state value and typically store it in a server-side session. Then, as the user completes the OAuth flow, you check to make sure state value matches the value stored in the user's server-side session-- as that indicates the user had initiated the OAuth flow.
A state value should typically be a pseudo-random unguessable value. A simple value can be generated as an int with the rand() function in PHP, though you could get more complex as well to provide greater assurance.
The state exists to prevent things like me sending you a link via e-mail which contains an authorization code for my account, you clicking on it and the application pushing all the data into my account unbeknownst to you.
Some additional information is in the OAuth 2.0 threat model document:
https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-threatmodel-00
In particular, see the section on CSRF protection:
https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-26#section-10.12