How to post and get data from the same php file [PHP] - php

I've php file and with this I want both set and get data. (Is it possible?).
This is my php file:
require_once 'GetAreaDB.php';
$latitudeFrom = $_POST['latitudeFrom'];
$longitudeFrom = $_POST['longitudeFrom'];
$maxDistance = $_POST['maxDistance'];
// These three values come from my swift app.
$getArea1 = new GetAreaDB();
$locals = $getArea1->getPositionByCoordinate($latitudeFrom,$longitudeFrom,$maxDistance);
$jsonArray = array();
foreach ($locals as $local) {
$jsonArray1 = array(
"id" => $local->getID(),
"json_local" => $local->getJSON()
);
array_push($jsonArray,$jsonArray1);
}
echo json_encode($jsonArray);
My idea is to create a php file that receives post parameters and then, on the base of these, it get other data.
How can I solve?

Related

.JSON file creates NULL value via PHP

So I'm trying to figure out why I get a NULL value in my .json file after I try to write the array to it. It only happens with the 'array_push' line after creating a new file. If there is a .json file already there with a value in it, it'll write to it correctly. The only thing I could guess was the file is missing the '{' and '}' in it upon creation.
I've got a small work around so far, but not sure that this is the right way to do it. Can someone tell me if this is good or bad?
Just to clarify, the .json document only holds the vault of NULL, there are no array elements or anything in the file besides the word NULL.
//CHECK IF FILE EXISTS, ELSE CREATE IT
$log_filename = "./site_files/logs/error-404-log.json";
if(!file_exists($log_filename)) {
touch($log_filename);
//LINE BELOW IS MY WORK AROUND, I'M NOT SURE IF THIS IS THE RIGHT WAY
file_put_contents($log_filename, json_encode(json_decode("{}")));
echo "$log_filename was created. <br />";
}
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($log_array != "") { $log_array = json_decode($json_data, true); }
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
$log_filename = "error-404-log.json"; // establish the path/to/filename.json
if (file_exists($log_filename)) { // if path/to/filename.json exists
$json = file_get_contents($log_filename); // access PRETTY json string
echo "pre-existing data: <div><pre>$json</pre></div><br>"; // display json string
$array = json_decode($json, true); // decode to prepare for new data
}
// data always maintains the same structure: an array of 2-element arrays
$array[] = [
'current_date_stamp' => date('Y-m-d H:i:s'),
'current_page_trail' => "foo"
];
// create/update the file
$new_json = json_encode($array, JSON_PRETTY_PRINT); // re-encode updated array data
echo "new data: <div><pre>$new_json</pre></div>"; // display new json string
file_put_contents($log_filename, $new_json); // create or overwrite file
Your code is failing because you are comparing $log_array with an empty string, this condition will always pass because this array will never be an empty string. In the if statement you decode the contents of the file, when the file has no content this will be an empty string and it will return NULL, after this you write this NULL value to your file. If you check if $json_data is an empty string your code should work, I would also recommend doing it like this:
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($json_data != "") {
$log_array = json_decode($json_data, true);
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
}
This is better since if the string is empty all other actions are irrelevant.

Get data to/from secondary PHP file - works with some data, not with other

