I have a file which is a small place_config.php file.
Take this as an example where i am setting my variables
<?php
//config file
$place_config = array(
'credentials' => array(
'sid' => 'some_value',
'token' => 'some_token'
)
?>
I want to change the sid and token from the admin panel of the user for the ease. How can i effectively achieve this. One solution which i understand is to make the content of the file in a string with the variables of $_REQUEST placed after the post request write that whole string to the file? Is it a effective approach?
Submit a form with the proper inputs and when submitted call update_place_config():
function update_place_config() {
include('place_config.php');
$place_config['credentials']['sid'] = $_POST['sid'];
$place_config['credentials']['token'] = $_POST['token'];
$output = '<?php $place_config = ' . var_export($place_config, true) . '; ?>';
file_put_contents('place_config.php', $output);
return $place_config; //if you want to get the new config
}
Another option:
$content = file_get_contents('place_config.php');
$content = preg_replace("/('sid' =>) '[^']+'/", "$1 '{$_POST['sid']}'", $content);
file_put_contents('place_config.php', $content);
I personally would store in a database or use JSON if it needs to be a file.
Instead of storing the configuration data in a php file, I'll recommend storing them in a json file which can be easily read/edited through php.
Create a json file, let's say config.json. Then you can load the configuration using $conf = json_decode(file_get_contents("config.json")). You can make changes to the $conf object and save back the configurations as file_put_contents("config.json", json_encode($conf)).
I want to get request in a website like that
$id = "something";
$response = http_get("http://example.com?id=$id, array("timeout"=>1), $out);
I don't find how exactly I can use http_get
I've tried with file_get_contents, it is working like
$out = file_get_contents("http://www.example.com?id=something");
but I want it like that
$out = file_get_contents("http://www.example.com?id=$id");
this one is not working
The way I got it to work was using the code below.
$out = file_get_contents("http://www.example.com?id=".$id);
This will concatenate the $id variable contents onto the end of the url to request.
Basically I need some help sending array information through redirects in PHP. I have the following code:
Page1: I created the query string and sent it to page 2, I can get the data in $_GET on page 2.
$qstr = http_build_query(
array(
'products_array' => $products,
'quantity' => $_POST['quantity']
)
);
header('Location: registration.php?' . $qstr);
Page 2/3 I get the query string from $_server and concatenate it with the redirect page
header('Location: login.php?' . $_SERVER['QUERY_STRING']);
I can send the data using normal href links, but if I try to send it like above I can't retrieve the data past page 2.
If you could give me some input on this problem it would really help.
Thanks.
Edit:
echoing $qtystr gives:
products_array%5B0%5D%5Bitem%5D=http%3A%2F%2Fecx.images-amazon.com%2Fimages%2FI%2F61Y-rF9tF8L.SL1100.jpg&products_array%5B0%5D%5Bbrand%5D=Charmander&products_array%5B0%5D%5Bprice%5D=25&products_array%5B1%5D%5Bitem%5D=http%3A%2F%2Fecx.images-amazon.com%2Fimages%2FI%2F61vgC3GDI2L.SL1100.jpg&products_array%5B1%5D%5Bbrand%5D=Squirtle&products_array%5B1%5D%5Bprice%5D=15&products_array%5B2%5D%5Bitem%5D=http%3A%2F%2Fecx.images-amazon.com%2Fimages%2FI%2F51TnHKT4oML.SY300.jpg&products_array%5B2%5D%5Bbrand%5D=Bulbasaur&products_array%5B2%5D%5Bprice%5D=10&products_array%5B3%5D%5Bitem%5D=http%3A%2F%2Fecx.images-amazon.com%2Fimages%2FI%2F41MpzoPshAL.SX300.jpg&products_array%5B3%5D%5Bbrand%5D=Chikorita&products_array%5B3%5D%5Bprice%5D=20&products_array%5B4%5D%5Bitem%5D=http%3A%2F%2Fecx.images-amazon.com%2Fimages%2FI%2F51BIJR%252BIqDL.SX355.jpg&products_array%5B4%5D%5Bbrand%5D=Mudkip&products_array%5B4%5D%5Bprice%5D=20&quantity%5B0%5D=0&quantity%5B1%5D=0&quantity%5B2%5D=0&quantity%5B3%5D=03&quantity%5B4%5D=0
which is a stupid amount of information to pass in a string (just testing stuff out), sorry, but it's all the information from the two arrays I needed.
Edit2:
I managed to fix it, I didn't give you guys enough info sorry. The problem was actually that I did not set the form action of my pages to preserve the data string, so it kept getting lost as I was processing the form. Thanks for all the advice, I'll be sure to try it out next time, especially sessions.
Using only PHP
To encode the data
$products = "some product";
$qtd = 1;
$array = array('products_array' => $products, 'quantity' => $qtd);
$json_str = json_encode($array);
echo $json_str;
header('Location: registration.php?' . $qstr);
To decode the data
$data = json_decode($post_data); //to decode the string into an object
echo $data->products_array . "\r\n";
echo $data->quantity . "\r\n";
How can I get a value of a second level JSON node using PHP from a Ajax request?
If I have the next JSON data in client:
var Data = {idJS: "1", dataToSet: "example", another:{ field1: "example2"} };
When the Ajax request is done, in PHP, dataToSet is get as follows: $_POST['dataToSet'], in particular, I use Codeigniter, then I use $this->input->post('dataToSet'). But, How can I get another->field1?
[Solved]:
$postdata = $this->input->post();
$postdata['another']['field1'];
I don't know how you do it with codeigniter, but you have to decode the json. Afterwards you can acces the field. This might look something like this:
$postdata = json_decode($this->input->post);
$postdata['another']['field1];
This should do it:
$data = $this->input->post('another');
print_r($data->field1);
// or you can do it in one line:
$this->input->post('another')->field1;
Try this:
$ata = json_decode($this->input->post('dataToSet'), true);
$field1 = $data['another']['field1'];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there something like serialize/unserialize PHP functions in jQuery?
These functions return a string representations of an array or an object which can than be decoded back into array/object.
http://sk2.php.net/serialize
jQuery's serialize/serializeArray only works for form elements. I think you're looking for something more generic like this:
http://code.google.com/p/jquery-json/
This plugin makes it simple to convert to and from JSON:
var thing = {plugin: 'jquery-json', version: 2.2};
var encoded = $.toJSON(thing);
//'{"plugin":"jquery-json","version":2.2}'
var name = $.evalJSON(encoded).plugin;
//"jquery-json"
var version = $.evalJSON(encoded).version;
// 2.2
Most people asked me why I would want
to do such a thing, which boggles my
mind. Javascript makes it relatively
easy to convert from JSON, thanks to
eval(), but converting to JSON is
supposedly an edge requirement.
This plugin exposes four new functions
onto the $, or jQuery object:
toJSON: Serializes a javascript object, number, string, or arry into JSON.
evalJSON: Converts from JSON to Javascript, quickly, and is trivial.
secureEvalJSON: Converts from JSON to Javascript, but does so while checking to see if the source is actually JSON, and not with other Javascript statements thrown in.
quoteString: Places quotes around a string, and inteligently escapes any quote, backslash, or control characters.
Why, yes: jQuery's serialize. To unserialize, you'd have to code a function yourself, esentially splitting the string at the &'s and then the ='s.
I was trying to serialize a form and then save it, and when the user returned to the form unserialize it and repopulate the data. Turns out there is a pretty sweet jQuery plugin for doing this already: jQuery autosave. Maybe this will help out some of you.
I personally like Chris' unserialize function for handling jQuery's serialized strings, however, don't forget to also urldecode() them on the server-side as data such as 'email' => 'me%40domain.com' will be coming in if you use the function as-is.
Updated:
function _unserializeJQuery($rubble = NULL) {
$bricks = explode('&', $rubble);
foreach ($bricks as $key => $value) {
$walls = preg_split('/=/', $value);
$built[urldecode($walls[0])] = urldecode($walls[1]);
}
return $built;
}
You should use the native JSON library. For IE less than 8, you'll also need to use Crockford's JSON.js.
Follow the variable "formdata" and look at the supporting code to see how I got this to work in a wordpress environment.
I'm using this on the client side (js):
// bind button, setup and call .ajax
jQuery('#submitbutton').click(function() {
jQuery('#response_area').html('');
// put all name-values from form into one long string
var serializedformdata = jQuery('#submitform').serialize();
// configure array of options for the ajax call (can use a different action for each form)
options = {
type: 'POST',
url: sv_submitform_global_js_vars.ajaxurl,
datatype: 'json',
data: {
clienttime: getnow(),
sv_submit_form_check: jQuery('#sv_submit_form_check').val(),
// this data:action:'value' is specifically required by the wordpress wp_ajax_<value> action hook to process the received data on the php/server side
action: 'sv_submitform_hook',
formdata: serializedformdata,
},
beforeSend: beforesendfunc,
// process returned json formatted data in function named below
success: successfunc,
}
// execute the ajax call to server (sending data)
jQuery.ajax(options);
});
... and this on the server side (PHP) to get the data back out and into a nice associative array for server side database work.
/////////////////////////////////////
// ajax serverside data handler ///
/////////////////////////////////////
// Add AJAX actions for submit form
// Serves logged in users
add_action( 'wp_ajax_sv_submitform_hook', 'sv_submitform_handler' );
// Serves non-logged in users
add_action( 'wp_ajax_nopriv_sv_submitform_hook', 'sv_submitform_handler' );
// this is the function that processes the input from the submit form
function sv_submitform_handler(){
date_default_timezone_set('EST');
$servertime = date('h:i:s a').' Server Time';
// fda = form data array can be used anywhere after the next statement.
// example: if ($fda['formfieldbyname'] == 'something'){...};
parse_str($_POST['formdata'],$fda);
// this is how the nonce value is read
// form side is wp_nonce_field('sv_submitform','sv_submitform_check');
if (!check_ajax_referer('sv_submitform', 'sv_submitform_check', false )){
$data = $servertime . ' (Security Failed)';
} else {
$data = $servertime . ' (Security Passed)';
};
$returndata = array('data' => $data);
exit(json_encode($returndata));
};
And for the WordPress coders out there, it took me a while to realize that the wp_ajax_ hook had to be in either a plugin file or my child theme's functions.php. It will not work in a normal page template!
As of version 1.4.1 of jQuery there is a jQuery.parseJSON() function built in.
http://api.jquery.com/jQuery.parseJSON/
I had the same problem recently, I was using jQuery's .serializeArray() to post form data for validation via an AJAX call. On the server side I needed to split this object down into an associative array that would replicate the original $_POST data structure, so I wrote this little function:
function unserializeMe($obj) {
$data = array();
foreach($obj as $arr) {
$data[$arr['name']] = $arr['value'];
}
return $data;
}
Then all you have to do is cast the input object to an array type before passing it in the funciton call:
$objData = (array) $_POST['data'];
$data = unserializeMe($objData);
Use function parse_str.
$array = array();
$string = "title=Hello&desc=World=&s[]=5&s[]=6&s[]=7";
parse_str($string, $array);
description on php.net
I also wrote a function to parse the jQuery .serialize() function:
function createArray($rubble) {
$bricks = explode('&', $rubble);
foreach($bricks as $key => $value) {
$walls = preg_split('/=/', $value);
$built[$walls[0]] = $walls[1];
}
return $built;
}