File: /var/www/html/s3-file-server/api-upload.php
<?php
$response = array();
if(isset($_POST['file_url'])){
$file_name = $_POST['file_url'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$imageName = generateRandomString();
$newFileName = $imageName . '-' . time() . '.' . $extension;
$file_ext = $extension;
$file_ext = strtolower($file_ext);
//Prevent upload of certain files that can cause security issues
if($file_ext=="php" || $file_ext=="html"){
$response['errorcode'] = "201";
$response['errormessage'] = "Invalid extenstion";
}
else
{
$file_error = 0;
if($file_ext == "png" || $file_ext == "jpg" ||$file_ext == "jpeg" ||$file_ext == "gif" ||$file_ext == "bmp"){
$file_dir = "uploads/img/";
}
elseif ($file_ext == "mp4" ||$file_ext == "avi" ||$file_ext == "mkv" ||$file_ext == "mpeg" ||$file_ext == "mov") {
$file_dir = "uploads/vid/";
}
elseif ($file_ext == "mp3" ||$file_ext == "flac") {
$file_dir = "uploads/aud/";
}
$file_destination = $file_dir . $newFileName;
$data = file_get_contents($file_name);
if(file_put_contents($file_destination, $data))
{
$newFileURL = url().$file_destination;
$response['errorcode'] = "200";
$response['errormessage'] = "Uploaded";
$response['url'] = $newFileURL;
}
}
echo json_encode($response);
}
if(isset($_POST['file'])){
$file_name = $_POST['file'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$imageName = generateRandomString();
$newFileName = $imageName . '-' . time() . '.' . $extension;
$file_ext = $extension;
$file_ext = strtolower($file_ext);
//Prevent upload of certain files that can cause security issues
if($file_ext=="php" || $file_ext=="html"){
$response['errorcode'] = "201";
$response['errormessage'] = "Invalid extenstion";
}
else
{
$file_error = 0;
if($file_ext == "png" || $file_ext == "jpg" ||$file_ext == "jpeg" ||$file_ext == "gif" ||$file_ext == "bmp"){
$file_dir = "uploads/img/";
}
elseif ($file_ext == "mp4" ||$file_ext == "avi" ||$file_ext == "mkv" ||$file_ext == "mpeg" ||$file_ext == "mov") {
$file_dir = "uploads/vid/";
}
elseif ($file_ext == "mp3" ||$file_ext == "flac") {
$file_dir = "uploads/aud/";
}
$file_destination = $file_dir . $newFileName;
$data = file_get_contents($file_name);
if(file_put_contents($file_destination, $data))
{
$newFileURL = url().$file_destination;
$response['errorcode'] = "200";
$response['errormessage'] = "Uploaded";
$response['url'] = $newFileURL;
}
}
echo json_encode($response);
}
function generateRandomString($length = 30) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[random_int(0, $charactersLength - 1)];
}
return $randomString;
}
function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
$currentDir = basename(__DIR__);
return $protocol . "://" . $_SERVER['HTTP_HOST']."/".$currentDir."/";
}
?>