Store and prepare data in php with specific parameter request url - php

I have seen here this url json response data file from Highstock:
https://www.highcharts.com/samples/data/jsonp.php?filename=msft-c.json
So the data (encoded in json format) taken via GET request changes every time that the filename parameter value is different, for example in our case we can call different data by using these other 2 parameters: aapl-c.json and goog-c.json.
How can be performed in php the same data preparation for store multiple data resources with different filenames values request? And can we call a specific portion of data by using different parameter values? Also a very simple explanation of the logic behind this process would be enough.

I am skipping some verifications here, but the process is quite simple, this is a quite basic GET var analysis. When there is ?varname=value at the end of th URL, PHP gets the variable in the $_GET array. However, it is quite unsafe to use it raw, you should filter it before.
Another advice here is not to try to load a file dynamically from this var value or these kind of things, for security reasons. It is better to only allow desired values (used a switch here that have a quite strange syntax, but if/else fit just the same).
Then with php, you have to create your document with a display, like echo. In this case, it is JSON, so you just have to output your JSON.
Would be something like:
<?php
//sanitize the value from $_GET array
$getVar = filter_input(INPUT_GET, 'filename', FILTER_SANITIZE_STRING);
//do various things depending on value
switch($getVar){
case 'aapl-c.json':
$display = '{ "content": "i am JSON 1" }';
break;
case 'goog-c.json':
$display = '{ "content": "i am JSON 2" }';
break;
default:
$display = '';
}
//send the json data to the document
echo $display;
//terminate script for security
exit;

Related

How to handle multiple request coming at the same time php

I have configured a url to other platform which is webhook for them. In this URL, order are coming simultaneously, which i manipulate and save it to the database.
The problem is that sometimes order timings are exactly same, so the orders data are mixed with each other and wrong information is saving into the database.
How would i handle this situation in php as i am using core php.
So that when two or more request are coming together, so each will be executed one by one.
For reading the input data sent to the url is
file_get_contents('php://input');
PHP CODE :
case "order_relay":
$body = file_get_contents('php://input');
$data = (array) json_decode($body);
$orderData = (array) $data['order']->details;
break;

Writing values to INI file

