Skip to content

Instantly share code, notes, and snippets.

@GeekyGeeky
Created January 19, 2021 19:06
Show Gist options
  • Save GeekyGeeky/2c44052cd0aa10f60c7740b86b9e3037 to your computer and use it in GitHub Desktop.
Save GeekyGeeky/2c44052cd0aa10f60c7740b86b9e3037 to your computer and use it in GitHub Desktop.
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once '../config/database.php';
include_once '../objects/product.php';
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
// $data = json_decode(file_get_contents("php://input"));
$title=isset($_POST['title']) ? $_POST['title'] : "";
$desc=isset($_POST['desc']) ? $_POST['desc'] : "";
$price=isset($_POST['price']) ? $_POST['price'] : "";
// decode jwt here
// if jwt is not empty
if($title and $desc and $price and $_FILES['image']){
$ds = DIRECTORY_SEPARATOR;
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$storage_path = $_SERVER['DOCUMENT_ROOT'].$ds."images";
if (in_array(strtolower($ext), ['png', 'jpeg', 'jpg'])) {
$filename = time()."_".str_replace(" ", "_", $_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $storage_path.$ds.$file)) {
$product->title = $title;
$product->description = $desc;
$product->price = $price;
// update image
if($product->create($filename)){
http_response_code(201);
exit(json_encode(array("message" => "success", "product"=> $product)));
}else{
http_response_code(503);
exit(json_encode(array("message" => "Oooops!! Something went wrong.Try Again")));
}
// exit(json_encode(array("message" => "image added")));
}else{
http_response_code(503);
exit(json_encode(array("message" => "Unable to create product")));
}
}else{
http_response_code(400);
exit(json_encode(array("message" => "Image uploaded not allowed")));
}
}else{
http_response_code(422);
exit(json_encode(array("message" => "Oooops!! Something went wrong.Try Again")));
}
// catch will be here
// if decode fails, it means jwt is invalid
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment