Inserting Data Using PHP Curl - php

I am trying to add the following data to my database using curl. It insert's the data but the data inserted is blank
Employee Name = Test
Employee Salary = 100
Employee Age = 28
This is my code in inserting the data:
// set post fields
$data["employee_name"] = "test";
$data["employee_salary"] = 1;
$data["employee_age"] = 1;
$ch = curl_init('http://localhost/cloud/v1/employees');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
This is my Function in getting the data :
function insert_employee()
{
global $connection;
$data = json_decode(file_get_contents('php://input'), true);
$employee_name=$data["employee_name"];
$employee_salary=$data["employee_salary"];
$employee_age=$data["employee_age"];
echo $query="INSERT INTO employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."'";
if(mysqli_query($connection, $query))
{
$response=array(
'status' => 1,
'status_message' =>'Employee Added Successfully.'
);
}
else
{
$response=array(
'status' => 0,
'status_message' =>'Employee Addition Failed.'
);
}
header('Content-Type: application/json');
echo json_encode($response);
}
Thank you

Replace this line:
$data = json_decode(file_get_contents('php://input'), true);
with:
$data = $_POST;
PHP will take your POSTed data and push it straight into a global $_POST array. No need to play with json_decode (unless you have posted a JSON string) or php://input.
Be aware, however, that blindly trusting posted data, and concatenating posted variables into a SQL statement is a huge security hole! Please look in to prepared statements and input validation.

Related

Pass PHP variable/value from one page to another

I have been trying to send the xml response I have stored in '$kxml' variable to the 'kycresult.php' page. I want to fetch the values from that xml and just print it. I am able to fetch the values if I store the xml in txt file and then get it using 'simplexml_load_file' but I don't want to create an extra file. Please let me know if there is a way to send the $kxml on next page.
$kycch = curl_init();
curl_setopt($kycch, CURLOPT_URL, $csckua_url);
curl_setopt($kycch, CURLOPT_POSTFIELDS, $kycxml);
curl_setopt($kycch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($kycch, CURLOPT_TIMEOUT, 20);
$kycresult = curl_exec($kycch);
$curl_errno = curl_errno($kycch);
$curl_error = curl_error($kycch);
curl_close($kycch);
// echo $kycresult;
$kxml = simplexml_load_string($kycresult);
if ($kxml['ret'] == 'Y') {
// $ksuccess = 'Authentication Successful';
header('location:Kycresult.php');
} else {
$ksuccess = 'Authentication Failed';
}
As one of the possible solutions you can store the variable in session
session_start();
$_SESSION['kxml'] = $kxml;
Then on the next page it will be available through
$kxml = $_SESSION['kxml'];
But actually it still stores in the auxiliary file by default under the hood.

JSON: Update base64 string using url JSON

I'm new to JSON Code. I want to learn about the update function. Currently, I successfully can update data to the database. Below is the code.
<?php
require_once "../config/configPDO.php";
$photo_after = 'kk haha';
$report_id = 1;
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport?taskname=&reportStatus=&photoBefore=&photoAfter=". urlencode($photo_after) . "&reportID=$report_id";
$data = file_get_contents($url);
$json = json_decode($data);
$query = $json->otReportList;
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
the problem is, if the value of $photo_after is base64 string, which is too large string, it will give the error:
1) PHP Warning: file_get_contents.....
2) PHP Notice: Trying to get property 'otReportList' of non-object in C:
BUT
when I change the code to this,
<?php
require_once "../config/configPDO.php";
$photo_after = 'mama kk';
$report_id = 1;
$sql = "UPDATE ot_report SET photo_after ='$photo_after', time_photo_after = GETDATE(), ot_end = '20:30:00' WHERE report_id = '$report_id'";
$query = $conn->prepare($sql);
$query->execute();
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
The data will updated including when the value of $photo_after is in base 64 string.
Can I know what is the problem? Any solution to allow the base64 string update thru json link?
Thanks
// ...
// It's likely that the following line failed
$data = file_get_contents($url);
// ...
If the length of $url is more than 2048 bytes, that could cause file_get_contents($url) to fail. See What is the maximum length of a URL in different browsers?.
Consequent to such failure, you end up with a value of $json which is not an object. Ultimately, the property otReportList would not exist in $json hence the error: ...trying to get property 'otReportList' of non-object in C....
To surmount the URL length limitation, it would be best to embed the value of $photo_after in the request body. As requests made with GET method should not have a body, using POST method would be appropriate.
Below is a conceptual adjustment of your code to send the data with a POST method:
<?php
require_once "../config/configPDO.php";
# You must adapt backend behind this URL to be able to service the
# POST request
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport";
$report_id = 1;
$photo_after = 'very-long-base64-encoding-of-an-image';
$request_content = <<<CONTENT
{
"taskname": $taskname,
"report_id": $report_id,
"photoBefore": $photoBefore,
"photo_after": $photo_after,
"reportStatus": $reportStatus
}
CONTENT;
$request_content_length = strlen($request_content);
# Depending on your server configuration, you may need to set
# $request_headers as an associative array instead of a string.
$request_headers = <<<HEADERS
Content-type: application/json
Content-Length: $request_content_length
HEADERS;
$request_options = array(
'http' => array(
'method' => "POST",
'header' => $request_headers,
'content' => $request_content
)
);
$request_context = stream_context_create($request_options);
$data = file_get_contents($url, false, $request_context);
# The request may fail for whatever reason, you should handle that case.
if (!$data) {
throw new Exception('Request failed, data is invalid');
}
$json = json_decode($data);
$query = $json->otReportList;
if ($query) {
echo "Data Save!";
} else {
echo "Error!! Not Saved";
}
?>
sending a long GET URL is not a good practice. You need to use POST method with cURL. And your webservice should receive the data using post method.
Here's example sending post using PHP:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
Sample code from: PHP + curl, HTTP POST sample code?
And all output from the webservice will put in the curl_exec() method and from there you can decode the replied json string.

REST API response to URL rewriting

I am trying REST API USING PHP. I have modified my URL REWRITING using .htaccess rules. This is the POST URL which is sent from my curl code along with DATA ARRAY. So that php reads its as a POST COMMAND AND INSERTS the data into my products table using PDO.
this is my code for curl command:
<?php
$data=array(
'product_name' =>'Television',
'price' => 1000,
'quantity' => 10,
'seller' =>'XYZ Traders'
);
$url = 'http://localhost/API2/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);
echo $response;
?>
While my php code for products.php is:
<?php
// Connect to database
require_once('database.php');
$request_method=$_SERVER["REQUEST_METHOD"];
switch($request_method)
{
case 'POST':
// Insert Product
insert_product($db);
break;
default:
// Invalid Request Method
header("HTTP/1.0 405 Method Not Allowed");
break;
}
function insert_product($db)
{
//global $connection;
$_product_name=$_POST["product_name"];
$_price=$_POST["price"];
$_quantity=$_POST["quantity"];
$_seller=$_POST["seller"];
$query = 'INSERT INTO products
(Product_name, Price, Quantity,Seller)
VALUES
( :product_name, :price, :quantity,:seller)';
$statement = $db->prepare($query);
//$statement->bindValue(':category_id', $category_id);
$statement->bindValue(':product_name', $_product_name);
$statement->bindValue(':price', $_price);
$statement->bindValue(':quantity', $_quantity);
$statement->bindValue(':seller', $_seller);
$bool=$statement->execute();
$statement->closeCursor();
if($bool)
{
$response=array(
'status' => 1,
'status_message' =>'Product Added Successfully.'
);
}
else
{
$response=array(
'status' => 0,
'status_message' =>'Product Addition Failed.'
);
}
header('Content-Type: application/json');
echo json_encode($response);
}
//$db = null;
// Close database connection
//mysqli_close($connection);
when i send the request to my localhost it recieves it but no response is being sent. Products is a table with product_ID,Product_name,Price,Quantity,Seller. So how to make it work. I am trying to develop REST API using all its rules so don't know whats the issue.

