Php - Post variable values' part at specific index is missing - php

I'm making a POST request to my application with a long stringified JSON like below:
/////POST PARAMETER VALUE
{"objects":[{"type":"path","originX":"center","originY":"center","left":118.63,"top":252.5,"width":41,"height":139,"fill":null,"overlayFill":null,"stroke":{"source":"function anonymous() {var patternCanvas = fabric.document.createElement('canvas');patternCanvas.width = patternCanvas.height = 10;var ctx = patternCanvas.getContext('2d');ctx.stroke`Style = quotesquare005E7Aquote;ctx.lineWidth` = 5;ctx.beginPath();ctx.moveTo(5, 0);ctx.lineTo(5, 10);ctx.closePath();ctx.stroke(); return patternCanvas;}","repeat":"repeat","offsetX":0,"offsetY":0},"strokeWidth":15,"strokeDashArray":null,"strokeLineCap":"round","strokeLineJoin":"round","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"selectable":true,"hasControls":true,"hasBorders":true,"hasRotatingPoint":true,"transparentCorners":true,"perPixelTargetFind":false,"shadow":null,"visible":true,"clipTo":null,"path":[["M",40.5,0],["Q",40.5,0,41,0],["Q",41.5,0,41.25,2],["Q",41,4,38,16.5],["Q",35,29,29.5,42],["Q",24,55,21,65],["Q",18,75,15.5,83.5],["Q",13,92,9.5,101.5],["Q",6,111,4.5,118],["Q",3,125,2,128],["Q",1,131,0.5,134],["Q",0,137,0,138],["L",0,139]],"pathOffset":{"x":0,"y":0}}],"background":""}
////// END
Every time i do this request, value comes missing. In the server the part that i highlighted is lost. I realised that it's a specific index range at the string. When i give another data in this json stringified format, it looses again the part in that index range. And i'm sure that i'm sending the value complete because i checked it at the request headers.
The problem is not about my code because i tested it with POSTMAN app and the result is same.
Anyone can help about this misterious situation. Is there anything in this value which causes some escaping. And i'm using Codeigniter.
Thanks

Related

How to get the value from an array in ionic?

I have created a php file.
Response from php-
response:"{"status":true,"originalName":"1527931554722.png","generatedName":"ceabe4c3b0074eb3d64cca21493be324.png"}"
I want to get the value of generatedName in ionic.
I used this code:->
let name = response[3]; console.log(name);
It gives output 't' on console.
response:"{"status":true,"originalName":"1527931554722.png","generatedName":"ceabe4c3b0074eb3d64cca21493be324.png"}"
try response.generatedName
You do not need index here, just access the property since its already an object.
DEMO
let response = {"status":true,"originalName":"1527931554722.png","generatedName":"ceabe4c3b0074eb3d64cca21493be324.png"};
console.log(response.generatedName);

Get values through post method from URL

I am trying some code to get value from URL through post method and search database table for that value and get info from the database and encode it into JSON response.
Here is my code :
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","json") or die("Error " . mysqli_error($connection));
if (isset($_POST['empid'])) {
$k = $_POST['empid'];
//fetch table rows from mysql db
$sql = "select `salary` from tbl_employee where `employee_id` = $k ";
} else {
//fetch table rows from mysql db
$sql = "select `salary` from tbl_employee";
}
//fetch table rows from mysql db
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
I used Postman extension on Chrome and pass the values but it is not returning. Instead it is returning the else part.
Postman Screenshot
Looking at your screen shot, you have not passed body key values, instead you passed params.
Click on Body Tab and then pass key & value pair.
As per your screenshot you are sending your empid through query parameter so you need to access that as follows
<?php
if (isset($_GET['empid'])) {
echo $_GET['empid'];
}else{
// else part
}
also for that you need to Request Url in Postman using GET method.
But as you have stated that you want to send empid through POST in postman, you have to send it through form-data in Postman and access it as $_POST["empid"];. following is the screenshot for your reference
else there is another option where you can send the POST data through body as row json and access it as
$rawPostData = file_get_contents('php://input');
$jsonData = json_decode($rawPostData);
and $post will contain the raw data. And you can send it through postman as in following screenshot.
You have to set the Body to "x-www-form-urlencoded" and adding the variables to be posted
Or try this SO question, its already been answered
I replicated the code and db on my system to figure out the problem. I also added some lines of code before if (isset($_POST['empid'])) { for diagnostics sake:
$method = $_SERVER['REQUEST_METHOD'];
echo $method."<br/>";
The application file is index.php deployed in json directory inside webroot.
When I send any request to http://localhost/json directory (either POST/GET), Apache redirects the request as a GET request to index.php (as configured in my Apache config file). I assume this is what you're experiencing.
But when I send the request to http://localhost/json/index.php, the request is accurately received and processed.
Therefore, I would say the solution is that you need to specify the php file and also set the empid parameter as part of the body in Postman (not as part of the url).
I think you should also check the post if emptyif (isset($_POST['empid']) AND ($_POST['empid']) != ""). to allow php to execute the line before else.Sometimes programming becomes unpredictable.
use if(isset($_REQUEST['empid'])) to test in POSTMAN...
Then use if(isset($_POST['empid'])) to test directly from app...
have a look Issue in POSTMAN https://github.com/postmanlabs/postman-app-support/issues/391
To get the value of a variable from the URL(query string), you need to use either $_GET or $_REQUEST.$_POST represents data that is sent to the script via the HTTP POST method.
So, in your code you just need to do this :
$_REQUEST['empid'] instead of $_POST['empid']
In POST method the data is sent to the server as a package in a separate communication with the processing script. Data sent through POST method will not visible in the URL.
Confirm that in postman Content-Type should be application/x-www-form-urlencoded in request header.
Postman reference doc : https://www.getpostman.com/docs/requests
Hey it sounds like you are just needing to do a GET request to your DB.
You are more than welcome to send in variables via a GET request as well.
GET http://localhost/json?empid=3
You can then get data from your GET request like so $_GET['empid']
I suggest a GET request because I see your not actually posting any data to your server, your just handing in a variable in which you want to use to query with.
I do understand that GET requests are less secure, but in your scenario your POST just doesn't seem to want to work. So a different tack might do you justice.
If you want a value from the URL, you need to use $_GET["empid"] instead $_POST["empid"]
Submitting a form through POST method
By post method of form submission, we can send number or length of data. Sensitive information like password does not get exposed in URL by POST method, so our login forms we should use POST method to submit data. This is how we collect data submitted by POST method in PHP
$id=$_POST['id'];
$password=$_POST['password'];
Collecting data submitted by either GET or POST method
If a page is receiving a data which can come in any one of the method GET or POST then how to collect it ? Here we are not sure how to collect the data. So we will use like this.
$id=$_REQUEST['id'];
$password=$_REQUEST['password'];
Looking at the URL you are requesting, you are sending a GET value within your POST request.
http://localhost/json?empid=3
As you can see here, the url holds the empid variable and so the is send to the server as beeing a GET variable ($_GET)
Use $_GET['empid'] to access this variable, while using $_POST to access the other variables.
You could also use $_REQUEST to access both GET and POST data by the same global.

pass a value from one page to another outside querystring and without javascript?

One solution to automatically building navigation for a site is by scanning a folder for documents like this:
foreach(glob('pages/*.pg.php') as $_SITE_NAV_filePath):
$_SITE_NAV_filePath = explode('.pg',pathinfo($_SITE_NAV_filePath,PATHINFO_FILENAME));
$_SITE_NAV_fileName = $_SITE_NAV_filePath[0];
$_SITE_NAV_qv = preg_replace('/([A-Z])/','-$1',$_SITE_NAV_fileName); $_SITE_NAV_qv = trim($_SITE_NAV_qv,'-');
$_SITE_NAV_name = preg_replace('/([A-Z])/',' $1',$_SITE_NAV_fileName);
?>
<li><?=$_SITE_NAV_name?></li>
<?php
endforeach;
This code will turn "AnAwesomePage.pg.php" into a menu item like this :
<li>An Awesome Page</li>
This might be bad practice (?).
Anyway; I don't use this method very often since most of the time the sites have a database, and with that comes better solutions...
But my question is this:
Is there a way to prefix the filename with a integer followed by and underscore (3_AnAwesomePage.pg.php), for sorting order purposes, and pass it somehow to the destination page outside of the querystring and without any async javascript?
I could just explode the filename once again on "_" to get the sort order and store it somewhere, somehow?
This is the code for handeling the page query request:
$_SITE_PAGE['qv'] = $_GET['page'];
if (empty($_SITE_PAGE['qv'])){ $_SITE_PAGE['qv'] = explode('-','Home'); }
else { $_SITE_PAGE['qv'] = explode('-',$_GET['page']); }
$_SITE_PAGE['file'] = 'pages/'.implode($_SITE_PAGE['qv']).'.pg.php';
This code turns "An-Awesome-Page" back into "AnAwesomePage.pg.php" so it's possible to include it with php.
But with a prefix, it's not so easy.
The probliem is; Now there's no way to know what prefix number there was before since it has been stripped away from the query string. So I need to send it somehow along in the "background".
One very bad solution I came up with was to transform the navigation link into a form button and just _POST the prefix interger along with the form. At fist it sounded like a nice solution, but then I realized that once a user refreshes their page, it didn't look very good. And after all, that's not what forms are for either...
Any good solutions out there?
Or some other and better way for dealing with this?
There are two ways to keep that number saved, you can use cookies or php session variables.
But in this case, if user first enter the url in the browser or in a new browser, then he should be taken to default number.
Like you have:
1_first-page.php
2_first-page.php
3_first-page.php
If user enter the url like: domain.com/?page=first-page, you have to take him to 1_first-page.php to any number which you want to be default.

mysql LAST_INSERT_ID() is causing some SQL problems when passing back value retrieved

I need some help figuring out why the following scenario does not work. I'm trying to retrieve a value from the last updated ID in mysql, then pass that value via javascript over to an ajax call which calls a .php page, which also calls another function "ZEND_emaiL" in a different php page.
In the very first php page that retrieves the id from mysql LAST_INSERT_ID(), if I hard code the value "100" it works, but if I use the value returned from LAST_INSERT_ID() it causes a failure.
Here's the php code for the LAST_INSERT_ID():
$sql='SELECT LAST_INSERT_ID();';
$last_updated_id = $db->get_var( $sql );
$last_updated_id = $last_updated_id+0;//make int
echo $last_updated_id; //send output back to the ajax call
var_dump($last_updated_id); ------------->RETURNS **int 149**
if I send back a hard coded "100" like this: echo 100; then it works.
Any ideas? Thanks for your help in advance.
The following are values retrieved from the php page that contains the ZEND_email() function. I grabbed these for debugging purposes hoping it would help.
RETURN VALUES for Hard Coded:
var_dump($n_id);---------->Returns **int 100**
var_dump($sqlresult);----->Returns **resource 24**
var_dump($row);----------->Returns **array of data to parse through**
RETURN VALUES FOR Passed in Variable (Fails):
function ZEND_email($to, $from="", $subject="", $msg="", $notif_id='', $root_dir="")
{
var_dump($notif_id);---------------------->RETURNS **string '100'**
$notif_id = $notif_id+0;//convert to int
var_dump($notif_id);---------------------->RETURNS **int 100**
$n_id = $notif_id;
$xsql = $sql_str->SQL_SELECT_all_notif_attachments($account_id, $n_id);
$sqlresult=mysql_query($xsql);
$row=mysql_fetch_row($sqlresult);
var_dump($n_id);---------------->RETURNS **int 100**
var_dump($sqlresult);----------->RETURNS **resource 24**
var_dump($row);----------------->RETURNS **boolean false**
}
you are aware that you could use mysql_insert_id() ?
see http://uk.php.net/manual/en/function.mysql-insert-id.php which would give you an INT value directly,
btw, to convert a variable to integer you can use:
$foo = (int) $bar
or
$foo = intval($bar);
or
$foo = settype($bar,'int');
Hard to tell from those code snippets. Better check what's going on on the client-side.
E.g. with firebug you can both check the actual response data and step into the javascript code.
Had to scrap this code...couldn't get it all to work with the feature for the app so we dropped it. Thanks for your help.

Reading JSON arrays with jQuery/JS

Alright, this pretty much goes along with my previous question. I'm still trying to figure out how to display data from an array which is created by a PHP file- using JS/jQuery. I'm working on a points system for ZetaBoards, and I've currently got it set up here. (Points will be displayed below the users post count once I get this working.. you guys can't see the +/- functions which work fine, haha. :p )
http://outlinetokens.hostei.com/scripts/output.php
So, for each user- I can get their user ID, I just don't know how to check if their name is in the array. (and if it is, display their points) I'm guessing I'll have to do something like this? Here's the chunk of the code that deals with this.. you'll see where I need help.
if (location.href.match('/topic/')) {
$.getScript('http://outlinetokens.hostei.com/scripts/output.php', function () {
$('td.c_username a.member').each(function () {
value = 0;
u = $(this).attr('href').split('profile/')[1].split('/')[0];
// this is where I need to do the 'search.' Just a basic guess.. help. D:
if (values.uid == u) {
value = values.points;
}
$(this).parents('tr').next().find('dl.user_info').append('<dt>' + options.system_name + ':</dt><dd class="Points"><span id="point_total">' + value + '</span></dd>');
});
})
}
...in case the code tag screwed it up:
http://ryjoe.pastebin.com/raw.php?i=0bsZNnVq`
Thanks! (:
Why are these lines in your data formatted like this:
{'uid','342230','name','Joe','points','250'}
instead of this:
{'uid': '342230', 'name': 'Joe', 'points','250'}
If that was formatted correctly you could access the properties.
I'm not sure if I'm reading your question right, but you can load JSON with jQuery, instead of a script.
If then, the array is one of usernames, you can just use response.hasOwnProperty(username) or similar to check if it's in the JSON object you got back
Also, in php use json_encode
You want JQuery.parseJSON. Load the data string, parse it, and assuming its valid JSON, it will become a JS object. Then just access the members in the usual way.

Categories