Files
dog/php/php-dog/upload.php
2022-12-28 15:42:10 +01:00

83 lines
2.1 KiB
PHP

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
session_start();
require __DIR__.'/classes/Database.php';
require __DIR__.'/classes/lib.php';
$result = new CMsg(0);
if(!isset($_SESSION["user"]))
{
$result = new CMsg(0, 401, "not logged in");
return $result->jsonarray();
}
$user = $_SESSION["user"];
$allowTypes = array('jpg','png','jpeg','gif','pdf');
// File upload path
$targetDir = "uploads/".$user->qr_id;
if (!file_exists($targetDir))
{
mkdir($targetDir, 0755, true);
}
$fileName = basename($_FILES["file"]["name"]);
$fileType = pathinfo($fileName,PATHINFO_EXTENSION);
if(!in_array($fileType, $allowTypes))
{
$result = new CMsg(
0,
406,
'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.');
return $result->jsonarray();
}
$newFilename = getNewFilename($targetDir, $fileType, 20);
if(strlen($newFilename) == 0)
{
$result = new CMsg(
0,
507,
'Too many uploaded files on the server, try it again later');
return $result->jsonarray();
}
$targetFilePath = $targetDir . '/' . $fileName;
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"]))
{
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath))
{
// Insert image file name into database
$update = $db->query("UPDATE dogs SET picture = '".$fileName."' WHERE qr_id = ".$user->qr_id);
if($update)
{
$result = new CMsg(1,200,"The file ".$fileName. " has been uploaded successfully.");
}
else
{
$result = new CMsg(0,500,"File upload failed, please try again.");
}
}
else
{
$result = new CMsg(0,500,"Sorry, there was an error uploading your file.");
}
}
else
{
$result = new CMsg(1,204,'Please select a file to upload.');
}
// Display status message
echo $result->jsonarray();
?>