I have a SPA (react) that is uses PHP calls to connect to a MongoDB.
Works great.
However, due to 'rules' I need to serve the javascript files from a different server -- a server that supports neither MongoDB nor MongoDB php client. Let's call this server, SERVER_A.
Let's call the server hosting the MongoDB PHP client and the MongoDB, SERVER_B. ('B' for 'backend'... :) )
The solution, I believe, was to build a php 'middleman' on SERVER_A that simply passes data on to SERVER_B. Research shows me that file_get_contents is the tool for this.
So I take my original known-working PHP file, I put it on SERVER_B and rename it to "mongoPatch_backend.php".
<?php
$user = "xxxx";
$pwd = 'xxx';
$filter = [];
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],
];
$bson = MongoDB\BSON\fromJSON($newData);
$value = MongoDB\BSON\toPHP($bson);
$manager = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#SERVER_B:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
[$needleKey => $needle],
['$set' => $value],
['multi' => false, 'upsert' => true]
);
$results = $manager->executeBulkWrite('sedwe.users', $bulk);
var_dump($results);
?>
On SERVER_A I then make a new file, dbPatch.php, like so:
<?php
$API = "https://SERVER_B/php/mongoPatch_backend.php?";
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$postData = "needleKey=".urlencode($needleKey);
$postData .= "&needle=".urlencode($needle);
$postData .= "&newData=".urlencode($newData);
// echo $API.$postData;
$data = file_get_contents($API.$postData);
echo $data;
?>
But when I call it, I get nothing echo'd back out of $data.
Any idea why? Remember, the exact same call directly to mongoPatch_backend.php works just fine (but it's a CORS call, so it's not a valid option).
So here is what I've tried:
First, to ensure my AJAX call was still working, I spit out the response to the console. I get nothing.
So I changed the last line of the middleman (dbPatch.php) to echo "Hello World" instead of echo $data and received "Hello World" on the console as expected.
Next, I then changed the last line of my middleman (dbPatch.php) back to echo $data and tried reducing the 'backend' to a simple <?php echo "Hello Back World"; ?> and got nothing on the console.
Next, I go to https://SERVER_B/php/mongoPatch_backend.php in a browser ... and I'm greeted with "Hello Back World" as expected in the browser.
... which leads me to believe something is up with the transferring of info from server to server. Logical call, eh?
Unfortunately, when I try the same thing with just a 'fetch' command, it works perfectly fine:
Here is my 'middleman' (dbFetch.php) script on SERVER_A:
<?php
$API = "https://SERVER_B/php/mongoFetch_backend.php?";
$collection = $_REQUEST['collection'];
$postData = "collection=".urlencode($collection);
$needleID = $_REQUEST['needleID'];
$postData .= "&needleID=".urlencode($needleID);
$data = file_get_contents($API.$postData);
echo $data;
?>
And this is the file on the backend, SERVER_B:
<?php
$user = "xxxx";
$pwd = 'xxxx';
$filter = [];
if (isset($_REQUEST['needleID'])) {
$needleID = $_REQUEST['needleID'];
$filter = ['id'=> $needleID];
}
if (isset($_REQUEST['collection'])) {
$collection = $_REQUEST['collection'];
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#SERVER_B:27017");
// Query Class
$query = new MongoDB\Driver\Query($filter);
$rows = $connection->executeQuery("db_name.$collection", $query);
// Convert rows to Array and send result back to client
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>
Huzzah, this works! ... and it's also proof there doesn't appear to be a problem with the server-to-server communication.
So back to ground zero.
I then go with a very simple newData value -- shorter, but same general layout - stringified json. It works! The data ends up in the database.
So I'm forced to think something is wrong with the data in newData (which is only a few hundred lines of stringified JSON made like this: encodeURIComponent(JSON.stringify(newData)). But, this bears repeating: this works if I skip the middleman.
... and that puts me at a loss. PHP isn't something I understand well... can you help?
EDIT to answer comment:
When I call mongoPatch_backend.php directly on SERVER_B it works (as stated above). I had it echo the $newData and it spits out a stringified JSON version of the variable (not URLencoded).
When I call dbPatch.php, it does not give me anything that was passed back from mongoPatch_backend.
As I said in the OP, if I modify mongoPatch_backend.php to do nothing other than echo "hellow world" I am still unable to log it to console when calling it via the above dbPatch.php file.
EDIT: I also tried putting the two PHP files on the same server and am getting the same results. (ie: both the dbPatch.php and mongoPatch.php files are in the same directory on the same server)
EDIT2: I have done a var_dump from the middleman and I get standard-looking human-readable stringified text back.
I do the same var_dump($_REQUEST['newData']); in the backend file and I get nothing back.

How can I select the key to remove? PHP and JSON

I'm trying to select a dynamic method to remove key from a json file,at the moment, this code overwrite ALL json file and write {"0":{"name":null,"url":null}} do you know how can I solve it? I just want delete ONE key when I press delete button.
PHP:
<?php
var_dump($_POST);
$data_url = 'js/json.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
$data[] = array(
'name' => $name,
'url' => $url
);
foreach($data as $key=>$val){
// check status
if ($val["status"]=="DELETE"){
// this deletes record from array
unset($data[$key]);
}
}
file_put_contents('js/json.json', json_encode($data, JSON_FORCE_OBJECT));
header('Location: http://URL/index.php');
?>
JSON:
[{"name":"asdf","url":"asdf"},{"name":"asfd","url":"dsaf"}]
You are reading the data into $data_array and writing out $data, so what you are writing is the data you want to delete - after you've processed it to delete all the records.
What this code does is take the $url value (from however it's set) and goes through the $data_array read from the input file and if it finds a match, it removes it. Then writes out $data_array back to the file.
$data_url = 'js/json.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
// Next line just for testing
//$url = "asdf"; // $_POST['URL']; ?
foreach($data_array as $key=>$val){
// check URL
if ($url == $val["url"]){
// this deletes record from array
unset($data_array[$key]);
}
}
$data_array = array_values($data_array);
file_put_contents($data_url, json_encode($data_array));

Sending JSON Array via PHP (Campaign Monitor)

I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php
This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}

HTTP PUT Parameter

I create a rest-webservice with the php framework "tonic".
I have a User Class and handle it with the library.
According to CRUD i use HTTP_PUT to UPDATE the User:
function put($request) {
$response = new Response($request);
$split = explode ('&',$request);
$para = array();
foreach($split as $i) {
$names = explode('=',$i);
$para[$names[0]] = $names[1];
}
$response->body = var_dump($para);
return $response;
}
My Question is how do I access the calling parameters?
At the moment I parse it manually into an array.
PHP will not translate a classic "application/x-www-form-urlencoded" request into $_POST / $_GET if the method is PUT (and there is no $_PUT).
So if you use this content type you have to parse the query string manually:
<?php
$putdata = fopen("php://input", "r");
$para = parse_str($putdata);
http://www.php.net/manual/en/features.file-upload.put-method.php

Categories