PHP + curl, HTTP POST sample code?

前端 未结 11 2368
北荒
北荒 2020-11-21 04:58

Can anyone show me how to do a php curl with an HTTP POST?

I want to send data like this:

username=user1, password=passuser1, gender=1
11条回答
  •  逝去的感伤
    2020-11-21 05:43

    If you try to login on site with cookies.

    This code:

    if ($server_output == "OK") { ... } else { ... }
    

    May not works if you try to login, because many sites returns status 200, but the post is not successful.

    Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.

    Also the post can be successful, but the status can be redirect instead 200.

    To be sure the post is successful try this:

    Follow location after the post, so it will go to the page where the post do redirect to:

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    

    And than check if new cookies existing in the request:

    if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 
    
    {echo 'post successful'; }
    
    else { echo 'not successful'; }
    

提交回复
热议问题