I'm having a hard time parsing text together with an image. I'm using the slim rest API, and here's my code:
$app->post('/updateprofile', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true);
$id = $data["id"];
$influencer_id = $data["influencer_id"];
$first_name = $data["first_name"];
My problem is what if I want to include a file that is being uploaded by user in the client side, which is an android device, how can I parse the image and put it in a variable?
If possible, you should use multipart/form-data for submission instead of json encoded data, so you can access $_FILES directly. If not possible, or you want to keep using json, you could send the image encoded in base64 as a part of your json and decode it on receive like this:
function base64ToImg($base64_string, $filename) {
$f = fopen($filename, "wb");
$data = explode(',', $base64_string);
fwrite($f, base64_decode($data[1]));
fclose($f);
return $filename;
}
base64ToImg($data["image"], "path/to/img");
EDIT
The usual way to send files to a server is to set the enctype="multipart/form-data" in an html form; doing so, your form will look like
<form name = 'formName' enctype="multipart/form-data">
<input name = 'data1' type = 'text'>
<input name = 'file1' type = 'file'>
</form>
In your server, you will receive the info in $_FILES and $_POST:
<?php
$data1 = $_POST["data1"];
$file = $_FILES["file1"];
move_uploaded_file($file["tmp_name"], "path/to/img");
?>
Since you said that it was an android device, I will add that the form stuff may not be of help if what you are developing is an android app you will have to do something like this (more or less, it has been a long long time since my last android app).
httpClient = new DefaultHttpClient();
post = new HttpPost(yourUrl);
post.setHeader("Content-type", "multipart/form-data");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("data1", new StringBody(data1));
multipartEntity.addPart("file1", new FileBody(file1));
post.setEntity(multipartEntity);
response = httpClient.execute(httpPost);
Related
The issue is, that I am sending a JSON file in a POST request but i don't know how to get the data from the request itself
Here is the python script that sends the POST request:
import json
import httplib
filepath = 'example.txt'
with open(filepath) as fp:
line = fp.readline()
line2 = fp.readline(9)
jsonbaloo = {}
jsonbaloo["name"] = line
jsonbaloo["score"]= line2
result = json.dumps(jsonbaloo)
def post_dict():
headers = {"Content-type": "application/json", "Accept": "text/plain"}
conn = httplib.HTTPConnection('altrevista.org')
conn.request("POST", "/", result, headers)
post_dict()
I want to get the JSON data server side, so I can put it on an SQL database, but I can't program in PHP.
PHP SCRIPT:
<?php
function detectRequestBody() {
$rawInput = fopen('php://input', 'r');
$tempStream = fopen('php://temp', 'r+');
stream_copy_to_stream($rawInput, $tempStream);
rewind($tempStream);
return $tempStream;
}
?>
conn.read() to get the response back
Since you're writing to a file, you can read from the file using PHP with fopen() or file_get_contents().
Using fopen():
$fileHandle = fopen("path/to/example.txt", "r");
Using file_get_contents():
$fileString = file_get_contents("path/to/example.txt");
You should receive the data using file_get_contents (php://input stream) and convert it to an array using json_decode.
// Retrieve the Post JSON data
$input = file_get_contents('php://input');
// Convert to json to array
$array = json_decode($input, true);
// View the content of the array
print_r($array);
im trying to download a remote xml file, but is not working, is not storing the file on my storage.
my code:
$url = 'http://xml.url.xml';
set_time_limit(0);
// Download file and save it on folder
$guzzleClient = new Client();
$response = $guzzleClient->get($url);
$body = $response->getBody();
$body->seek(0);
$size = $body->getSize();
$file = $body->read($size);
Storage::download($file);
The Storage::download() method is used to generate response, that will force the download in the browser.
Use Storage::put('filename.xml', $content) instead.
You can read more in the docs:
https://laravel.com/docs/5.6/filesystem
I have a JSON file badly formatted (doc1.json):
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192}
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472}
{...}{...}
And I have to change it in this:
{"u":[
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192},
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472},
{...},{...}
]}
Can I do this in a PHP file?
//Get the contents of file
$fileStr = file_get_contents(filelocation);
//Make proper json
$fileStr = str_replace('}{', '},{', $fileStr);
//Create new json
$fileStr = '{"u":[' . $fileStr . ']}';
//Insert the new string into the file
file_put_contents(filelocation, $fileStr);
I would build the data structure you want from the file:
$file_path = '/path/to/file';
$array_from_file = file($file_path);
// set up object container
$obj = new StdClass;
$obj->u = array();
// iterate through lines from file
// load data into object container
foreach($array_from_file as $json) {
$line_obj = json_decode($json);
if(is_null($line_obj)) {
throw new Exception('We have some bad JSON here.');
} else {
$obj->u[] = $line_obj;
}
}
// encode to JSON
$json = json_encode($obj);
// overwrite existing file
// use 'w' mode to truncate file and open for writing
$fh = fopen($file_path, 'w');
// write JSON to file
$bytes_written = fwrite($fh, $json);
fclose($fh);
This assumes each of the JSON object repsentations in your original file are on a separate line.
I prefer this approach over string manipulation, as you can then have built in checks where you are decoding JSON to see if the input is valid JSON format that can be de-serialized. If the script operates successfully, this guarantees that your output will be able to be de-serialized by the caller to the script.
I'm working with android and try to create an app that able to upload several image to the server. I had tried to upload the image to my localhost using xampp, it works well. But when I try to upload to my enterprise server I can't find my file, in the other word. The file can't be written. I don't know what make it failed? This is my code
Upload tp XAMPP
Connection string private static final String url_photo = "http://192.168.7.110/blabla/base.php";
Path static final String path = "C:\\xampp\\htdocs\\psn_asset_oracle\\Images\\";
Upload to actual enterprise server
Connection String private static final String url_photo = "http://192.168.4.27/oracle/logam/am/data_images/android_image/base.php";
Path static final String path = "http://192.168.4.27/oracle/logam/am/data_images/android_image/";
My code to upload to server
params_p.add(new BasicNameValuePair("image_name_1",
image_name_1));
params_p.add(new BasicNameValuePair("image_name_2",
image_name_2));
params_p.add(new BasicNameValuePair("image_name_3",
image_name_3));
params_p.add(new BasicNameValuePair("image_name_4",
image_name_4));
json_photo = jsonParser.makeHttpRequest(url_photo, "POST", params_p);
ArrayList<NameValuePair> params_p = new ArrayList<NameValuePair>();
PHP code
if(isset($_POST["image_name_1"]) && isset($_POST["image_name_2"]) && isset($_POST["image_name_3"]) && isset($_POST["image_name_4"])
&& isset($_POST["image_1"]) && isset($_POST["image_2"]) && isset($_POST["image_3"]) && isset($_POST["image_4"]))
{
$image_name_1 = $_POST["image_name_1"];
$image_name_2 = $_POST["image_name_2"];
$image_name_3 = $_POST["image_name_3"];
$image_name_4 = $_POST["image_name_4"];
$image_1 = $_POST["image_1"];
$image_2 = $_POST["image_2"];
$image_3 = $_POST["image_3"];
$image_4 = $_POST["image_4"];
/*---------base64 decoding utf-8 string-----------*/
$binary_1=base64_decode($image_1);
$binary_2=base64_decode($image_2);
$binary_3=base64_decode($image_3);
$binary_4=base64_decode($image_4);
/*-----------set binary, utf-8 bytes----------*/
header('Content-Type: bitmap; charset=utf-8');
/*---------------open specified directory and put image on it------------------*/
$file_1 = fopen($image_name_1, 'wb');
$file_2 = fopen($image_name_2, 'wb');
$file_3 = fopen($image_name_3, 'wb');
$file_4 = fopen($image_name_4, 'wb');
/*---------------------assign image to file system-----------------------------*/
fwrite($file_1, $binary_1);
fclose($file_1);
fwrite($file_2, $binary_2);
fclose($file_2);
fwrite($file_3, $binary_3);
fclose($file_3);
fwrite($file_4, $binary_4);
fclose($file_4);
$response["message"] = "Success";
echo json_encode($response);
}
I've contact my DBA and asked to give me permission to write the file, and it still doesn't work. The error is json doesn't give "Success" as message that indicate the file failed to be written. I will appreciate any help. Thank you.
Does the file server allows write access permission? Sample of chmod, http://catcode.com/teachmod/
Is your enterprise server online? The IP address looks private to me, 192.168.4.27.
Dont use json use http post.
See below code
HttpClient client = new DefaultHttpClient();
String postURL = "your url";
HttpPost post = new HttpPost(postURL);
try {
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(img, "image.jpg");
reqEntity.addPart("image", bab);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
Here img is your image in ByteArray format
The problem solved after my DBA give me another file path.
I want to pass an image as a byte array from php to a .NET web serice.
The php client is as follows:
<?php
class Image{
public $ImgIn = array();
}
$file = file_get_contents('chathura.jpg');
$ImgIn = str_split($file);
foreach ($ImgIn as $key=>$val) { $ImgIn[$key] = ord($val); }
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage(new Image());
echo $result->PutImageResult;
//print_r($ImgIn);
?>
Here is the web method in ASP.NET web service:
[WebMethod]
public string PutImage(byte[] ImgIn)
{
System.IO.MemoryStream ms =
new System.IO.MemoryStream(ImgIn);
System.Drawing.Bitmap b =
(System.Drawing.Bitmap)Image.FromStream(ms);
b.Save("imageTest", System.Drawing.Imaging.ImageFormat.Jpeg);
return "test";
}
When I run this the image content is correctly read to ImgIm array in php client. (In this instance the image had 16992 elements.) However when the array is passed to the web service method it contains only 5 elements (the first 5 elements of the image)
Can I know what is the reason for the loss of data ? How can I avoid it ?
Thanks
file_get_contents returns the file contents as string which is not useful for binary files such as images. Try this:
$handle = fopen("chathura.jpg", "r");
$contents = fread($handle, filesize("chathura.jpg"));
fclose($handle);
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($contents);
Guys, it seems that it is not going to be any use to try and pass data as a byte array as PHP anyway converts it to a string when sending. This conversion seems to introduce control characters to the string, making it only send a part of the byte array. I got this to work by sending a base64 encoded string and decoding inside the server.
My client side code:
<?php
class Image{
public $ImgIn = '';
}
//ini_set("memory_limit","20M");
$imageData = file_get_contents('chathura.jpg');
$encodedData = base64_encode($imageData);
$Img = new Image();
$Img->ImgIn = $encodedData;
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($Img);
echo($result->PutImageResult);
?>
ASP .NET web service code:
[WebMethod]
public string PutImage(String ImgIn)
{
byte[] ImgInBytes = Convert.FromBase64String(ImgIn);
System.IO.MemoryStream ms =
new System.IO.MemoryStream(ImgInBytes);
System.Drawing.Bitmap b =
(System.Drawing.Bitmap)Image.FromStream(ms);
b.Save("C:\\imageTest.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
return "success";
}