I have php script, which receives data from javascript application and sends them to email.
Here is how I get the data:
$postdata = file_get_contents('php://input');
$request = json_decode($postdata, true);
And here is how I convert variables:
$premiumTotal = $request['premiumTotal'];
$variant = $request['variant'];
$risksBuilding = $request['risksBuilding'];
When the variable is string - everything works fine.
But the last one is an Array ($risksBuilding) and in e-mail I receive the word "Array".
How can I output this variable ?
Related
Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.
I am working with the SendGrid PHP Library (https://sendgrid.com/docs/Integrate/Code_Examples/php.html).
The response is sent ass JSON - e.g. should be something like:
{"message":"success"}
I can send a simple email via:
<?php
$root="../../";
require $root . 'vendor/autoload.php';
$sendgrid = new SendGrid($SendGrid);
$email = new SendGrid\Email();
$email
//->addTo('you#me.com')
->addTo('you#me.com')
->setFrom('me#bar.com')
->setSubject('Subject goes here')
->setText('Hello World!')
->setHtml('<strong>Hello World!</strong>')
;
$res = $sendgrid->send($email);
?>
When I display the output of $res e.g. using PHP-REF (https://github.com/digitalnature/php-ref) I can see that it looks like this:
It appears the response is an Object - presumably JSON?
However, I can't access the data as JSON because if I try this:
$newtxt = json_decode($res);
I get this error:
Warning: json_decode() expects parameter 1 to be string, object given in C:\xampp\htdocs\jim\001-jimpix\contact_old\test-send-grid.php on line 24
And if I try this:
$j_array = json_decode($res, true);
I get the same error.
I can hard code the "$res" value as:
$res = "{\"message\":\"success\"}";
And then that works.
However, I can't work out how to access the JSON returned by SendGrid.
I've tried various things like:
$res = json_decode(json_encode($res),TRUE);
Presumably there is a way to access the JSON returned by SendGrid so I can access the JSON data.
But I don't know how?
As you can see from the PHP-REF response, $res is not the raw JSON.
You can access the result simply by using $res->getBody(). This will give you the parsed JSON from SendGrid.
You do not need to json_decode this.
I am sending the json data from a python program using the below code
import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)
and receiving it in a php server side using the below code.
<?php
if($_GET['temp_value']) {
$temp_value = $_GET['temp_value'];
echo $temp_value;
# $data = array($id, $description);
$arr=json_decode($temp_value,true);
} else {
echo "not found";}
// Connect to MySQL
include("dbconnect.php");
// Prepare the SQL statement
$SQL = "INSERT INTO test1.temperature1 (temp_value) VALUES ('$arr')";
// Execute SQL statement
mysqli_query($dbh,$SQL);
Echo "<a href=http://localhost/json1/review_data.php><center><u><b><h1>Manage values<h1><b><u></center></a>"
?>
along with the json data I have implemented like Id,time and date also gets updated in the database when i send the data.But what is happening here is like whenever i send the data from the python program it won't give any errors,when i see in the database and in the php page only 0(zero) values are inserted in both,however time and id gets updated.please someone suggest me a proper code and way.
Try this:
<?php
$json_payload = json_decode($_GET['json_payload']);
$temp_value = $json_payload['temp_value'];
?>
When you do this:
r = requests.get('http://localhost/json1/js2.php',data=payload)
You are sending a get request containing a JSON string representation of your data:
'{"temp_value": 132}'
stored in the get parameter named json_payload.
Therefore, on the client side, you must retrieve the contents of the json_payload parameter and decode the JSON string therein in order to retrieve temp_value.
Alternatively, you could do this:
payload = {"temp_value":132}
r = requests.get('http://localhost/json1/js2.php',data=payload)
And leave your PHP code unmodified.
import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)
print(r.url)//http://localhost/json1/js2.php
Json data is not passed in to php.Check your python code
payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
Result:
http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value3
You have to use like
payload = {"temp_value":132}
I'm want to post a binary data string from a Python script to a webserver where a PHP script should pick it up and store it. I receive the whatever I echo in my POST part of the php script on the Python side so I assume, the actual POST works. However, I'm posting 23 Bytes and strlen($_POST['data']) stays 0.
My PHP script to pickj up the data looks like this:
if (isset($_REQUEST["f"]) && $_REQUEST["f"]=="post_status") {
$fname = "status/".time().".bin";
if (file_exists($fname)) {
$fname = $fname."_".rand();
if (file_exists($fname)) {
$fname = $fname."_".rand();
}
}
echo strlen($_POST['data'])." SUCCESS!";
}
and the Python POST script looks like this:
data = statusstr
host = HOST
func = "post_status"
url = "http://{0}{1}?f={2}".format(host,URI,func)
print url
r = urllib2.Request(url, data,{'Content-Type': 'application/octet-stream'})
r.get_method = lambda: 'PUT'
response = urllib2.urlopen(r)
print "RESPONSE " + response.read()
Why does my data not seem to get through, I'm wondering?
Thank you,
PHP will only populate posted values into the $_POST/REQUEST arrays for data that is sent as one of the form data content types. In your case, you need to read in the binary data directly from standard in like this:
$postdata = file_get_contents("php://input");
I am stuck a long time with trying to send a JSON from javascript to a PHP script : the sending is fine (I can see the JSON in fiddler) yet I receive nothing in the PHP script :
javascript:
var person = {
name: 'yoel',
age: 28
};
xmlhttp.open("POST","http://localhost:8888/statisticsdb.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(person));
php :
echo 'trying to print ' . var_dump($_POST["name"]);
I would expect obviously to see SOMETHING but var_dump returns nothing. Help would be much appreciated!
try:
$data = json_decode(file_get_contents('php://input'));
var_dump($data->name);
the reason for this is, that the body of your POST-request is:
{"name":"yoel","age":28}
though, php expects something like (ref):
name=yoel&age=28
The json string can not be parsed properly, and thus $_POST will be empty.
$_POST holds value decoded from request having Content-Type application/x-www-form-urlencoded, i.e. it parses:
param1=value1¶m2=value2
into:
array( 'param1' => 'value1', 'param2' => 'value2')
If you send data in json format, you have to json_decode it from the raw php input:
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
And you'll have a PHP object filled with your json stuff.
Add this:
xmlhttp.setRequestHeader("Content-length", JSON.stringify(person).length);