Accessing POST data - php

I'm very new to PHP but have a good understanding of C,
When I want to access some post data on an API i'm creating in PHP I use:
$_POST['date_set']
to fetch a value being passed for date - This all works perfectly, however I read I should be fetching it like this:
$date_set = trim(urldecode($_POST['date_set']));
This always returns a 00:00:00 value for the date after it's stored in my DB.
When I access directly using $_POST['date_set'] I get whatever value was posted, for example: 2013-08-28 10:31:03
Can someone tell me what I'm messing up?

You should try it like,
$date_set = $_POST['date_set'].explode(' ');//('2013-08-28 10:31:03').explode(' ')
echo $date_set[1];
or
echo date('H:i:s',strtotime($_POST['date_set'])));
//echo date('H:i:s',strtotime('2013-08-28 10:31:03'));
If you are very new in php the Read date()

You only run urldecode over data is URL encoded. PHP will have decoded it before populating $_POST, so you certainly shouldn't be using that. (You might have to if you are dealing with double-encoded data, but the right solution there should be to not double encode the data).
trim removes leading and trailing white-space. It is useful if you have a free form input in which rogue spaces might be typed. You will need to do further sanity checking afterwards.

urldecode — Decodes URL-encoded string
Description
string urldecode ( string $str )
Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.
urldecode: is used only for GET requests. you should be fine using $_POST['date_set'] only.
http://php.net/manual/en/function.urldecode.php

You'd better do this way
if(isset($_POST['date_set'])){
$date_set = $_POST['date_set'];
}
then you can use $date_set how you want.
If you still get 00:00:00 for $date_set, the problem is coming from the code which provide you the $_POST value.

Related

Convert non-alphanumeric characters to unicode codes

I receive a token in this format :
{"signature": "MEQCIFf4uQXQYR6fA48cHZMwR5K0bO/wsK5ygoCukmAfWslIAiAdc4kN1BEixxrreSI3W3x4a92+fFTw7/Ulqw9RuJPRzg\u003d\u003d","protocolVersion": "ECv1", "signedMessage": "{\"encryptedMessage\":\"HKdqg8pDCiAwaHmGeI+/7xIDXXCTSfK+/SERLh94NBX6l99w7vNgBenMCiaAGvO+nbHkmnaOnwMcq/DpRhFtCJuYjAGKA83UePYjleSgXp8AjTKUweXxpqNEVvexSeflHBQNcx4stvB7lhsCeW9SMhecebfkcgQyGlawBECXrsIWhfIRGHklC6KE18tlA0GfvsQLhKreWspHCxQjgiBDim6uR57aKzTzlTFGYK+IB1mMJbVFTrEeBnKOAlvdt8Nh4BH3DhrmV3HVl+Ydc9V2G6iGZ6EmPxe3QG5dC9aYGollEXieasTFZm1Bt/LQMdyHmQEd+cmdIQNfGhxzz5pWpLP9g8LuoG+8h69TYaVFY2o0FjP2vSuPqGhMlXhcWgb/gJsiAOLGkS2ZdFbhpQg3kEyS5f/h91Wuoxy08JHpFxsvzWL3skfJ5eQc/BykvHyzzxzK\",\"ephemeralPublicKey\":\"BFnxpfpfIeFLmJ/KM/GcQyhU0MBlEReejnKa71gKFnV+5N2t3WNBnaaNu02gjy7Z5d07XO5+O77Qx3abHnw5rwk\\u003d\",\"tag\":\"kbnLkGZKyDKBWQAh6AyCNL55V4SF8DiZ4PeIudtKBH0\\u003d\"}"}
I need to json_decode it, do something with it then push it back. If I json_decode it, I will get the \u003d character decoded to =, which is fine. But how do I encode it back ? I think I played with every possible conversion function in PHP and I'm fresh out of ideas.
Here's a sandbox to play around with : http://sandbox.onlinephpfunctions.com/code/b93defec84a9a6f22f5085fbb7628b5afa816d95
In normal work you do not need to encode = to \u003d but if you must use somthing like this:
$encoded = str_replace('=','\\u003d', $encoded);
Note about your sandbox example:
In your example the token variable signedMessage is json in json
but after changes return as single json and not json in json like before changes.
maybe its fine for your application but check it

