PHP will not echo JSON_ENCODE unless i echo something else - php

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: *");

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.

How to save image using method PUT with API

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.

HTML function to download JSON stored in MySQL database

I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D

GD Library image generation does not work with mySQL query

Long story short, I have a project that requires creating a user's avatar based on their data from the database. The avatar is generated using the imagepng() and imagecopy() functions.
The user's avatar can either be male or female and that preference is saved in an SQL database as column "user_gender" where "0" = female and "1" = male:
Screenshot of table in phpmyadmin
So the idea is that we take the data from the database, assign the value (0 or 1) to a variable, then use that variable to generate the image. See code below:
<?php
//Database connection script not included, but works fine
$id = 1;
$sqlQuery = "SELECT * FROM table WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array(':id' => $id));
while($rs = $statement->fetch())
{
$gender = $rs['user_gender'];
}
if($gender == "0")
{
//Allocation of images, file paths
$bodytype ="images/female/f_body.png";
}
else
{
$bodytype ="images/male/f_body.png";
}
header('Content-Type: image/png');
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
imagepng($destination);
?>
This code however, does not work as it results in a blank black page on the browser.
HOWEVER, this code, without any pulling from the database, works perfectly fine:
<?php
//taking out the sql query and just creating a $gender variable for testing
$gender = "0";
if($gender === 0)
{
$bodytype ="images/female/f_body.png";
}
else
{
$bodytype ="images/female/f_body.png";
}
header('Content-Type: image/png');
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
imagepng($destination);
?>
This is the output with the second code, showing that the image generation is indeed functional and the problem is most likely the passing from sql to php:
Working image generation in browser
I'd be extremely grateful to know what I am doing wrong or being hinted as to why the code stops working if the variable is pulled from the database.
Thank you!
I tried your code and encountered the same problem so I did some digging it and found that nothing was returned from the database so what I did was prefix the database name along with the tablename and it worked. See code below
$gender = '';
$sqlQuery = "SELECT * FROM register.users WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array('id' => 1));
while($rs = $statement->fetch())
{
$gender = $rs['gender'];
}
if($gender == 0)
{
$bodytype ="images/female/f_body.png";
}
else if($gender == 1)
{
$bodytype ="images/male/m_body.png";
}
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
header('Content-Type: image/png');
imagepng($destination);
Try it and let me know how it goes.

PHP MySql Picture Data

I cannot display an image from my Mysql Database.
I've kept following all the examples and other posts but can't seem to get it right...
<?php
$db = new PDO('mysql:host=localhost;dbname=MyDatabase;charset=utf8mb4', 'tester', '1234567890');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$request = "347";
$mytable = "u55";
$stmt = $db->prepare("SELECT * FROM ".$mytable." WHERE Id = :SearchName ");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $result[0]['TheAvatar'];
header("Content-Type: image/jpg");
echo '<img src="'.$result.'" />';
?>
My error that I have is image cannot be displayed because it contains errors.
The only difference I have from the examples is the data is stored in TEXT not BLOB/VARCHAR..
I've also tried using BinToHex() with the data to see if that made a difference.
The pictures come from a phone and are stored on a server.
The Pic data is in this link below (cant copy paste it so..)
http://spyon.agency/PicData.bmp
EDIT:
This is the code that stores the data into the DB..
It's a code snippet from the main file, the login remains the same as posted above. The Data comes from a JSON string.
$MessageDecoded = base64_decode ($request);
$input = json_decode($MessageDecoded);
Then the function that stores the data is
$mTheAvatar = $input[$i]->TheAvatar;
$mTheDirection= $input[$i]->TheDirection;
$mTheGroup = $input[$i]->TheGroup;
$mTheMedia = $input[$i]->TheMedia;
$mTheMessage = $input[$i]->TheMessage;
$mTheSenderName= $input[$i]->TheSenderName;
$mTheThumbImage = $input[$i]->TheThumbImage;
$mTheTime = $input[$i]->TheTime;
$mTheMediaExtension = $input[$i]->TheMediaExtension;
$statement = $db->prepare('INSERT INTO '.$mDevice.' '.
'(TheAvatar , TheDirection , TheGroup , TheMedia , TheMediaExtension , TheMessage , TheSenderName , TheThumbImage , TheTime) '.
'VALUES (:aTheAvatar, :aTheDirection, :aTheGroup , :aTheMedia, :aTheMediaExtension , :aTheMessage, :aTheSenderName, :aTheThumbImage, :aTheTime)');
try {
$statement->execute(array(
"aTheAvatar" => $mTheAvatar,
"aTheDirection" => $mTheDirection,
"aTheGroup" => $mTheGroup,
"aTheMedia" => $mTheMedia,
"aTheMediaExtension" => $mTheMediaExtension,
"aTheMessage" => $mTheMessage,
"aTheSenderName" => $mTheSenderName,
"aTheThumbImage" => $mTheThumbImage,
"aTheTime" => $mTheTime
));
} catch(PDOException $ex) {
echo "An Error occured!";
echo $ex->getMessage();
die;
}
you can use this code to show your image :
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result ).'"/>';

Categories