I'm trying to store multiple data and then at the end go a head and push the data into the new .ini file. I found solutions which works but I want to get all the data first and then update the file at the end but the solutions i found updates the file straight away!
A solution I liked and worked is located: https://stackoverflow.com/a/36997282/6613233
I am trying to allow it gather information and then push it to the file at the end. My own attempt at this is below but i keep getting array array in my ini file.
Code:
$fbsettingsDB = parse_ini_file("location.ini", true);
$fbsettingsDB["id"]["value"] = $_POST['fbconfigid'];
$fbsettingsDB["location"]["value"] = $_POST['fbconfigcty'];
file_put_contents('location.ini', implode("\n", $fbsettingsDB));
The above is how I want to collect data. I have a bunch of code which goes in and out of statements, I want it to go ahead.. Assign the values required and at the very end go ahead and put the contents in the file like shown above.
Using the referred code i would then have to do:
config_set("location.ini", "id", "value", $_POST['fbconfigid']);
config_set("location.ini", "location", "value", $_POST['something']);
config_set("location.ini", "result", "value", $_POST['somethingelse']);
Which overwrites the file every time which in my opinion is just crazy! Overkill for my idea, there is obviously some way that can suit my needs so i can just call the function once after making a list of edit/changes and then when i call the function it grabs all my changed data and saves the file the way i want it!
I'll try to explain first why your code doesn't work, compared to the other.
Your inifile-array is build up of a nested array, $array[section][item] = value. The first dimension has the section names. The second dimension is the name of the items in the sections. So $fbsettingsDB["location"] contains an array of items, of which "value" is one.
Implode doesn't check if the array is nested. It just takes the first dimension (the sections) and tries to treat their values as a string. Since those values are actually arrays of items, PHP just converts that to the text 'array'.
Apart from that, you can't just implode the whole array. Section names should be enclosed in square brackets, so there is a little more work to do in that regard too.
If you check the solution in the answer you referred to, you'll see that it contains a loop which takes care of the first layer, the sections.
The array of items of each section is converted separately with implode, which is then prefixed by the section name in square brackets, and the whole lot is appended to the end result.
So, your intention here: You don't want to set a value and write it back to file at once, but update multiple values and only write the end result to disk. Well, fortunately the function doesn't have to be atomic. It already performs three separate actions: loading from disk, modifying the data, and serializing it back to disk. Let's see if those can be isolated in separate functions:
Read the data. Well, hardly worth to make a function, but it may make your application somewhat more consistent if you use the same naming et cetera in a collection of related functions.
Note: I just wrote these from scratch. No PHP at hand to test, so they might contain minor syntactical errors.
So here it is:
// Loads ini file data
function config_read($config_file) {
return parse_ini_file($config_file, true);
}
Setting the config in the loaded data. Again, hardly worth to have a function, but it adds readability and hides how exactly the ini file data is built up, so you don't have to worry about implementation details when using it. Note that the array is passed by reference. The array you specify is updated. The function doesn't return a value.
// Update a setting in loaded inifile data
function config_set(&$config_data, $section, $key, $value) {
$config_data[$section][$key] = $value;
}
Then writing it:
// Serializes inifile config data back to disk.
function config_write($config_data, $config_file) {
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$value";
}, array_values($section_content), array_keys($section_content));
$section_content = implode("\n", $section_content);
$new_content .= "[$section]\n$section_content\n";
}
file_put_contents($config_file, $new_content);
}
Note that so far I didn't modify any of the code. I just wrapped it in separate functions. If you like, you could even call those functions in another function, so you still got the shorthand to write everything to disk at once. You'll have the original functionality, but without having duplicate code:
// Short-hand function for updating a single config value in a file.
function config_set_file($config_file, $section, $key, $value) {
$config_data = config_read($config_file);
config_set($config_data, $section, $key, $value)
config_write($config_file, $section, $key, $value);
}
So, now you got this collection of functions, you can decide which to use based on the situation. If you just want to update a single value, you might as well write this:
config_set_file("location.ini", "id", "value", $_POST['fbconfigid']);
But if you have multiple configs to set, you can do this:
// Load
$config_data = config_read("location.ini");
// Set multiple values
config_set($config_data, "id", "value", $_POST['fbconfigid']);
config_set($config_data, "location", "value", $_POST['something']);
config_set($config_data, "result", "value", $_POST['somethingelse']);
// Save
config_write($config_data, $config_file);
I can imagine you can add other shorthands, like config_set_array_file, which you could call like this.. I'll leave the implementation of this one to you for exercise. ;)
array_config_set_file($config_file, array(
"id" => $_POST['fbconfigid'],
"location" => $_POST['something'],
"result" => $_POST['somethingelse']));
And after that, you can poor all this into an IniFile class to make it even nicer. :)

Create a script that dies when it detects base64 in the $_Post array

