Accessing POST parameter with file upload in PHP - php

Trying to access the POST parameter passed with image uploading. When I print $_POST, the output is as follows:
array (
'%entity' => 'org.apache.http.client.entity.UrlEncodedFormEntity#532d2d84',
)
The PHP code is as follows:
$data = file_get_contents($_FILES['source']['tmp_name']);
$image = imagecreatefromstring( $data );
$ifp = fopen( '1.png', "wb" );
fwrite( $ifp, $data);
fclose( $ifp );
echo '<pre>';
print_r($POST);
User id is sent along with the file in POST request.
How to access the USERID which is passed with the file?

In your output you have listed key => value. You have to use the key part on $_POST array.
Just try with:
$_POST['%entity']

Related

fwrite() writes a json encoded array two times

I'm trying to write a json file with data gathered via get requests. The json file is a 2D array of strings, but when the data is written to the file, the nested array is written twice.
<?php
//used for parsing html
include("simple_html_dom.php");
//read the file
$fp = fopen("j.json", "r");
$t = fread($fp, filesize("j.json"));
fclose($fp);
$loaded = json_decode($t);
//print the loaded array
print_r($loaded);
//gathering the data
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo1 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
$data = file_get_html($url)->find("span[class=ora] b", 0)->plaintext;
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo2 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo3 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
//adding the new data to the array
array_push($loaded, array($prezzo1, $prezzo2, $prezzo3, $data));
//the new json string is parsed and ready to be written
$s = json_encode($loaded);
//printing stuff to ensure the data is correct
echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
//write the new json string to the same file
$fp = fopen("j.json", "w");
fwrite($fp, $s);
fclose($fp);
?>
j.json before the script runs:
[]
What the script prints:
Array ( )
[["128,54","128,54","128,54","30\/12"]], type=string
Array ( [0] => Array ( [0] => 128,54 [1] => 128,54 [2] => 128,54 [3] => 30/12 ) )
j.json after the script:
[["128,54","128,54","128,54","30\/12"],["128,54","128,54","128,54","30\/12"]]
I tried opening the file like this: $fp = fopen("j.json", "r+"); and at the and i changed the script:
$s = "\"".json_encode($loaded)."\"";
echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
fwrite($fp, $s);
fclose($fp);
And I found out that a null is being written too:
[]"[["128,54","128,54","128,54","30\/12"]]""null"
The browser sends two requests when visiting a url, a request to the php file and another request to /favicon.ico. The second request is send to check if the site has a favicon. This second requests causes the script to execute twice.
The request for the favicon can be prevented by following the steps described here: https://stackoverflow.com/a/38917888/6310593

How to convert data URI to buffer (string with binary)?

I am using react to edit an image and send its final data using mycanvas.toDataURL() to php.
The API I am using says, instead of an image, I could although
[...] upload an image from a buffer (a string with binary)
Their example looks like this:
$sourceData = file_get_contents("example.jpg");
$resultData = \Tinify\fromBuffer($sourceData)->toBuffer();
Like I said, instead of an uploaded image, I have got a data URI looking like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDgAAAQ4C2dj892d2dh98a2d...
How can I convert this data URI to a valid buffer to be used as $sourceData?
You can try converting the string to an image file and then send that file, you can use a code like this to do that:
function base64_to_image($base64_string, $output_file) {
$ifp = fopen( $output_file, 'wb' );
$data = explode( ',', $base64_string );
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
fclose( $ifp );
return $output_file;
}
So, just call it like :
$file = base64_to_image('data:image/png;base64,iVBORw0...', 'myImage.png');
$sourceData = file_get_contents($file);
$resultData = \Tinify\fromBuffer($sourceData)->toBuffer();
Edit:
Alternatively(preferred) you can just use the decoded string as is instead of writing to a file and reading it. Like this:
function base64_to_image($base64_string) {
$data = explode( ',', $base64_string );
return base64_decode($data[ 1 ]);
}
And you can call it like this:
$sourceData = base64_to_image('data:image/png;base64,iVBORw0...');
$resultData = \Tinify\fromBuffer($sourceData)->toBuffer();

writing all files in directory to json

