Simple curl to PHP file upload
I need to view a log file from work but don’t have SSH access to work without VPN and from work due to IP/port filter. However, HTTP does work so though I would give HTTP POST a go via PHP and CURL. Took a bit of playing around but in the end is quite simple.
Setup consist of either a HTML form or CURL command to send the file via HTTP POST and a PHP backend to accepts the HTTP POST call and provide feedback.
HTML Backend (upload.php) is:
$allowedExts = array("txt", "htm", "html", "csv", "log", "pdf");
$uploadPath = "/Users/username/Sites/logs/";
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "text/plain")
|| ($_FILES["file"]["type"] == "text/html")
|| ($_FILES["file"]["type"] == "text/x-log")
|| ($_FILES["file"]["type"] == "text/csv")
|| ($_FILES["file"]["type"] == "application/pdf"))
&& ($_FILES["file"]["size"] < 104857600)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo $_FILES["file"]["error"];
}
else
{
echo "File Name: " . $_FILES["file"]["name"] . "
";
echo "Mime Type: " . $_FILES["file"]["type"] . "
";
echo "File Size: " . ($_FILES["file"]["size"] / (1024 * 1)) . " kB
";
echo "Temp File: " . $_FILES["file"]["tmp_name"] . "
";
if (file_exists($uploadPath . $_FILES["file"]["name"]))
{
echo "
Note: " . $uploadPath . $_FILES["file"]["name"] . " already exists and will be overwritten.
";
}
move_uploaded_file($_FILES["file"]["tmp_name"],
$uploadPath . $_FILES["file"]["name"]);
echo "Saved as: " . $uploadPath . $_FILES["file"]["name"];
}
}
else
{
echo "Invalid file extension mime type size";
echo "";
}
HTML front end:
\
\
\
\
\
\
CLI backend (upload-curl.php):
$allowedExts = array("txt", "htm", "html", "csv", "log", "pdf");
$uploadPath = "/Users/username/Sites/logs/";
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "text/plain")
|| ($_FILES["file"]["type"] == "text/html")
|| ($_FILES["file"]["type"] == "text/x-log")
|| ($_FILES["file"]["type"] == "text/csv")
|| ($_FILES["file"]["type"] == "application/pdf"))
&& ($_FILES["file"]["size"] < 104857600)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo $_FILES["file"]["error"];
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],$uploadPath . $_FILES["file"]["name"]);
if (file_exists($uploadPath . $_FILES["file"]["name"]))
{
echo "owerwrote: " . $uploadPath . $_FILES["file"]["name"] . "\n";
}
else
{
echo "uploaded: " . $uploadPath . $_FILES["file"]["name"] . "\n";
}
}
}
else
{
echo "Invalid file extension, mime type or size";
}
CLI frontend:
curl -F "file=@test.log;type=text/x-log" https://www.mattparkinson.eu/upload-curl.php
Not for log files I have to override the mime type to text/x-log as by default these were application/octet-stream.