I have been trying to create a little script that dies when it detects base64 encoded information being posted to our server.
For some reason it is not entering the loop ...
if (in_array('base64_decode', $_POST, true)) { ... }
When I test it. What am I missing?
Edit: Sorry for this misunderstanding I wasn't clear enough. I am having things like ...
[gkwdwjfvzjpj] => eval(base64_decode($_POST....
Posted to the server and I want to know how can I just detect this string.
What your code searches for is whether or not the string "base64_encode" is one of the POSTed values.
If you want to check if base64_decode is in a substring of the POSTed data:
function spam_in_post_values () {
foreach ($_POST as $postval) {
if (strpos($postval, 'base64_decode') !== false) {
return true;
}
}
return false;
}
However, it seems that you are inserting POSTed data into the HTML, which is a bad idea.
There is a principle in programming called Don't trust user input. You should:
never ever directly insert user input into the HTML
<p><?php echo $_POST['userdata']; ?></p>
when the user posts something like
"</p><script>location.href='http://otherwebsite';</script>"
your users will be kidnapped!
The same is true for attributes, never use unescaped userdata in attributes:
<a onclick="alert('Hello <?php echo $_POST['username']; ?>!')">
When the user posts "'); location.href='http://spamsite.com';('"
users of your website will get kidnapped!
never ever directly eval user input in PHP:
$x = $_POST['x']; // we expect "5"
$y = $_POST['y']; // we expect "3"
$operator = $_POST['operator']; // we expect "*", "+", "-", "/"
$result = eval($x . $operator . $y);
When the user sends malicious data, he can do everything you can do with your privileges
in PHP. Delete files, send emails, download and install malware to your server, and so on.
never ever run eval on user input in JavaScript (even better, never use eval!)
For the same reasons outlined above, malicious input can run arbitrary code in your client.
If you expect to get JSON data, use JSON.parse(jsondata) to get them as an object (or jQuery.parseJSON(...), or angular.parseJSON(...), or whatever your library provides).
This also extends to "hidden" uses of eval, like new Function("arg", userSuppliedString), event handlers element.onclick = "alert('<user supplied value>')", setTimeout/setInterval calls setTimeout("element.textContent = " + userSuppliedValue, 3000), etc.
Instead of testing for data that you do not want, validate that you received data you do want.

query string in php url which fetches values from files in directories

for security reasons we need to disable a php/mysql for a non-profit site as it has a lot of vulnerabilities. It's a small site so we want to just rebuild the site without database and bypass the vulnerability of an admin page.
The website just needs to stay alive and remain dormant. We do not need to keep updating the site in future so we're looking for a static-ish design.
Our current URL structure is such that it has query strings in the url which fetches values from the database.
e.g. artist.php?id=2
I'm looking for a easy and quick way change artist.php so instead of fetching values from a database it would just include data from a flat html file so.
artist.php?id=1 = fetch data from /artist/1.html
artist.php?id=2 = fetch data from /artist/2.html
artist.php?id=3 = fetch data from /artist/3.html
artist.php?id=4 = fetch data from /artist/4.html
artist.php?id=5 = fetch data from /artist/5.html
The reason for doing it this way is that we need to preserve the URL structure for SEO purposes. So I do not want to use the html files for the public.
What basic php code would I need to achieve this?
To do it exactly as you ask would be like this:
$id = intval($_GET['id']);
$page = file_get_contents("/artist/$id.html");
In case $id === 0 there was something else besides numbers in the query parameter. You could also have the artist information in an array:
// datafile.php
return array(
1 => "Artist 1 is this and that",
2 => "Artist 2..."
)
And then in your artist.php
$data = include('datafile.php');
if (array_key_exists($_GET['id'], $data)) {
$page = $data[$_GET['id']];
} else {
// 404
}
HTML isn't your best option, but its cousin is THE BEST for static data files.
Let me introduce you to XML! (documentation to PHP parser)
XML is similar to HTML as structure, but it's made to store data rather than webpages.
If instead your html pages are already completed and you just need to serve them, you can use the url rewriting from your webserver (if you're using Apache, see mod_rewrite)
At last, a pure PHP solution (which I don't recommend)
<?php
//protect from displaying unwanted webpages or other vulnerabilities:
//we NEVER trust user input, and we NEVER use it directly without checking it up.
$valid_ids = array(1,2,3,4,5 /*etc*/);
if(in_array($_REQUEST['id'])){
$id = $_REQUEST['id'];
} else {
echo "missing artist!"; die;
}
//read the html file
$html_page = file_get_contents("/artist/$id.html");
//display the html file
echo $html_page;

Receive http $_POST and feed into SimpleXML

I'm currently trying to setup a page which receives XML via an HTTP POST. I have successfully used SimpleXML to retrieve the XML from a file and then perform my logic, but I am unsure how to set it up to receive a POST submission.
Is there a default way to retrieve all information from $_POST as a string?
//'get'ting the xml from a file
$job = simplexml_load_file(/path/to/file);
//my assumption on how to accept the XML post - throws a not string error
$job = simplexml_load_string($_POST);
As the is being received from a third party, is there extra information that I am not being supplied? All my previous handlings have been with name=value pairs, i.e. $value = $_POST['name']; To rephrase, do all HTTP POSTs have a name handle to them?
Sorry for the multi-faceted question, I'm a bit lost, so am trying to cover all angles.
Any help is greatly appreciated!
You're most likely looking for the raw POST data.
$postdata = file_get_contents("php://input");
This code will combine all posted variables into a single string variable:
$foo = "";
foreach( $_POST as $val )
{
$foo .= $val;
}
well, if you are receiving xml with using post, why not are you using xmlrpc?

Categories