I made simple text editor and now working on image upload and image manager. I have set up manager to read .json file with all images and it works ok. The problem is for php script to actually write newly added images to that json.
$file = "images.json";
$arr_data = array();
foreach(glob('/uploads/*') as $image) {
$arr_data = array(
'link' => $image,
'tag' => 'images',
);
}
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data,$jsondata);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata));
I am getting
Warning: array_push() expects parameter 1 to be array
even tho array data is provided. How to solve this?
If you are starting with an empty file i.e. images.json then the first time you run these 2 lines
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
the second line will change $arr_data into a boolean probably. As json_decode() will fail to convert nothing into an array.
So add this to initialize the file for use
<?php
$file = "images.json";
file_put_contents($file, '[]'); // init the file
You are also reusing the $arr_data variable so amend this also and you are overwriting the new array as well
$file = "images.json";
file_put_contents($file, '[]'); // init the file
$arr_data = array();
foreach(glob('/uploads/*') as $image) {
// amended to not reuse $arr_data
// ameded to not overwrite the array as you build it
$new_arr[] = array( 'link' => $image, 'tag' => 'images');
}
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data,$new_arr);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata));

Save data from modal form using AJAX

I would like to be able to save the data I entered on a modal form to a file and return the data into an alert after submission.
This is the current AJAX I have.
$("#submit").click(function(){
$.ajax({
type: "POST",
url: "save.php",
data: $('#form1').serialize(),
success: function(r){
alert (r);
return false;
},
dataType: "html"
});
$('.modal').modal('show');
});
If you need to see save.php, here it is:
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$data = array(
"name" => $_POST['name1'],
"branch_address" => $_POST['bAddress1'],
"officer_in_charge" => $_POST['officer1'],
"contact_number" => $_POST['contactN1']
); //processes the fields on the form
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
?>
You just need to echo the json data from the PHP file, like this:
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
echo $json;
This is how data is returned via ajax - you simply echo it out, then it should be captured by the script as the variable r in this case.
File save.php
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$data = array(
"name" => $_POST['name1'],
"branch_address" => $_POST['bAddress1'],
"officer_in_charge" => $_POST['officer1'],
"contact_number" => $_POST['contactN1']
); //processes the fields on the form
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
echo $json;
?>
Use echo $json; after the line file_put_contents( $file, $json, FILE_APPEND);

How to generate JSON data with PHP?

CREATE TABLE Posts
{
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
url VARCHAR(200)
}
json.php code
<?php
$sql=mysql_query("select * from Posts limit 20");
echo '{"posts": [';
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
echo '
{
"title":"'.$title.'",
"url":"'.$url.'"
},';
}
echo ']}';
?>
I have to generate results.json file.
To generate JSON in PHP, you need only one function, json_encode().
When working with database, you need to get all the rows into array first. Here is a sample code for mysqli
$sql="select * from Posts limit 20";
$result = $db->query($sql);
$posts = $result->fetch_all(MYSQLI_ASSOC);
then you can either use this array directly or make it part of another array:
echo json_encode($posts);
// or
$response = json_encode([
'posts' => $posts,
]);
if you need to save it in a file then just use file_put_contents()
file_put_contents('myfile.json', json_encode($posts));
Use this:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
You can create the myfile.json before you run the script.But its not compulsory if you have full sudo privileges(read/write permissions(For of you on Mac).
Here is a working Example:
<?php
// data stored in an array called posts
$posts = Array (
"0" => Array (
"id" => "01",
"title" => "Hello",
),
"1" => Array (
"id" => "02",
"title" => "Yoyo",
),
"2" => Array (
"id" => "03",
"title" => "I like Apples",
)
);
// encode array to json
$json = json_encode($posts);
$bytes = file_put_contents("myfile.json", $json); //generate json file
echo "Here is the myfile data $bytes.";
?>
Insert your fetched values into an array instead of echoing.
Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.
If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.
my_json.php
$array = array(
'title' => $title,
'url' => $url
);
echo json_encode($array);
Then in your script set the path to the file my_json.php
Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.
$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT)); // here it will print the array pretty
fclose($fp);
Hope it will works for you....
You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.
First, you need to decode it :
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);
Then change the data :
$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
if ($entry['activity_code'] == '1') {
$data[$key]['activity_name'] = "TENNIS";
}
}
Then re-encode it and save it back in the file:
$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
copy
Use PHP's json methods to create the json then write it to a file with fwrite.

Categories