Getting a curl response in string format

I am trying to execute a url and getting its response. Following is the code that executes the curl. I want the curl execution to return me a string in $result.
<?php
$fields = array
(
'username'=>urlencode($username),
'pwrd'=>urlencode($pwrd),
'customer_num'=>urlencode($customer_num)
);
$url = 'http://localhost/test200.php';
//open connection
set_time_limit(20);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result; //I want $result to be "Successful"
?>
This is my test200.php on localhost:
<?php
$usernam = $_POST['username'];
$pass = $_POST['pwrd'];
$customer_num = $_POST['customer_num'];
echo "Successful!";
?>
What changes do I make in test200.php? Please help.
You should use the httpcode returned by the curl execution and not rely on a string that is returned
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Here - http://www.webmasterworld.com/forum88/12492.htm
Once the data is sent to test200.php do the appropriate manipulation like insert the posted values into a table and on success
echo "Successful!";
or print the same in your test200.php.. assuming you are doing an insert code in test200.php code would be like
<?php
$qry = "INSERT INTO `your_table` (`field_customer_name`, `field_username`, `field_password`) VALUES ($fields['customer_num'], $fields['username'], some_encrypt_fxn($fields['pwrd']))";
mysql_query($qry);
$err_flag = mysql_error($your_conn_link);
if($err_flag == '') {
echo "Successful!";
}
else {
echo "Failed, Error " . $err_flag;
}
?>
If the purpose of getting "Successful!" is to check if the cURL returns success then i suggest using Prateik's answer of using the returned status code
Somehow a simple print("Successful"); statement in test200.php worked well. The response i get now is as follows: HTTP Code: 0 Array ( [0] => [1] => Successful )

retrieve Json information from php file using cURL

ive seen lots of examples and to be honest i am a little confused on the matter.
I have been doing php for only 3 weeks so i am very new to this.
Basically i have wrote a function that asks for a token and a url, then it checks the database to if is exists, if it exists it then will offer a json array. I was wondering how select file and enter the function and retrieve the json data using cURL.
The function i have created is within the http://www.domain.com/api.php
Here is the function code:
function check_api_website($token, $url){
$token = trim(htmlentities($token));
$safetoken = mysql_real_escape_string($token);
$url = trim(htmlentities($url));
$safeurl = mysql_real_escape_string($url);
$checkwebsite = "SELECT message,islive FROM websitetokens WHERE url='".$safeurl."' AND token='".$safetoken."'";
$checkwebsite_result = mysql_query($checkwebsite) OR die();
$numberofrows = mysql_num_rows($checkwebsite_result);
if($numberofrows > 0){
$website = mysql_fetch_array($checkwebsite_result);
$message = stripslashes($website["message"]);
$islive = stripslashes($website["islive"]);
json_encode(array(
'message' => $message,
'islive' => $islive,
));
$date = date('Y-m-d');
$time = gmdate('H:i');
$loginwebsite = "UPDATE websitetokens SET loggedin='".$date."',time='".$time."' WHERE url='".$safeurl."' AND token='".$safetoken."'";
$loginwebsite_result = mysql_query($loginwebsite) OR die();
} else {
json_encode(array(
'message' => '',
'islive' => '1',
));
}
}
As you can see the json_encode is there and that is what i am wanting to retrieve.
If you could please explain a little also would help my learning.
Thanks for the help in advance :)
A simple request with cUrl to retrieve and parse JSON data would look like this:
function get_json($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($resultCode == 200) {
return json_decode($data);
} else {
return false;
}
}
You can place this method in your code and simply call it like this:
$json = get_json('http://www.example.com');
Good to see you're aware SQL injections and escaping the input. However, some PHP configurations might have the so called 'magic quotes' enabled, which escapes quotes on any input parameters with slashes.
If those slashes aren't stripped before calling mysql_real_escape_string, the resulting string will be double escaped. You can use a method like this to make sure everything gets escaped properly:
function escape_string($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return mysql_real_escape_string($string);
}

Categories