i've tried a lot of things to achieve this but none of them seem to
work. Im using PHP 7.4
Let's say i have this:
$othervar = array();
$var = array(1, 2, 3);
$othervar = $var;
THIS doesn't work for me, var_dump($othervar) returns
array(1) { [0]=> string(5) "Array" }
I've tried using array_push, i DON'T WANT to use array_merge because i
need to assign two arrays to one variable. This is what i need to do:
$variable = array();
$variable["type1"] = $data; //Array 1
$variable["type2"] = $otherData; //Array 2
This doesn't work either.
Barmar showed me here that this works so i must be doing it wrong somewhere else.
I'll explan the whole code:
To login to my webpage, i send a request trough AJAX request with jQuery.
function SendData(data, btn, actionOnSuccess, shouldReplace = false, elementToReplace = "", getServerData = true, htmlData = "") {
if (!loading)
{
ToggleLoading();
data.push({name: "action", value: $(btn).data("action")});
data.push({name: "attr", value: JSON.stringify($(btn).data("attr"))});
$.post("SendRequest.php", data)
.done(function (r) {
if (!r.success)
//ajax sent and received but it has an error
else
//ajax sent and it was successfull
})
.fail(function () {
//ajax call failed
});
}
else {
//This determines if some request is already executing or not.
}
}
"action" and "attr" are encrypted values that i send to reference some actions on the system (i'll show more here):
The code goes from AJAX to SendRequest.php where it executes an action let's say, login.
The first lines of SendRequest.php are:
require "Functions.php";
$apiAction = Decrypt($_POST["action"]); //Action
$actionData = json_decode(Decrypt($_POST["attr"])); //Attr
$finalPost = $_POST;
foreach ($actionData as $key => $value) { $finalPost[$key] = $value; }
$finalPost["loggedin_ip"] = $_SERVER['REMOTE_ADDR'];
$result = APICall($apiAction, $finalPost);
Then, this is what i want to achieve to communicate with my API:
function APICall($option, $data = array())
{
session_start();
$post = array("uData" => ArrayToAPI($_SESSION), "uPost" => ArrayToAPI($data));
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_URL, "https://apiurl?" . $option); //option is the ACTION to perform on API (let's say "login") it is an encrypted word on a data-attr atribute on every form/button that creates a communication with API.
$returned = curl_exec($ch);
curl_close ($ch);
$newData = json_decode($returned, true);
return $newData;
}
function ArrayToAPI($array)
{
$toApiData = array();
foreach ($array as $key=>$value) {
if (is_array($value))
$toApiData[$key] = ArrayToAPI($value);
else
$toApiData[$key] = Encrypt($value);
}
return $toApiData;
}
This is what i have on API side:
ob_start();
var_dump($_POST);
$result = ob_get_clean();
$api->EndRequest(false, array("errorDesc" => "a - " . $result));
function EndRequest(bool $task_completed, array $data = array())
{
$jsonData = array();
$jsonData['success'] = $task_completed;
$jsonData['data'] = $data;
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsonData, JSON_FORCE_OBJECT);
exit;
}
This ALWAYS returns
array(2) { ["uData"]=> string(5) "Array" ["uPost"]=> string(5) "Array" }
I hope im more clear now, thanks.
The problem is with the request being sent out from your code because of this line:
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
CURLOPT_POSTFIELDS doesn't support multi-level arrays. Your array values (which the keys are pointing to) are cast to string, which ends up as Array. Use:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
.. instead to "properly" serialize multidimensional arrays in a post request ("properly" as there are many ways to do just that, but it matches the expected PHP format - with [] to denote arrays).
Related
I'm trying to get the details from this example (i created the code right now).
But i'm very... confused... how can i get the details of the link, then separate and send to my MYSQL database..
<?php
$ch = curl_init();
$url = "https://reqres.in/api/users?page=2";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
if($e = curl_error($ch)) {
echo $e;
}
else {
$decoded = json_decode($resp, true);
//print_r($decoded);
foreach($decoded as $key => $item) {
$array = array(
'id' => ,
'email' => ,
'first_name' => ,
'last_name' => ,
);
print_r($array);
}
}
curl_close($ch);
?>
If you call the url in your browser then you will see that the result array is present in the data field.
You may check this by printing the whole result:
print_r($decoded);
So if you like to print_r the results it should be simply
print_r($decoded['data']);
If you like to store it in your database you may walk through the array and store each item
foreach($decoded['data'] as $item) {
storeItem($item);
}
To make this work you should implement the storeItem function which accepts the array $item and stores it into your database. There are various tutorials about doing that.
I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);
I'm new to JSON Code. I want to learn about the update function. Currently, I successfully can update data to the database. Below is the code.
<?php
require_once "../config/configPDO.php";
$photo_after = 'kk haha';
$report_id = 1;
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport?taskname=&reportStatus=&photoBefore=&photoAfter=". urlencode($photo_after) . "&reportID=$report_id";
$data = file_get_contents($url);
$json = json_decode($data);
$query = $json->otReportList;
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
the problem is, if the value of $photo_after is base64 string, which is too large string, it will give the error:
1) PHP Warning: file_get_contents.....
2) PHP Notice: Trying to get property 'otReportList' of non-object in C:
BUT
when I change the code to this,
<?php
require_once "../config/configPDO.php";
$photo_after = 'mama kk';
$report_id = 1;
$sql = "UPDATE ot_report SET photo_after ='$photo_after', time_photo_after = GETDATE(), ot_end = '20:30:00' WHERE report_id = '$report_id'";
$query = $conn->prepare($sql);
$query->execute();
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
The data will updated including when the value of $photo_after is in base 64 string.
Can I know what is the problem? Any solution to allow the base64 string update thru json link?
Thanks
// ...
// It's likely that the following line failed
$data = file_get_contents($url);
// ...
If the length of $url is more than 2048 bytes, that could cause file_get_contents($url) to fail. See What is the maximum length of a URL in different browsers?.
Consequent to such failure, you end up with a value of $json which is not an object. Ultimately, the property otReportList would not exist in $json hence the error: ...trying to get property 'otReportList' of non-object in C....
To surmount the URL length limitation, it would be best to embed the value of $photo_after in the request body. As requests made with GET method should not have a body, using POST method would be appropriate.
Below is a conceptual adjustment of your code to send the data with a POST method:
<?php
require_once "../config/configPDO.php";
# You must adapt backend behind this URL to be able to service the
# POST request
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport";
$report_id = 1;
$photo_after = 'very-long-base64-encoding-of-an-image';
$request_content = <<<CONTENT
{
"taskname": $taskname,
"report_id": $report_id,
"photoBefore": $photoBefore,
"photo_after": $photo_after,
"reportStatus": $reportStatus
}
CONTENT;
$request_content_length = strlen($request_content);
# Depending on your server configuration, you may need to set
# $request_headers as an associative array instead of a string.
$request_headers = <<<HEADERS
Content-type: application/json
Content-Length: $request_content_length
HEADERS;
$request_options = array(
'http' => array(
'method' => "POST",
'header' => $request_headers,
'content' => $request_content
)
);
$request_context = stream_context_create($request_options);
$data = file_get_contents($url, false, $request_context);
# The request may fail for whatever reason, you should handle that case.
if (!$data) {
throw new Exception('Request failed, data is invalid');
}
$json = json_decode($data);
$query = $json->otReportList;
if ($query) {
echo "Data Save!";
} else {
echo "Error!! Not Saved";
}
?>
sending a long GET URL is not a good practice. You need to use POST method with cURL. And your webservice should receive the data using post method.
Here's example sending post using PHP:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
Sample code from: PHP + curl, HTTP POST sample code?
And all output from the webservice will put in the curl_exec() method and from there you can decode the replied json string.
Any idea how one would update a user's Twitter status with an image - using the Twitter-Async class?
This is what I have
$twitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET,$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
$array = array('media[]' => '#/img/1.jpg','status' => $status);
$twitter->post('/statuses/update_with_media.json', $array);
With thanks to #billythekid, I have managed to do this. This is what you need to do:
Look these functions up in the EpiOAuth file and see what I've added and alter it where necessary.
EpiOAuth.php
//I have this on line 24
protected $mediaUrl = 'https://upload.twitter.com';
//and altered getApiUrl() to include check for such (you may wish to make this a regex in keeping with the rest?)
private function getApiUrl($endpoint)
{
if(strpos($endpoint,"with_media") > 0)
return "{$this->mediaUrl}/{$this->apiVersion}{$endpoint}";
elseif(preg_match('#^/(trends|search)[./]?(?=(json|daily|current|weekly))#', $endpoint))
return "{$this->searchUrl}{$endpoint}";
elseif(!empty($this->apiVersion))
return "{$this->apiVersionedUrl}/{$this->apiVersion}{$endpoint}";
else
return "{$this->apiUrl}{$endpoint}";
}
// add urldecode if post is multiPart (otherwise tweet is encoded)
protected function httpPost($url, $params = null, $isMultipart)
{
$this->addDefaultHeaders($url, $params['oauth']);
$ch = $this->curlInit($url);
curl_setopt($ch, CURLOPT_POST, 1);
// php's curl extension automatically sets the content type
// based on whether the params are in string or array form
if ($isMultipart) {
$params['request']['status'] = urldecode($params['request']['status']);
}
if($isMultipart)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params['request']);
else
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->buildHttpQueryRaw($params['request']));
$resp = $this->executeCurl($ch);
$this->emptyHeaders();
return $resp;
}
Post image
// how to post image
$twitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET,$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
$array = array('#media[]' => '#/img/1.jpg','status' => $status);
$twitter->post('/statuses/update_with_media.json', $array);
I'm using CURL to post to a script hosted on a remote server.
I'm sending a multidimensional array using this:
$urlserver = "myserver";
$arraytag = array('tags'=>$taggenerici,'tagesplosi'=>$tagesplosi,'matrice'=>$matricefin,'id' =>$identificativo);
$postfields = http_build_query($arraytag);
//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$urlserver);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_POST,sizeof($postfields));
curl_setopt($ch, CURLOPT_POSTFIELDS,$postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1); // RETURN THE CONTENTS OF THE CALL
//execute request sending post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
The problem is about the result: infact if i try to execute my script i get a randomic result. I'd like to view an array of 20rows X 43columns but it stops at row10 and column28. But if i refresh my page after some try i get my full array.
I'd like to say that i have tried to get the array before sending it to the remote server and it works fine cos i get my array entirely without any kind of cutting.
script being called (minus unused mysql connection):
<?php
$taggenerici = $_POST['tags'];
$matrice = $_POST['matrice'];
$identificativo = $_POST['id'];
$tagesplosi = $_POST['tagesplosi'];
//Here i create the array with "a" and "?"
for($dom=0;$dom<sizeof($identificativo);$dom++) {
for ($tag=0;$tag<sizeof($taggenerici);$tag++) {
$matrice[$dom][$tag] = "a, ";
}
$tagAdd=sizeof($taggenerici)+1;
$matrice[$dom][$tagAdd] ="?";
}
//Here i set "p".
for($dom=0;$dom<sizeof($identificativo);$dom++) {
for ($tag=0;$tag<sizeof($taggenerici);$tag++) {
for ($tagarray=0;$tagarray<sizeof($tagesplosi[$dom]);$tagarray++) {
if ($taggenerici[$tag] == $tagesplosi[$dom][$tagarray]) {
$matrice[$dom][$tag] = "p, ";
}
}
}
}
//this is the $result which I call on the client. (echo $valore);
foreach ($matrice as $kappa => $vu) {
echo "<br>";
foreach ($vu as $kii => $valore)
echo $valore;
}
}