How to save image using method PUT with API - php

i am getting issue in PUT method. But everything is fine when i'm doing method post
here is some code :
<?php
header("Content-type: multipart/form-data");
include_once '../Database/database.php';
$status = array();
if(is_uploaded_file($_FILES["ImageKTP"]["tmp_name"]))
{
$tmp_file = $_FILES["ImageKTP"]["tmp_name"];
$ImageKTP = $_FILES["ImageKTP"]["name"];
$upload_dir = "./uploads/" .$ImageKTP;
if (move_uploaded_file($tmp_file, $upload_dir)) {
$status['kode']=1;
$status['deskripsi']='upload success';
$ImageKTP = $upload_dir;
} else {
$status['kode']=0;
$status['deskripsi']='upload failed';
$ImageKTP = null;
}
}
echo json_encode($status);
?>
But when i'm doing method put using application/json, the result is failed
<?php
header("Content-type: application/json");
include_once '../Database/database.php';
include_once '../Controller/users.php';
$data = json_decode(file_get_contents('php://input'), true);
$email=$data['email'];
$idcardnumber=$data['idcardnumber'];
$placeofbirth=$data['placeofbirth'];
$dateofbirth=$data['dateofbirth'];
$Gender=$data['Gender'];
$Religion=$data['Religion'];
$ImageKTP=$data['ImageKTP'];
$ImageSelfie=$data['ImageSelfie'];
$ImageFamilyMemberCard=$data['ImageFamilyMemberCard'];
$database = new Database();
$db = $database->getConnection();
$user = new Users($db);
$stmt = $user->UpdateProfile($email, $idcardnumber, $placeofbirth, $dateofbirth, $Gender, $Religion, $ImageKTP, $ImageSelfie, $ImageFamilyMemberCard);
if($stmt->rowCount() > 0){
// create array
$profile_arr=array(
"success" => 1,
"message" => "Successfully Update Profile!"
);
}
else{
$profile_arr=array(
"success" => 0,
"message" => "Update Profile Failed!",
);
}
print_r(json_encode($profile_arr));
?>
I still didnt find out how to solve this problem cause i want to update profile using method PUT include other value

The $_FILES array only works with POST requests. If you want to use PUT there are some configurations to the web server that need to be made first, you can find a detailed guide here.

Related

Error trying to get PHP array to JSON after adding headers (for AJAX)

