🤖 Ai回答: In PHP, you can use cURL to make HTTP requests through a proxy server、This is useful for anonymizing requests, bypassing geo-restrictions, or testing behind corporate firewalls.
Here’s how to set up a cURL request with a proxy in PHP:
✅ Basic cURL with HTTP Proxy
php
<?php
$ch = curl_init();
// The target URL you want to access
curl_setopt($ch, CURLOPT_URL, https://httpbin.org/ip);
// Set the proxy server (format: host:port)
curl_setopt($ch, CURLOPT_PROXY, 123.45.67.89:8080);
// Optional: If your proxy requires authentication
curl_setopt($ch, CURLOPT_PROXYUSERPWD, username:password);
// Optional: Specify proxy type (HTTP, SOCKS4, SOCKS5)
// Default is HTTP, but you can explicitly set:
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
// Return the response instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set a user agent (some proxies/sites block bots)
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
// Optional: Set timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo 'cURL error: ' 、curl_error($ch);
} else {
echo Response:\n 、$response;
}
⚠️ Public proxies are often slow, unreliable, or malicious、Don’t use them for sensitive tasks.
✅ Best Practices
| Tip | Description |
| Use timeouts | Prevent hanging requests: `CURLOPT_TIMEOUT`, `CURLOPT_CONNECTTIMEOUT` |
| Verify SSL | Use `CURLOPT_SSL_VERIFYPEER` and `CURLOPT_SSL_VERIFYHOST` in production |
| Rotate proxies | For scraping: rotate multiple proxies to avoid bans |
| Check proxy status | Test if proxy works before using it (`curl_getinfo()` helps) |
| Avoid public proxies for sensitive data | They can log your traffic |
Let me know if you want to:
Use cURL with SOCKS5 + Tor
Rotate proxies automatically
Handle proxy authentication with NTLM
Use cURL in a loop with multiple proxies