inserting php session id into database from php://input callback - php

i have a callback page, that i am using to insert data in a db. when i load this page. and echo $_SESSION['user_id']. it echos the user_id, and inserts it into the db. however when i am trying to insert the data while doing the callback function, the $_SESSSION['user_id'] is ignored and the other data is succesfully inserted. why is this?
echo $_SESSION['user_id'];
$decodedJSON = json_decode(file_get_contents('php://input'), true);
$account = $decodedJSON['account'];
$query_insert = "insert into video (account,userid) values ($account,$_SESSION['user_id'])";
$result_insert = mysql_query($query_insert);
When i refresh the page, $_SESSION['user_id'] is inserted. But when i try to run the callback function, $account is inserted, but $_SESSION['user_id'] is not.

I'm not 100% sure of how this all fits together with your code sample, but if you're trying to pass somethign to stanard input and then run the PHP, you also need to pass the sessionID.
When you call the code from your borwser, cookies magically handle all that for you, and the sessions ID is passed in a cookie. But if you're calling from another source, cookies are not passed.
I could explain how to do it, but nothing better than the PHP manual: http://php.net/manual/en/session.idpassing.php - basically append the SID to the end of hte URL.
But note the comment about "session.use_trans_sid" which is disabled by default and needs to be enabled in php.ini

Related

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.

Custom session save_handler overwerites current saved data in database

So I finally managed to save some session data in to the database.
Now a new problem arises. When I load the page once all data is being saved.
When I reload the page and I write something to the session all data that's already in the session is being replaced with this new data. This means that with each load all the data is being replaced for new data. This is giving me problems because I'm saving a order_id into the session when there is no order_id present in the session.
This is the code that writes the data into the database. And yes it says replace into. But because this is a custom handler how can i actually append data to this current session with out renewing everything. Also how can I replace old data for new data witch is already present in the session.
The code that handles the writing to the database.
function _write($id, $data) {
$access = time();
$id = $this->session_db->real_escape_string($id);
$access = $this->session_db->real_escape_string($access);
$data = $this->session_db->real_escape_string($data);
$sql = "REPLACE INTO sessions VALUES ('$id', '$access', '$data')";
return $this->session_db->query($sql);
}
Is there something that i can do to put all the data directly after session_start() in the session variable so it always has all the data and doesn't overwrite the data with a single value when I do something like:
$_SESSION['LAST_ACTIVITY'] = time(); ?
EDIT: Also when I try to echo the session directly after the session_start();
It gives me there error
Warning: session_start(): Failed to decode session object. Session has been destroyed in /var/www/vhosts/url/httpdocs/index.php on line 13
Is there something wrong with the serialized string I don't understand why it is giving me this error.
Thanks in advance, some help will be appreciated.
Ok so now everything is working. I kinda feel embarrassed for saying what the problem was. So ok the problem and the solution.
The problem was that the session serialized data was way to long for a regular text field in the database. My string was over 500.000 characters long regular text field in database supports until 65.000+ characters.
So I changed the field from "TEXT" to "LONGTEXT" now it has enough space to save the string. And now everything works properly.
Everybody thanks for your time so far.

php GET requests and their subsequent use as a variable (in an SQL confdition)

I have successfully extracted the correct data from my database during testing (its just a prototype - so yes I know its not secure SQL). The test SQL is
$sql=
SELECT *
FROM jobcards
WHERE jobnumber='$jobnumber'
";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{loop}
The issue is the source of the data to which $jobnumber is set.
If during testing I set $jobnumber to the string Agen912-491 (implicitly) I get out of the database exactly what I should get out. However here is the problem.
I am clicking from a link on another page. The link creates the URL:-
domain.php/jobcard.php?jobnumber=%20Agen912-491
which take me to the page on which the SQL query (and the output) resides. So on the page I set
$jobnumber = $_GET["jobnumber"];
echo $jobnumber;//testing
to request (and test) the jobnumber (passed from the link) that I need to insert into the WHERE condition. As expected the echo correctly returns Agen912-491. So exactly the same string (it seems) as the implicit value used succesfully in testing. All good so far.
However when I then set $jobnumber= $_GET["jobnumber"]; the database query fails to find any records. [In desperation I fudged the process so that the variable $jobnumber = $_SESSION ["jobnumber"]; (and ensured via an echo that $_session[] gave me Agent912-491). Now the database correctly returns the record again!
So for some reason the $GET["jobnumber"]; statement when set to $jobnumber is failing [even though when it is echoed it returns the correct value that works implicity (and when set it via $s[session]. So there is clearly an issue with a) requesting $_GET["jobnumber"]; b) setting it to the $jobnumber and then c) using that in the WHERE statement. Everything else works as does setting $jobnumber implicitly or via $_session.
I have an incline it might be something to do with santitising the $_GET result before using it. But that really is a guess and even if correct I dont know what exactly to try out.
Help would be really appreciated. Many thanks.

Ajax - security breach? - PHP

I build a system in php, i have page name x.php
and in this page i create variable name $accountid and get the acocunt id from the sesstion.
now i have others varibles in php at the same page that calls to functions that in other page called functions.php, and deliver the accountid, the function return info about the account (for example the name of the user..)
is this security breach?
i mean the user can call in ajax to the function with other accountid and then he can get info about other account?
here is the code example:
<?php
include "Includs/Config.php";
if(!isset($_SESSION[get("session_name")])) {
header("Location: index.php");
}
$accountid = getAccountid($_SESSION[get("session_name")]);
$e = getECategorys($accountid);
?>
function getE($accountId){
$query = mysql_query("SELECT * FROM `x` WHERE `accountid` = $accountId");
while($result = mysql_fetch_assoc($query)){
// get the info about the account..
}
}
Yes you are right. User can get information by passing another accountId to that function.
Solution: All you can do is check session variable and passed accountId. You can put condition, If session variable (accountId) is matched with passed accountId to that function then only retrieve data otherwise gives an error.
Second solution is to achieve this thing with class base, setting private member variable of accountId.
Hope this helps.
I'm not sure, it seems you are getting accountId from the $_SESSION so this seems to be safe.
Also, users can't call php functions directly using ajax.
Actually, you shouldn't consider AJAX as something else than a simple HTTP request.

PHP $GET variable works with one value but not with another. why?

I am trying to retrieve user inputs from a previous page using the URL. I have the following code on the previous page which sends the username and account status via the URL.
header("location: pagename.php?user=$username&status=$status");
On 'pagename.php' I have the following code which stores the values in local variables and echos them for my benefit.
if(isset($_GET['user'], $_GET['status'])){
$user = mysqli_real_escape_string($con, $_GET['user']);
$status = mysqli_real_escape_string($con, $_GET['status']);
echo $user.' - '. $status;
}
While, elswhere, this method works perfectly for retrieving 5 values form the URL, on this occasion I am failing to retrieve the status and it echoes the following 'username - ' You can see an image of the output for better understanding. I would much appreciate your assistance in helping me retrieve the status from the URL using PHP.
http://www.awesomescreenshot.com/image/378892/c50c452d8597f2ac29970a6a21bfcc62
Having tried var_dump($_GET) I get the following result:
I just realised that the issue lied with the naming of the variable $status, which incidentally happened to be the same name used in my login session and because I was not logged in it did not get the account status. I fixed the issue by simply renaming the variable.

Categories