I have a PHP (Laravel framework) application and when a request is being made on my site, i want to do the exact same request with CURL but only change the URL. That includes:
- headers
- POST data (if present)
- uploaded files (if present)
- anything else a Request would contain
I have started writing my own code like this:
<?php
$url = $request->fullUrl(); // Current URL
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, "http://otherurlhere.com/");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->method());
if ($request->method() == "POST") {
$fields_string = "";
$fields = $request->all();
curl_setopt($ch,CURLOPT_POST, true);
if (count($request->files)) {
foreach ($_FILES as $key => $file) {
if (is_array($file['name'])) {
foreach ($file['name'] as $key2 => $value2) {
$tmpfile = $_FILES[$key]['tmp_name'][$key2];
$filename = basename($_FILES[$key]['name'][$key2]);
$fields[$key] = '@'.$tmpfile.';filename='.$filename;
}
}
else {
$tmpfile = $_FILES[$key]['tmp_name'];
$filename = basename($_FILES[$key]['name']);
$fields[$key] = '@'.$tmpfile.';filename='.$filename;
}
}
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
}
else {
$fields_string = http_build_query($fields);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
}
}
$headers = [];
foreach ($request->headers->all() as $key => $header) {
$headers = [];
foreach ($request->headers->all() as $key => $header) {
$headers[] = $key.": ".$header[0];
}
if (count($headers) > 0) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$headers = explode("\n", $header);
foreach ($headers as $header) {
if (!empty($header))
if (substr($header, 0, 12) == "Content-Type")
header($header);
}
echo $body;
//close connection
curl_close($ch);
exit();
?>
But if feels like i am complicating things too much, plus the files upload part isn't really working, so i was wondering if anybody new of a very simple solution that would just copy everything in a PHP CURL replica.
Even if it is the same as "Chrome copy as CURL" functionality and it would give me a command. That would be great as well, because i could use exec() with that.