I am trying to get users' data (hypothetical) from mySQL database, store them in an array, convert the array to json to be able to use it in AJAX requests in Javascript.
The code works, but when I add:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Content-Type: application/json');
at the top of the index.php, the browser gives me the error:
SyntaxError: JSON.parse: unexpected character at line 5 column 1 of the JSON data
I still haven't any .js file btw, I'm just trying to get it ready for ajax,
and I know the first two headers make the json accessible from the client,
and the last header tells it is in json format.
Here is the code; all the files are in one folder;
index.php
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Content-Type: application/json');
require 'config.php';
if($_SERVER['REQUEST_METHOD'] == "GET") {
if(isset($_GET['request'])) {
if($_GET['request'] == "user" && isset($_GET['name'])) {
$test = new TestClass($_GET['name']);
$detail = $test->get_detail();
echo json_encode($detail);
}
else if($_GET['request'] == "users") {
$users = TestClass::get_users();
echo json_encode($users);
}
}
} ?>
config.php
<?php
$dbhost="localhost";
$dbname="ajax";
$dbuser="root";
$dbpassword="";
require 'test.class.php'; ?>
test.class.php
<?php
class TestClass {
private $name;
function __construct($name) {
$this->name = $name;
}
public function get_detail() {
try {
$conn = new PDO("mysql:host=".$GLOBALS['dbhost'].";dbname=".$GLOBALS['dbname'], $GLOBALS['dbuser'], $GLOBALS['dbpassword']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users where username = ?");
$stmt->execute([$this->name]);
$res = $stmt->fetch();
return array(
"ID" => $res['ID'],
"username" => $res['username'],
"email" => $res['email'],
"password" => $res['password'],
);
}catch(PDOException $e) {
echo $e->getMessage();
return array();
}
}
public static function get_users() {
try{
$conn = new PDO("mysql:host=".$GLOBALS['dbhost'].";dbname=".$GLOBALS['dbname'], $GLOBALS['dbuser'], $GLOBALS['dbpassword']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users");
$stmt->execute([]);
$array = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($array, array(
"ID" => $row['ID'],
"username" => $row['username'],
"email" => $row['email'],
"password" => $row['password'],
));
}
return $array;
} catch(PDOException $e) {
return array();
}
}
}?>
How i said I still don't have any JavaScript file. I am expecting to see the string of the Array in JSON format by going to: localhost/folder/index.php?request=users
From Firefox
info:
-server: XAMPP for Linux 8.1.10 (so, LAMPP);
-os: Ubuntu server 22.04.1 LTS x86_64, Kernel: 5.15.0-52-generic
-browser: Firefox Browser 106.0.1 (via snap)
Thank you, I tried to google this, but nothing was clear to me.
UPDATE
I was following a tutorial, and whith the above code,
but without the three headers,
this was the output:
But from what I understood, I also have to add the three headers to make it accessible from js.
after adding them, here's the output:
I was expecting to see the data like in the first image.
I solved this, for some reason, which I still don't know,
when I changed the index.php to another structure
using the switch statement to manage the requests, the output was fine.
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Content-Type: application/json');
require 'config.php';
if(isset($_GET['request'])) {
switch($_GET['request']) {
case "user":
$test = new TestClass($_GET['name']);
$detail = $test->get_detail();
echo json_encode($detail);
break;
case "users":
$users = TestClass::get_users();
echo json_encode($users);
break;
}
}?>
Maybe someone can explain why this happened.

Problem saving multiple JSON records to a file

I made an HTML form that sends the data to JSON, but I experienced a problem with code I took from a tutorial. It makes a new JSON file every time I submit a new form. How to make it so it adds the data to it, not rewrite it?
This is the PHP code I'm using
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function get_data() {
$datae = array();
$datae[] = array(
'Name' => $_POST['name'],
'Strategy' => $_POST['strategy'],
'Teams' => $_POST['team'],
);
return json_encode($datae);
}
$name = "strategies";
$file_name = $name . '.json';
if(file_put_contents(
"$file_name", get_data())) {
echo $file_name .' file created';
}
else {
echo 'There is some error';
}
}
?>

JSON is overwriting the old data how to keep on adding data with new ID

