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.
Related
Im working with so called webhooks. What basically happens is. There's a process happening in the background and when that process finishes it will send a POST request to an URL that I have to specify. For example 'www.bla/process.php'.
The post request that is sent will have a body of data. My question is , is it possible to read the data that is sent and just print it out for example?
Yes
It is possible to pass info from one page to another and print it out for example.
There are many method's...
// THE SAME
echo $_POST['DATA1'];
echo ($_POST['DATA1']);
// THE SAME
// IF = DATA IS SET AND NOT EMPTY
if (isset($_POST['DATA1']) && !empty($_POST['DATA1'])) {
$DATA1 = $_POST['DATA1'];
}
echo($DATA1);
Hey I'm new to php need help creating anew page per user. I have a user login and registration system already. I also have a profiles.php page but, how can I let the website make an automatic webpage for every new user.
Whenever I try to connect it through $_GET or $_POST I get an Undefined index error.
include ("includes/profiles.dbh.inc.php");
$requested_user = $_POST['mailuid'];
try{
$stmt2 = $conn2->prepare("SELECT * FROM profile WHERE id = ?");
$stmt2->execute(array($requested_user));
$mydata = $stmt2->fetch();
} catch (Exception $e) {
//error with mysql
die();
}
I've seen this question come up a few times. One of the first things you need to consider is how is the user going to interact with this page.
Are they going to access it via links? http://example.com/index.php?user=1
Or are they going to submit a form via post? http://example.com/index.php
This distinction is important because it changes the way you handle their request.
Let's look at each one:
Via a link: http://example.com/index.php?user=1
This will issue a get request to your server so you need to handle it via $_GET.
if (isset($_GET['user'])) {
$userId = $_GET['user'];
// ... query your DB and output result
}
Via a form using post: http://example.com/index.php (body with contain "user=1").
This will issue a post request to your server so you need to handle it via $_POST
if (isset($_POST['user'])) {
$userId = $_POST['user'];
// ... query your DB and output result
}
On a side note, it is important to know that an HTML <form> can submit either a post or get request. You can control this via it's method attribute. If you don't specify the method attribute, then it defaults to get.
<form method="post">
...
</form>
<form method="get">
...
</form>
So, to answer your question. You're likely getting an undefined error because you're trying to access the post array using the key mailuid ($_POST['mailuid']) but that does not exist. It doesn't exist because:
you're receiving a get request and the post is empty OR
you are receiving a post request but it doesn't contain the key mailuid
To debug, go back to the basics - use $_GET
Change your code to use $_GET['mailuid'] and then make sure you access your page with the corresponding query string - ...?mailuid=1.
Finally, turn on error reporting - https://stackoverflow.com/a/5438125/296555. You should always do this and correct all errors and warnings.
I'm currently a front end developer for a website which lets users sign up and then make purchasing of items.For transactions, I'm using an API which the payment gateway company provided but when passing data via AJAX certain sensitive data are exposed for the users to see. I was wondering if there is a way that I can pass my parameters to a database (which I'm going to create), and then let the database do the AJAX posting so sensitive parameters can be hidden from the users. Also the database will store the response from the callback.
The ajax doesn't have to post to a database unless you want it to, but even then the database would not be what posts the data to a remote api. It's up to your backend php to do that.
Using jquery for the ajax call you would use something like:
$.getJSON("your_backend.php", function(result){
//whatever you want to do with the json returned from the remote site.
}
In your_backend.php:
<?php
$user = "user name";
$key = "key"
$headers = array(
'http'=>(
'method'=>'GET',
'header'=>'Content: type=application/json \r\n'.
'user:$user \r\n'.
'key:$key'
)
)
$context = stream_context_create($headers)
$url_returns = file_get_contents($api_url, false, $context);
echo $url_returns
?>
I haven't debugged this, so it won't work until you go through it, but it should give you an idea about how to proceed. Depending on how complex the connection is with the remote api you may need to use the cURL library for php instead of the file_get_contents.
If you want to save the information in your database you would write an insert statement from the backend php.
I'm trying to make a simple "request register app", so I send a variable $appUser_id via POST to a .php file that will make the storage into the database. I worked, for a while, but then it stopped working and I don't know what I changed. It makes the registration into the database but sets the appUser_id to 0, but I'm sending a number.
It doesn't throw any error but doesn't get the proper variable's value.
And sending the data with Postman for now.
newRequest.php
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
require 'connection.php';
makeRequestRegister();
}
function makeRequestRegister()
{
global $connect;
$appUser_id = $_POST["appUser_id"];
$query = "INSERT INTO requests (appUser_id) VALUES ('$appUser_id')";
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
Connection.php
<?php
define('hostname', 'localhost');
define('user', 'root');
define('password', 'password');
define('databaseName', 'belandri_TEII');
$connect = mysqli_connect(hostname, user, password, databaseName);
?>
Postman
DataBase
Pd: Forget about injection and that kind of protection. I don't care about that for now.
You're currently using the Headers tab but, you should be using Body tab for POST data.
Check out the following example:
If you check out the Postman documentation, you'll see there's several ways to construct the Request Body:
form-data
multipart/form-data is the default encoding a web form uses to transfer data. This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.
urlencoded
This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.
raw
A raw request can contain anything. Postman doesn't touch the string entered in the raw editor except replacing environment variables. Whatever you put in the text area gets sent with the request. The raw editor lets you set the formatting type along with the correct header that you should send with the raw body. You can set the Content-Type header manually as well. Normally, you would be sending XML or JSON data here.
binary
binary data allows you to send things which you can not enter in Postman. For example, image, audio or video files. You can send text files as well. As mentioned earlier in the form-data section, you would have to reattach a file if you are loading a request through the history or the collection.
Looks like you may be sending that post variable in the headers. Use the body tab instead.
You are passing the $appUser_id as a string in the query, you don't need to put single quotes around the variable since double quotes evaluate vars inside. You can do:
$query = "INSERT INTO requests (appUser_id) VALUES ($appUser_id)";
Or
$query = "INSERT INTO requests (appUser_id) VALUES (".$appUser_id.")";
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