how to remove backslashes in json URL with php

i need to remove () backslash in my string when using echo json_encode()?
my example..
$song_url = 116e9155e0afc11555cf33dc9c9bd25d.mp3
$resmsg[] = array("Song_name"=>"$song_name","Song_URL"=>"http://www.kbmusique.com/songs/$song_url");
echo json_encode($resmsg);
my output is
[{"Song_name":"djigh araouioui","Song_URL":"http:\/\/www.kbmusique.com\/songs\/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
but i need as
[{"Song_name":"djigh araouioui","Song_URL":"http://www.kbmusique.com/songs/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
Is there a way to solve this? Thank you.
Your comment indicates that you just need to get a copy/pastable URL for testing.
Just parse the JSON and extract the piece of data you need from it. i.e. If you want a text representation of something, then convert the JSON to text, don't try to hack the JSON into a specific form.
You could do this in PHP with json_decode, in a browser with JSON.parse(), or just use a tool such as the Chrome JSONView extension.

PHP json_decode returns null

I'm writing PHP code that uses a database. To do so, I use an array as a hash-map.
Every time content is added or removed from my DB, I save it to file.
I'm forced by my DB structure to use this method and can't use mysql or any other standard DB (School project, so structure stays as is).
I built two functions:
function saveDB($db){
$json_db = json_encode($db);
file_put_contents("wordsDB.json", $json_db);
} // saveDB
function loadDB(){
$json_db = file_get_contents("wordsDB.json");
return json_decode($json_db, true);
} // loadDB
When echo-ing the string I get after the encoding or after loading from file, I get a valid json (Tested it on a json viewer) Whenever I try to decode the string using json_decode(), I get null (Tested it with var_dump()).
The json string itself is very long (~200,000 characters, and that's just for testing).
I tried the following:
Replacing single/double-quotes with double/single-quotes (Without any backslashes, with one backslash and three backslashes. And any combination I could think of with a different number of backslashes in the original and replaced string), both manually and using str_replace().
Adding quotes before and after the json string.
Changing the page's encoding.
Decoding without saving to file (Right after encoding).
Checked for slashes and backslashes. None to be found.
Tried addslashes().
Tried using various "Escape String" variants.
json_last_error() doesn't work. I get no error number (Get null, not 0).
It's not my server, so I'm not sure what PHP version is used, and I can't upgrade/downgrade/install anything.
I believe the size has something to do with it, because small strings seem to work fine.
Thanks Everybody :)
In your JSON file change null to "null" and it will solve the problem.
Check if your file is UTF8 encoded. json_decode works with UTF8 encoded data only.
EDIT:
After I saw uploaded JSON data, I did some digging and found that there are 'null' key. Search for:
"exceeding":{"S01E01.html":{"2217":1}},null:{"S01E01.html":
Change that null to be valid property name and json_decode will do the job.
I had a similar problem last week. my json was valid according to jsonlint.com.
My json string contained a # and a & and those two made json_decode fail and return null.
by using var_dump(json_decode($myvar)) which stops right where it fails I managed to figure out where the problem was coming from.
I suggest var_dumping and using find dunction to look for these king of characters.
Just on the off chance.. and more for anyone hitting this thread rather than the OP's issue...I missed the following, someone had htmlentities($json) way above me in the call stack. Just ensure you haven't been bitten by the same and check the html source.
Kickself #124

json_decode + json_encode combo not creating original JSON

I have some JSON that I got through an API call, and I run json_decode on it, grab an array from it, then re-encode it with json_encode. The result however is not the same JSON; it's messing up with the URLs. How do I make it encode properly?
original
{"created_at":"Mon, 19 Mar 2012 01:34:41 +0000","entities":{"hashtags":[{"text":"stanford","indices":[23,32]}],"urls":[{"url":"http:\/\/t.co\/Of4z6jKG","expanded_url":"http:\/\/360.io\/5sZc2T","display_url":"360.io\/5sZc2T","indices":[33,53]}],"user_mentions":[]},"from_user":"rayfk","from_user_id":335143881,"from_user_id_str":"335143881","from_user_name":"Raymond Kennedy","geo":{"coordinates":[37.4227,-122.1753],"type":"Point"},"id":181554251733020673,"id_str":"181554251733020673","iso_language_code":"en","metadata":{"result_type":"recent"},"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>","text":"View from mid lake log #stanford http:\/\/t.co\/Of4z6jKG","to_user":null,"to_user_id":null,"to_user_id_str":null,"to_user_name":null}
after decode/encode combo
{"created_at":"Mon, 19 Mar 2012 01:34:41 +0000","entities":{"hashtags":[{"text":"stanford","indices":[23,32]}],"urls":[{"url":"http:\/\/t.co\/Of4z6jKG","expanded_url":"http:\/\/360.io\/5sZc2T","display_url":"360.io\/5sZc2T","indices":[33,53]}],"user_mentions":[]},"from_user":"rayfk","from_user_id":335143881,"from_user_id_str":"335143881","from_user_name":"Raymond Kennedy","geo":{"coordinates":[37.4227,-122.1753],"type":"Point"},"id":181554251733020673,"id_str":"181554251733020673","iso_language_code":"en","metadata":{"result_type":"recent"},"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>","text":"View from mid lake log #stanford http:\/\/t.co\/Of4z6jKG","to_user":null,"to_user_id":null,"to_user_id_str":null,"to_user_name":null}
Those are the full snippets, but the culprit is this:
original "source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>"
after "source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>"
I'm not sure what is causing it but you can correct it by applying the html_entity_decode() function to the after version. This will change things such as < or " back to their original form.
Depending on how it affects your quoting, there are a few flags you can pass it as well to get the result you need.
ENT_COMPAT: Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES: Will convert both double and single quotes.
ENT_NOQUOTES: Will leave both double and single quotes unconverted.
[EDIT]
Run your broken JSON through this function:
function fixDoubleQuotedJSON($broken_json)
{
return str_replace('"','\\"',$broken_json);
}
http://codepad.org/DMkAS2iR
They seem to be equal, except at an unexcepted place:
before: "id":181554251733020673,"id_str"
after: "id":181554251733020000,"id_str"
Those id's won't really match after "lossless" json transforms, and JSON_BIGINT_AS_STRING option is supported from PHP 5.4.
Codepad's php version is 5.2.5 by the way;

Insert special characters to a string for web address (PHP question)

I posted this question last week, but I wasn't very clear on what was needed. So I'm reposting right now.
I have a string stored in a database, which looks something like this:
<5u79cfda 4d01ga3a 11c833f9 7b52df2a 7g210252 e21b01fa a73d3463 9ge0e412>
I'm trying to insert this into a web address, but needs to be encoded properly for it to work. I'm running a query to obtain the script:
$result = mysql_query("SELECT cPushID FROM tblUsers WHERE intUserID='20' AND Length(cPushID) > 70");
$pid = mysql_fetch_row($result);
Then trying to insert it into this web address to be executed:
file_get_contents("http://domain/test.php?msg='Test!'&to=$pid");
How do I properly insert this string into the web address so it will be read properly upon execution.
Thanks for your help.
Use urlencode.
How about urlencode?
$encoded = urlencode($some_string");
Pass that encoded string to file_get_contents
If you ever need to decode it, use urldecode()
http://php.net/manual/en/function.urlencode.php
You need to urlencode() your query string in order to safely encode those spaces (and possible angle brackets as well?!)
file_get_contents("http://domain/test.php?msg='Test!'&to=".urlencode($pid));
The query string is automatically decoded when you read $_GET['pid']

Categories