so, I am working on a JSON file that should keep on incrementing IDs.
However I get stuck at id:0 and when I insert new data the old data will be replaced by the new one (it keeps id:0).
I am not entirely sure what code is related and what not, so I will post whatever I think should be related and if someone with more knowledge related to JSON could adjust (in case it needs any) it, I would appreciate it a lot.
The include database_json.php contains the following code:
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
EDIT: someone wanted me to post how the JSON itself looked like... so this is how it looks:
The file is called: database.json
{
"data":
[
{
"id":0,
"exercisetitle":"Test300520180924",
"exerciseWord":["huiswerk"],
"syllables":["Huis","werk"],
"file":"jsonData_.json",
"audio":null,"language":null
}
]
}
(do not mind the audio and language, that's something for later on.
The best I could do was this, yes I read the stuff about making a post and how to properly format stuff etc. but I people would often say I need to include certain code etc etc. and it mostly would turn out messy as hell, so I would rather have a bit too much code (the code I think is related) then not have enough.
Cheers!

using $_GET['VALUE'] from a FORM using method POST

I am troubleshooting CAPTCHA problem in someone Else's code, where the form method is "POST"
But in the action.php file the code is like this:
$key=substr($_SESSION['key'],0,5);
$number = $_GET['img_code'];
if($_GET['img_code']){
if($number==$key)
{
echo "done";
exit();
}
else
{
echo false;
exit();
}
}
I have tried to var_dump($_GET['img_code']) and as expected I am getting null value.
but if I am doing it var_dump($_POST['img_code']) I am getting the correct value.
but once I am setting it to POST, I start getting error "captcha not entered correctly.
Any help will be greatly appreciated.
UPDATE:
FORM METHO
<form action="{$Site_Root}signup.php" method="post" class="frmRegister tutor-registration" name="frmRegister" id="frmRegister" enctype="multipart/form-data" >
Further Update:
If I am using $_REQUEST['img_code'] and then doing a var_dump I am getting the matching string for $key and $number like
string(5) "f065a" string(5) "f065a"
but problem is when I am applying this as a condition for example:
I am getting - "captcha not entered correctly."
if(isset($_POST['email'])){
if ($key==$number){ // condition line is added by me
if(!empty($_FILES['photo']['name']))
{
$_POST['photo'] = fileUpload($_FILES['photo'],TUTOR);
$thumb->image($physical_path['Tutor'].$_POST['photo']);
$thumb->size_width(120);
$thumb->jpeg_quality(100);
$filename = $thumb->get2(); //small_thumb_
}
else
{
$_POST['photo'] = "";
}
$tutor_id = $tut->Insert($_POST);
$to_email = $_POST['email'];
global $mail;
$mail = '';
$mail = new htmlMimeMail();
$mail->setFrom($config[WC_CONTACT_US]);
//Set Cc
// $mail->setCc(array($config[WC_CONTACT_US]));
$mail->setSubject('Welcome to TuitionJobsPortal.com!');
$tpl2 = new Smarty;
$tpl2->template_dir = $physical_path['EmailTemplate'];
$tpl2->compile_dir = $physical_path['Site_Root']. 'templates_c/';
$tpl2->debugging = DEBUG;
$tpl2->assign(array("membername" => $_POST['tutor_name'],
"vcode" => $_POST['verification_code'],
"tutor_id" => $tutor_id,
"Templates_Image" => $virtual_path['Site_Root'].'templates/images/',
"Site_Root" => $virtual_path['Site_Root'],
));
$content = $tpl2->fetch('registration'. $config['tplEx']);
$mail->setHtml($content);
$result = $mail->send(array($to_email));
header("location: signup.php?signup=true");
exit();
}
} //this is added.
I don't think you can access $_POST data from $_GET , so either change form method to GET or access posted data using $_POST['img_code'] .
You can use the $_REQUEST global variable, it can do the work of both GET and POST,

PHP will not echo JSON_ENCODE unless i echo something else

i have a file on the disk that i retrieve, and store its contents into an array for display as json.
function getCurrentPic($username, $password){
$con = connectToPDO();
$valid = validateUser($username, $password);
if($valid == 1){
$sth = $con->prepare('
SELECT current_pic
FROM user
WHERE
username = :username');
$sth->execute(array(':username' => $username));
$sth->bindColumn(1, $imagePath, PDO::PARAM_STR);
$sth->fetch(PDO::FETCH_BOUND);
echo spitImageJSON($imagePath);
}
}
function spitImageJSON($imagePath){
if(strlen($imagePath) > 1){
$IDPath = $imagePath.'d';
$id = getContentsAtPath($IDPath);
$image = getContentsAtPath($imagePath);
//echo "$imagePath";
$arrayData = array(array(
'image' => $image,
'id' => $id
));
return json_encode($arrayData);
}
}
that code doesn't work unless i uncomment the echo "$imagePath", at which point it prints the path AND the json.. when i re-comment it, nothing is echoed. I'm losing my mind. please help.
btw the file is just a base64 encoded string.. id is just a numerical string
by placing
header("Content-type: application/json");
before returning the json, it worked like it was supposed to without the echo $imagePath
In case anyone else has this problem, I had to add the following on top over the correct answer:
header("Access-Control-Allow-Origin: *");

Categories