I sending a JSON object from my android app to my web service. (using volley). Here is a part of my code.
private void sendtoDB(final String ngno){
String tag_string_req = "req_save_to_db";
final JSONObject JSONdates = new JSONObject();
for(int i = 0 ; i < dates.size() ; i++){
try{
JSONdates.put("date", dates.get(i));
}catch (Exception e){
e.printStackTrace();
}
}
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_UpdateDates, new Response.Listener<String>() {
#Override
public void onResponse(String response) { ....}
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("ngno", ngno);
params.put("JSON", JSONdates.toString());
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
dates array contains several date Strings that i want to store in my Database. Below is the output of my JSON object (JSONdates).
{"dates":["Wed Mar 30 00:00:00 GMT+05:30 2016","Thu Mar 31 00:00:00 GMT+05:30 2016"]}
My question is how do i receive this JSON object in my php and how to decode it properly and get each date value to a variable so i can execute sql query accordingly.
This is my php code.
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
if(isset($_POST['ngno']) && isset($_POST['JSON']) ){
$ngno = $_POST['ngno'];
$json = json_decode($_POST['JSON'], true);
foreach($json){
$date = $json['date'];
$job = $db->updateDates($ngno, $date);
if($job){
$response["error"] = FALSE;
echo json_encode($response);
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in Updating!";
echo json_encode($response);
}
}
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Dates are missing!";
echo json_encode($response);
}
?>
updateDates function
public function updateDates($ngno, $date){
$stmt = $this->conn->prepare("INSERT INTO datepicker(ngno, date) VALUES($ngno, $date)");
$result = $stmt->execute();
$stmt->close();
}
I get a syntax error near forearch($json) unexcepted ')'.
Any help would be much appreciated.
EDIT 1:
changed the foreach loop in php code as following
foreach($dates as $date){
error_log[$date];
$job = $db->updateDates($ngno, $date);
if($job){
$response["error"] = FALSE;
echo json_encode($response);
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in Updating!";
echo json_encode($response);
}
}
But now it says, PHP Warning: Invalid argument supplied for foreach()
Any help Guys? Im new to programming and not sure how to get it fixed.
change foreach($json){ to foreach($json['dates'] as $date){and delete the line $date = $json['date'];. See php manual about foreach for more info about the foreach syntax
Related
why nothing happened when i put the correct email, but whatevet i put correct or incorrect password the program still not doing anything. It's like the program not checked the password, can you help me ?
This my login.php
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'];
$password = $_POST['password'];
require_once 'connect.php';
$sql = "SELECT * FROM user WHERE email='$email' ";
$response = mysqli_query($conn, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1 ) {
$row = mysqli_fetch_assoc($response);
if ( password_verify($password, $row['password']) ) { // I Think The Problem At This but i still don't know.
echo $password;
$index['name'] = $row['name'];
$index['email'] = $row['email'];
$index['id'] = $row['id'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}
}
}
?>
This my SignInActivity.java // or at this the problem is ?
public class SignInActivity extends AppCompatActivity {
private EditText email,password;
private Button login;
private TextView link_regist;
private static String URL_LOGIN = "https://awalspace.com/app/imbalopunyajangandiganggu/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
email = findViewById(R.id.titEmail);
password = findViewById(R.id.titPassword);
login = findViewById(R.id.btnSignIn);
link_regist = findViewById(R.id.tvToSignUp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if(!mEmail.isEmpty() || !mPassword.isEmpty())
{
login(mEmail,mPassword);
}
else{
email.setError("Silahkan Masukkan Email");
password.setError("Silahkan Masukkan Password");
}
}
});
}
private void login(final String email, final String password) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray =jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email = object.getString("email").trim();
Toast.makeText(SignInActivity.this, "Success Login. \n Your Name : "+name+"\nYour Email : "+email,Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SignInActivity.this, "Error "+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SignInActivity.this, "Error "+error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email",email);
params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Partial answer:
First off
You are open to SQL injection. You should parameterize your query.
Parameterized queries in PHP with MySQL connection
Second
You can add the password to your query so you don't have to do a 2nd check, if you store the passed password in the DB, or you can hash your password first then use it in your query. That avoids getting more user data than necessary (with the associated possible leaking of data) and avoids needing a second method to find the correct user.
This is shown in the link above.
If you store a salt in the DB, I can understand why you need the 2nd method, but you might be able to salt the password in the SQL, via a SQL function. Since you don't include the code for password_verify, we have no way to know what you're actually doing there, so I'm keeping this as basic as I can. (My philosophy is to keep things simple until complications are required.)
Third
Even if you are getting all the columns in that table, specify the column names you need. You might end up adding to that table later, which would cause this query to pull more data than it needs, again.
Fourth
Since you already have the email, which is one of the parameters of the query, you don't need to get it from the DB.
FYI, the link above adds each parameter individually, but mysqli_stmt_bind_param can do them all in one shot.
Object oriented style
mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] ) : bool
Procedural style
mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed &$var1 [, mixed &$... ] ) : bool
...
types
A string that contains one or more characters which specify the types for the corresponding bind variables:
...
https://www.php.net/manual/en/mysqli-stmt.bind-param.php
$stmt = mysqli_prepare($dbc, "SELECT name, id FROM users WHERE email= ? AND password = ?");
mysqli_stmt_bind_param($stmt, "ss", $email, $password); // or use a hash from a method instead of $password
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch($stmt);
This should pull just the one user, unless it doesn't pull any users, so you should have a clear indication of whether this user has access to your site/data/whatever or not. I would suggest sending an actual success message that you can recognize as something a little more specific to you, rather than the generic message you have right now. I understand you're still in testing phase, so it's something to think about later, if you hadn't already.
I would also suggest sending an HTTP 401 message back if $row is null. That way it's 100% guaranteed that your client software understands what happened as well as not giving any specifics as to why it failed. You can still tell the user something more meaningful, such as "Email and Password Combination Not Recognized". Also, don't specify if the email or the password is wrong, since this can lead to easier brute force hacking. There's a lot of contention around this idea of prompts, so I'll let you do your own research and make up your mind about it.
Whether your Java code is correctly sending the login credentials to your PHP server, IDK. I'm rusty on that, so I'll let someone else chime in, and why I'm saying this is a partial answer. At least this answer should get your PHP on the right track.
Hi I am having a hard time figuring out what could be the cause of this error. until I tried to use the debug and found out that instead of a json response I am getting an html response. Please help me figure this out.
Check this java code :
from this point the error is triggered
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_SUBMIT_CLIENT, response -> {
Log.d(TAG, "Submission Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Log.d("Debug", jObj.toString());
boolean error = jObj.getBoolean("success");
if (!error) {
Toast.makeText(getContext(), "Client successfully submitted.", Toast.LENGTH_LONG).show();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
and also this is my hp script. I have it also test in some websites and found no error so I'm pretty sure that there is no problem here. I will still post it and leave it to you guys and If there is a problem please point it out.
require_once __DIR__ . '/DB_Connect.php';
$db = new DB_CONNECT();
$query = mysqli_query("INSERT INTO clientinformation(amountApplied, mop, term, lastname, firstname, middlename, birthdate, age, sex, status, marriageDate, noChildren, nationality, acr, address, cityMunicipality, province, telNo, years, offAddress, offCityMunicipality, offProvince, offTelNo, offYears, busAddress, busCityMunicipality, busProvince, busTelNo, busYears, productServiceOffered) VALUES('$amountApplied','$mop','$term','$lastname','$firstname','$middlename','$birthdate','$age','$sex','$status','$marriageDate','$noChildren','$nationality','$acr','$address','$cityMunicipality','$province','$telNo','$years','$offAddress','$offCityMunicipality','$offProvince','$offTelNo','$offYears','$busAddress','$busCityMunicipality','$busProvince','$busTelNo','$busYears','$productServiceOffered')");
$result = $mysqli->query($query);
if ($result) {
$response["success"] = 1;
$response["error_msg"] = "Application successfully made.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["error_msg"] = "Oops! An error occurred.";
echo json_encode($response);
}
and lastly here is my log
W/System.err: org.json.JSONException: Value
at org.json.JSON.typeMismatch(JSON.java:112) W/System.err: at
org.json.JSONObject.(JSONObject.java:163)
at org.json.JSONObject.(JSONObject.java:176)
at info.androidhive.bottomnavigation.fragment.ApplicationFragment.lambda$submitClient$4$ApplicationFragment(ApplicationFragment.java:253)
at info.androidhive.bottomnavigation.fragment.-$$Lambda$ApplicationFragment$8jvL3OnFiDofc9nz50lAoSvp9ew.onResponse(Unknown
Source:4)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:873)
I'm a beginner in PHP and i've got this code where both if and else parts are executed in the same "run". I know it's logically impossible but that's what I'm getting.
Here's my PHP Code:
<?php
require_once 'create_request_form.php';
$db = new create_request_form();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['rqTitle']) && isset($_POST['rqMname']) && isset($_POST['rqUname']) && isset($_POST['rqBranch']) && isset($_POST['rqText']) && isset($_POST['rqMinPrice']) && isset($_POST['rqMaxPrice']) && isset($_POST['rqImage']) && isset($_POST['rqCategory']) && isset($_POST['rqDateTime'])) {
// receiving the post params
$rqTitle = $_POST['rqTitle'];
$rqMname = $_POST['rqMname'];
$rqUname = $_POST['rqUname'];
$rqBranch = $_POST['rqBranch'];
$rqText = $_POST['rqText'];
$rqMinPrice = $_POST['rqMinPrice'];
$rqMaxPrice = $_POST['rqMaxPrice'];
$rqImage = $_POST['rqImage'];
$rqCategory = $_POST['rqCategory'];
$rqDateTime = $_POST['rqDateTime'];
// check if there is a request with the same title
if ($db->checkReqTitle($rqTitle)) {
// Request already exists
$response["error"] = TRUE;
$response["error_msg"] = "Request already exists with the title: " . $rqTitle;
echo json_encode($response);
} else {
// create a new request
$request = $db->StoreReqInfo($rqTitle, $rqMname, $rqUname, $rqBranch, $rqText, $rqMinPrice, $rqMaxPrice, $rqImage, $rqCategory, $rqDateTime);
if ($request) {
// request stored successfully
$response["error"] = FALSE;
$response["request"]["rqTitle"] = $request["rqTitle"];
$response["request"]["rqMname"] = $request["rqMname"];
$response["request"]["rqUname"] = $request["rqUname"];
$response["request"]["rqBranch"] = $request["rqBranch"];
$response["request"]["rqText"] = $request["rqText"];
$response["request"]["rqMinPrice"] = $request["rqMinPrice"];
$response["request"]["rqMaxPrice"] = $request["rqMaxPrice"];
$response["request"]["rqImage"] = $request["rqImage"];
$response["request"]["rqCategory"] = $request["rqCategory"];
$response["request"]["rqDateTime"] = $request["rqDateTime"];
echo json_encode($response);
} else {
// request failed to store
$response["error"] = TRUE;
$response["error_msg"] = "An error occurred while creating the request. Please try again.";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>
The required behavior (storing data in the database) is all performed well but the $response I'm getting is the error string i've assigned to when a request title already exists instead of the JSON formatted array of the stored request (Both if and else bodies are executed but i get the result of if body as a response).
A screenshot of the $response using Postman to send the request:
A screenshot from my Samsung Galaxy Note 3:
I'm also using Galaxy Note 4 for testing and it just shows me a blank Toast message and doesn't start the intent(doesn't move to home screen).
So far the only possible explanation is that the script is being executed twice, however I can't find anywhere that called it a second time.
This is the java code responsible for sending a request with required paramters to the php script above.
private void storeRequest(final String rTitle, final String rMname, final String rUname,
final String rBranch, final String rText, final String rMinPrice,
final String rMaxPrice, final String imagePath, final String rCategory) {
// Tag used to cancel the request
String cancel_req_tag = "request";
//A progress dialog message to let the user know they are being registered
progressDialog.setMessage("Please wait while we add your request...");
showDialog();
//creating a StringRequest to send the registration info to the script
// at the server for processing
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REQUEST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Request Response: " + response.toString());
hideDialog();
try { //json objects must be surrounded by try catch statement
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) { // error is set to false, meaning no error
// Launch home activity
Intent intent = new Intent(CreateRequestActivity.this, HomeActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(CreateRequestActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(CreateRequestActivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("rqTitle", rTitle);
params.put("rqText", rText);
params.put("rqMname", rMname);
params.put("rqUname", rUname);
params.put("rqBranch", rBranch);
params.put("rqMinPrice", rMinPrice);
params.put("rqMaxPrice", rMaxPrice);
params.put("rqImage", imagePath);
params.put("rqCategory", rCategory);
params.put("rqDateTime", DateFormat.getDateTimeInstance().format(new Date()));
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
Any ideas?
Thanks in advance!
So turns out the problem stemmed from the Java code and not PHP (poor PHP ;P). More accurately, Volley requests have a problem with request timeouts, especially when sending requests using POST method.
So what worked for me was adding this line right before adding the request to the queue:
strReq.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0));
*Replace strReq with your request name. Basically what this line does is that it prevents volley from sending a duplicate request when the first request takes too long.
The original & more datailed answer:
The DefaultRetryPolicy.class's hasAttemptRemaining() class looks like this:
protected boolean hasAttemptRemaining() {
return this.mCurrentRetryCount <= this.mMaxNumRetries;
}
From what I can see, setting the maxNumRetries to 0 will still make that return true if it hasn't done a retry yet.
I fixed it with a
request.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0);
Source: Android Volley makes 2 requests to the server when retry policy is set to 0
Task: sync records from android sqlite to mysql.
Problem: mysql/php is not inserting data into my table in mysql. But no errors were shown.
DB_Connect.php:
<?php
class DB_Connect {
// constructor
function __construct(){
}
// destructor
function __destruct(){
}
// connecting to database
public function connect(){
require_once 'config.php'; // defined DB_HOST,DB_USER,DB_PASSWORD here
// connecting to mysql
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
// selecting database
mysqli_select_db($con,"heart");
// return database handler
return $con;
}
// closing database connection
public function close(){
mysqli_close($this->connect());
}
}
?>
DB_Operations.php:
<?php
class DB_Operations {
private $db;
public $last_id;
public $error;
public $error_conn;
public $error_no;
// constructor
function __construct(){
require 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct(){
}
// Storing new doctor
public function storeDoctor($_id,$firstName,$lastName,$specialization,$licenseNumber,$clinicAddress,$email,$contactNum,$username,$password,$aboutMe){
$result = mysqli_query($this->db->connect(),"INSERT INTO doctor(_id,first_name,last_name,specialization,license_number,clinic_address,email,contact_number,username,password,about_me) VALUES('$_id','$firstName','$lastName','$specialization','$licenseNumber','$clinicAddress','$email','$contactNum','$username','$password','$aboutMe')");
if (mysqli_connect_errno()){
$this->error_conn = mysqli_connect_error();
}
if(!$result){
if(mysqli_errno($this->db->connect()) == 1062){
// duplicate key - primary key violation
return true;
} else{
// for other reasons
$this->error = mysqli_error($this->db->connect());
$this->error_no = mysqli_errno($this->db->connect());
return false;
}
} else{
$this->last_id = mysqli_insert_id($this->db->connect());
return true;
}
}
// getters
public function getError(){
return $this->error;
}
public function getError_no(){
return $this->error_no;
}
public function getError_conn(){
return $this->error_conn;
}
...
insertuser.php:
<?php
include 'DB_Operations.php';
// create object for DB_Operations class
$db = new DB_Operations();
// get JSON posted by Android Application
$json = $_POST["doctorsJSON"];
// remove slashes
if(get_magic_quotes_gpc()){
$json = stripslashes($json);
}
// decode JSON into Array
$data = json_decode($json);
// util arrays to create response JSON
$a = array();
$b = array();
// loop through an array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data); $i++){
// store doctor into MySQL DB
$res = $db->storeDoctor($data[$i]->_id,$data[$i]->first_name,$data[$i]->last_name,$data[$i]->specialization,$data[$i]->license_number,$data[$i]->clinic_address,$data[$i]->email,$data[$i]->contact_number,$data[$i]->username,$data[$i]->password,$data[$i]->about_me);
// based on insertion, create JSON response
$b["local_id"] = $data[$i]->_id;
if($res){
$b["server_id"] = $db->last_id;
$b["status"] = 'yes';
}else{
$b["status"] = 'no';
$b["err_no"] = $db->getError_no();
$b["error"] = $db->getError();
$b["error_conn"] = $db->getError_conn();
}
array_push($a,$b);
}
// post JSON response back to Android Application
echo json_encode($a);
?>
I have a function in java which syncs the sqlite data to mysql:
public void syncSQLiteToMySQL(Context context,String selectQuery){
dop = new DatabaseOperations(context);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
ArrayList<HashMap<String,String>> doctorList = new ArrayList<HashMap<String,String>>();
doctorList = dop.getAllDoctors();
if(doctorList.size()!=0){
String json = dop.composeJSONfromSQLite(selectQuery);
params.put("doctorsJSON", json);
Log.i("json to pass", json);
client.post("http://"+ip+":8080/changed_server_name/insertuser.php",params ,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.e("client response",response);
try {
JSONArray arr = new JSONArray(response);
for(int i=0; i<arr.length();i++){
JSONObject obj = (JSONObject)arr.get(i);
// did something with json response here
dop.updateSyncStatus(obj.getString("local_id"),obj.getString("status"));
}
message = "DB Sync completed!";
} catch (JSONException e) {
message = "Error Occured [Server's JSON response might be invalid]!";
Log.e("JSONException",e.getMessage());
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
if(statusCode == 404){
message = "Requested resource not found";
}else if(statusCode == 500){
message = "Something went wrong at server end";
}else{
message = "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]";
Log.e("sync post failure",error.toString());
}
}
});
}
}
So, here's the response:
[{"local_id":"0","status":"no","err_no":0,"error":"","error_conn":null}]
The JSON works fine. No problem with it. I have checked and it passes correct data. Just the PHP and MySQL side. Somehow, I couldn't find the error to this code. There is no error message, error number is 0, and there was no error in connecting to DB. But the query in storeDoctor() returns false. How could this be? I have been reading about this problem on this site and others, but I have not really found something that's close to my problem.
Please enlighten me. Your help would really be appreciated. Thanks in advance.
Edit: I also tried mysqli_ping($this->db->connect()); and it returns true which means the connection is okay. So, what really is this something that makes the query fail?
Did you try using error_reporting(E_ALL);
Also inside the constructor you used
$this->db->connect();
And then in the store you used
$result = mysqli_query($this->db->connect(),
Can you post the code for connect
I'm trying to setup a connection with a java-server.
This is the php code:
<?php
$GLOBALS['THRIFT_ROOT'] = 'root';
/*Remember these two files? */
require_once 'Types.php';
require_once 'MachineControl.php';
/* Dependencies. In the proper order. */
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Transport/TTransport.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Exception/TException.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Exception/TApplicationException.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Base/TBase.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Protocol/TProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Transport/TBufferedTransport.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Type/TMessageType.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Factory/TStringFuncFactory.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/StringFunc/TStringFunc.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/StringFunc/Core.php';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Type/TType.php';
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TSocket;
use Thrift\Transport\TSocketPool;
use Thrift\Transport\TFramedTransport;
use Thrift\Transport\TBufferedTransport;
$host = '192.168.129.117';
$port = 9090;
$socket = new Thrift\Transport\TSocket($host, $port);
$transport = new TBufferedTransport($socket);
$protocol = new TBinaryProtocol($transport);
// Create a calculator client
$client = new MachineControlClient($protocol);
$transport->open();
echo "Eror: " . $client ->getError(); ?>
I have a connection with the java-server. But my output in the test.php file will be:
Fatal error: Uncaught exception 'Thrift\Exception\TApplicationException' with message 'Internal error processing getError' in C:\xampp\htdocs\jasa\thrift\MachineControl.php:877 Stack trace: #0 C:\xampp\htdocs\jasa\thrift\MachineControl.php(845): MachineControlClient->recv_getError() #1 C:\xampp\htdocs\jasa\thrift\test.php(34): MachineControlClient->getError() #2 {main} thrown in C:\xampp\htdocs\jasa\thrift\MachineControl.php on line 877
What is going wrong? All files and classes are in the file, the getError class looks like this:
public function getError()
{
$this->send_getError();
return $this->recv_getError();
}
public function send_getError()
{
$args = new \MachineControl_getError_args();
$bin_accel = ($this->output_ instanceof TProtocol::$TBINARYPROTOCOLACCELERATED) && function_exists('thrift_protocol_write_binary');
if ($bin_accel)
{
thrift_protocol_write_binary($this->output_, 'getError', TMessageType::CALL, $args, $this->seqid_, $this->output_->isStrictWrite());
}
else
{
$this->output_->writeMessageBegin('getError', TMessageType::CALL, $this->seqid_);
$args->write($this->output_);
$this->output_->writeMessageEnd();
$this->output_->getTransport()->flush();
}
}
public function recv_getError()
{
$bin_accel = ($this->input_ instanceof TProtocol::$TBINARYPROTOCOLACCELERATED) && function_exists('thrift_protocol_read_binary');
if ($bin_accel) $result = thrift_protocol_read_binary($this->input_, '\MachineControl_getError_result', $this->input_->isStrictRead());
else
{
$rseqid = 0;
$fname = null;
$mtype = 0;
$this->input_->readMessageBegin($fname, $mtype, $rseqid);
if ($mtype == TMessageType::EXCEPTION) {
$x = new TApplicationException();
$x->read($this->input_);
$this->input_->readMessageEnd();
throw $x;
}
$result = new \MachineControl_getError_result();
$result->read($this->input_);
$this->input_->readMessageEnd();
}
if ($result->success !== null) {
return $result->success;
}
throw new \Exception("getError failed: unknown result");
}
Many thanks for your time to discuss this issue ;)
Something was wrong in the server this topic will be closed