使用CURL与PHP传递Cookie及调试问题
Hey there, let's get your cookie delivery working and cover some other reliable ways to test this out!
First: The Critical Bug in Your CURL Code
The root problem here is a variable mismatch — you initialized your CURL session with $cSession, but then tried to set the cookie and verbose options on an undefined variable $ch. Those settings never got applied to your actual session, which is why the target page didn't pick up the cookie. Also, that stray fclose($temp) line can be removed since $temp isn't defined anywhere.
Corrected CURL Code
<?php $cSession = curl_init(); // Target URL curl_setopt($cSession, CURLOPT_URL, "https://www.test.com/testpage.php"); // Return response instead of outputting directly curl_setopt($cSession, CURLOPT_RETURNTRANSFER, true); // Include headers in the result (optional, great for debugging) curl_setopt($cSession, CURLOPT_HEADER, true); // Apply the cookie header to the CORRECT session variable curl_setopt($cSession, CURLOPT_HTTPHEADER, array("Cookie: test=cookie")); // Enable verbose output to inspect request details curl_setopt($cSession, CURLOPT_VERBOSE, true); // Execute the request $result = curl_exec($cSession); // Clean up the session curl_close($cSession); // Output the result echo $result; ?>
Quick Debug Tip for the Target Page
To confirm the cookie is arriving, update your testpage.php to dump all incoming request headers if the cookie is missing — this lets you verify exactly what's being sent:
<?php echo "You've Curled me "; if (isset($_COOKIE['test'])) { echo $_COOKIE['test']; } else { echo "<br>Request Headers Received:<br>"; foreach (getallheaders() as $name => $value) { echo "$name: $value<br>"; } } ?>
Alternative Ways to Test Cookie Delivery (Beyond JS/PHP)
If you want to validate cookie transmission without writing code, here are some straightforward methods:
- Command Line CURL: Run this in your terminal to see the full request flow. The
-vflag shows verbose details, so you can confirm the Cookie header is included:curl -v -H "Cookie: test=cookie" https://www.test.com/testpage.php - API Testing Tools: Use tools like Postman or Insomnia — create a GET request to your target URL, add a
Cookieheader with your value, send it, and check both the request headers (to confirm the cookie was sent) and the response (to see if the server recognizes it). - Browser Developer Tools: In Chrome/Firefox, open DevTools > Network tab, send a request to your target page, then click the request entry to view the "Request Headers" section. You can also right-click the request > Edit and Resend to manually add the Cookie header and retest.
- Wget: Similar to curl, use the
--headerflag to send the cookie and view the response directly:wget --header="Cookie: test=cookie" -O - https://www.test.com/testpage.php
内容的提问来源于stack exchange,提问作者John Bailey

