ionic 2 http.post cannot waiting response >= 7 seconds - php

sorry if my language is not good.
i have a ionic app, this app send data with angular http.post to server my company, this is my script on server :
<?php
set_time_limit(120);
ini_set("max_execution_time",120);
date_default_timezone_set("Asia/Jakarta");
require_once("menu.php");
class serviceController extends menu
{
private $clientInput;
public function __construct($clientInput){
$this->clientInput = $clientInput;
$this->Controller();
}
private function getMenu($packageName){
parent::__construct($packageName);
echo json_encode(parent::menu());
}
private function Controller(){
$Decode = json_decode($this->clientInput);
if($Decode->id=="getMenu"){
$this->getMenu($Decode->packageName);
}else if($Decode->id=="Development"){
sleep(15);
echo '{"status":"1","info":"Success"}';
}else{
switch($Decode->packageName){
case "com.guava.manis.mobile.payment":{
$this->doRequest("http://xxx.xxx.xxx.xxx/multiflat_new.jsp");
break;
}
}
}
}
private function doRequest($target){
$ch = curl_init($target);
$input = str_replace(':"",',':"-",',str_replace(':false,',':"-",',str_replace(':0,',':"-",',$this->clientInput)));
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$input);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type:application/json'));
$response = curl_exec($ch);
$finalResponse = rtrim("1",$response);
echo $finalResponse;
}
}
$clientInput = file_get_contents("php://input");
new serviceController($clientInput);
this is my script on my ionic app :
httpPOST(){
var request = JSON.stringify(this.finalREQ);
console.log("httpPOST request : "+request);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
return this.http.post(this.postUrl,request,options).timeout(50000)
}
when i send data json to server with field 'id' is 'Development' my script will be sleep 15 seconds, the problem is ionic app not receive response from server, but if i change sleep <=7 seconds it's works, my question is how to create ionic app can wait response >=7 seconds ?, but if my scripts on server i move to localhost, dan i send data to localhost it's works perfectly, where the problem ?, on my server scripts, my ionic app scripts, or on my configuration of apache ?

Related

The authorisation bearer isn't read correctly server-side

I have started working on an old application developed in PHP with codeigniter. The previous dev isn't in the company anymore, I'm all alone to figure out what's happening.
First of all, the code seems to be working as intended on the first "development" server, but raises an error on the "test" server. The code is the same, the servers should be configured the same (I still don't have all the clearances I need to check this). Anyway, here is the logic :
There is a login page which asks the usual credentiels. They are sent to the back controler via POST, he then sends a request to the authentication API which returns a token if everything is correct.
The token is then written on the server, recovered in the front page and the user is redirected to the home page. This last redirection is completed with a "autorization: Bearer {token}" in the header.
Here are the screens, obtained via Postman :
First call from the front to Authentication::login :
[![first call from front to authenticaiton::login][1]][1]
The token is then correctly recovered, and apparently stored server-side :
Authentication controler
public function login(){
[...]
$make_call = $this->callAPI('POST', $this->config->items('apiurl') . 'token/', $data_array, ^this->config->items('apibearer'), $this->config->item('proxy'));
$response = json_èdecode($make_call, true);
if(isset($response['error'])){
exit(json_encode(array('error'=>true, 'error_id'=>$response['error'])));
}
//parse token in JWT
$token = $this->auc9_config->getParser()->parse((string) $response['id_token']);
$token = $thi->writeToken($userId, $token);
exit(json_encode(array('error' => false, 'token' => $tken->__toString())));
}
}
public function writeToken($userId, $token){
$role = $token->claims()->get('functional_post');
$eds = $role['structure_element_id'];
if(!is_null($eds)){
$builder = $this->company_config->createBuilder();
$new_token = $builder->issuedAt(new DateTimeImmutable())
->expriresAt((new DateTimeImmutable())->add(new DateInterval('PT' . (3600 * 4) . 'S')))
->withClaim('id_cr', $token->claims()->get('structure_id'))
->withClaim('eds', $eds)
->withClaim('uuid_tablet','web_demo')
->withClaim('version_apk', 'web_demo')
->getToken($this->company_config(getSigner(), $this->company_config->getSigningKey());
return $new_token;
} else {
die(json_encode(array('error'=>true, 'error_id'=>'invalid_user')));
}
}
JS side, the url is rewriten and the token is sent in the header :
index.js
if(data.token){
const url = window.location.pathname.replace(/authentication\/?/, '');
$.ajax({
type : 'GET',
url,
headers: {
'autorization': 'Bearer ' + data.token
},
success : function(data){
window.location.reload();
},
error : function(err) {
$(form).find('.erros').append('<p>invalid token</p>')
}
});
}
Finaly, the home page is called via the last ajax call, the the page is loaded if the token workds properly :
Home controler
public function index(){
$home_page = $this->home_page->fetch_activated();
if(home_page === null){
show_404();
}else{
//display content
[...]
}
}
Home Model
class HomePage extends MY_Model {
[...]
public function fetch_activated() {
$result = $this->read(array('active IS NOT NULL' => null, 'active >' => 0));
return count($result) === 1 ? $result[0] : null;
}
}
**Error : **
In the development server, the user is correctly redirected to the home page
In the test server, the user is rooted to the 404 page
Without ssh access to the server, I can't put up some exit() command via VIM and watch the results, nor can I access any log file.
Do you have any idea whats I can do ?
Edit1 : transform images to code
Edit2 : added Home Model
As said by #nitrin0, there was a problem in the database. Once I got the credentials to access is, troubleshouting the problem was quite easy.

Session not being initiated from Guzzle Post

I am integrating Laravel into a legacy php app. The login page used to directly post to verifyUser.php which also started a Symfony Session.
The new architecture now posts to a laravel api which makes a Guzzle post to verifyUser.php.
javascript:
$(document).ready(function(){
$('#signIn').submit(function(){
var a = $('#email').val();
$.post('/api/login', { //this used to post to verifyUser.php
Username: $('#email').val(),
Password: $('#password').val()
}, function(data){
if(data['credentials'] == true){
console.log('credentials true');
console.log(data['uri']);
window.location.href=data['uri'];
} else {
$('#errMsg').html(data['errMsg']);
$('.alert').show();
}
}, 'json');
return false;
});
controller functions:
public function authenticate(Request $request) //aka api/login endpoint
{
//...
$legacyRes = $this->authenticateLegacy($request);
//...
}
private function authenticateLegacy(Request $request)
{
$response = null;
try {
$response = $this->client->post('/admin/verifyUser.php', [
'form_params' => ['Username' => $request->get('Username'),
'Password' => $request->get('Password')]
]);
}
catch(Exception $exception){
Log::error('Errrererererer', [$exception->getMessage()]);
}
$body = (string)$response->getBody();
Log::info('BODY:', [$body]);
return $body;
}
I have left out verifyUser.php because I have tested it and it returns the expected results.
When using the browser, the session information doesn't seem to get set. But according to my post responses, everything should be working.
Is this because I am routing the request through guzzle?
Posting under my answer to show updated code:
private function authenticateLegacy(Request $request)
{
//...
//parse cookie id from guzzle response
$body = (string)$response->getBody();
$cookie = $response->getHeader('Set-Cookie'); //PHPSESSID=SOMEID; path=/
$cookieBite = explode(';', $cookie)[0]; ////PHPSESSID=SOMEID
$cookieId = explode('=', $cookieBite)[1];
$data = json_decode($body, true);
$data['session'] = $cookieId;
return $data;
}
In the action:
public function authenticate(Request $request)
{
//...
$legacyRes = $this->authenticateLegacy($request);
//...
// this will have the session id in the body but will also
// set the cookie for the client so I don't have
// to set document.cookie w/ js
return response($legacyRes, 200)
->withCookie('PHPSESSID', $legacyRes['session']);
}
I assume your legacy endpoint uses cookies to identify a user's session.
A successfull request to the legacy endpoint returns a Set-Cookie header.
Guzzle doesn't forward this Set-Cookie header from the API response to the browser - you'll have to program this behaviour into the "wrapping" application.
You will need to tell guzzle to explicitly pass the corresponding Cookie header to the legacy api (to maintain the user's login state) when sending any further requests.
In order to achieve this you'll need to save this cookie within your new application (i.e. in the user's session or in database) and then pass it within a Cookie header along with all further requests you make to the legacy API.

How to connect phonegap app with php rest api

I have REST api on backend created with php (slim php micro framework). So code is:
INDEX.php
$app->post('/coords', 'authenticate', function() use ($app) {
$response = array();
//$jsonData = $app->request->post('podaci');
$jsonData = #file_get_contents('php://input');
$aData = json_decode($jsonData);
$latitude = $aData->location->latitude;
$longitude = $aData->location->longitude;
$podaci = $latitude.' ddd '.$longitude;
global $user_id;
$db = new DbHandler();
// creating new task
$coords_id = $db->createCoords($user_id, $podaci);
if ($coords_id != NULL) {
$response["error"] = false;
$response["message"] = "Coords insert successfully";
echoRespnse(201, $response);
} else {
$response["error"] = true;
$response["message"] = "Coords not inserted";
echoRespnse(200, $response);
}
});
I also have DBhandler file , code (function createCoords):
public function createCoords($user_id, $podaci) {
$stmt = $this->conn->prepare("INSERT INTO coords(podaci) VALUES(?)");
$stmt->bind_param("s", $podaci);
$result = $stmt->execute();
$stmt->close();
}
I try this REST api with sample data with ajax request and work well, but now I need to POST data from phonegap app to server and I write:
// BackgroundGeoLocation is highly configurable.
bgGeo.configure(callbackFn, failureFn, {
url: 'http://agroagro.com/agroMobile/v1/coords', // <-- Android ONLY: your server url to send locations to
params: {
Auth: 'df6017abde2d2re560896b63a0ee1039', // <-- Android ONLY: HTTP POST params sent to your server when persisting locations.
foo: 'bar' // <-- Android ONLY: HTTP POST params sent to your server when persisting locations.
},
desiredAccuracy: 0,
stationaryRadius: 50,
distanceFilter: 50,
notificationTitle: 'Background tracking', // <-- android only, customize the title of the notification
notificationText: 'ENABLED', // <-- android only, customize the text of the notification
activityType: 'AutomotiveNavigation',
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false // <-- enable this to clear background location settings when the app terminates
});
I read here how to make php file to get INPUT data: https://github.com/christocracy/cordova-plugin-background-geolocation/issues/79
as you can see from my index.php code I write everything fine but what can be problem? This just dont work when I test on my android phone.
I do not why you are using 'php://input'); for getting json data.
Its simple. use the following to grab the json data sent from your phone.
$request = $app->request();
$body = $request->getBody();
$input = json_decode($body);
To know more how to handle json data using slim you may try the following website.
http://www.ibm.com/developerworks/library/x-slim-rest/

PHP WebSocket ZMQ - Chat Operation - Send data to specific user

im working on a PHP project based on Symfony 2.2.11 and I installed the socketo related to the following tutorial http://socketo.me/docs/install to make my chat script working.
ServerCommand.php // Code of the command line that starts the WebSocket server
$oLoop = Factory::create();
// Listen for the web server to make a ZeroMQ push after an ajax request
$oContext = new Context($oLoop);
$oPull = $oContext->getSocket(\ZMQ::SOCKET_PULL);
// LET IT 127.0.0.1
$oPull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$oPull->on('message', array($oChat, 'onMessage'));
// Set up our WebSocket server for clients wanting real-time updates
$oWebSock = new Server($oLoop);
$oWebSock->listen(7979, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new IoServer(
new HttpServer(
new WsServer(
new WampServer(
$oChat
)
)
),
$oWebSock
);
$oLoop->run();
After a message is being added to database :
MessagesController.php
....
// This is our new stuff
$oContext = new \ZMQContext();
$oSocket = $oContext->getSocket(\ZMQ::SOCKET_PUSH, 'PushMe');
$oSocket->connect("tcp://mydomain:5555");
$aData = array(
'topic' => 'message',
'sUsername' => $oUserCurrent->getUsername(),
'sMessage' => $sMessage
);
$oSocket->send(json_encode($aData));
.....
The chat service :
Chat.php
/**
* A lookup of all the topics clients have subscribed to
*/
public function onSubscribe(ConnectionInterface $conn, $topic)
{
// When a visitor subscribes to a topic link the Topic object in a lookup array
$subject = $topic->getId();
$ip = $conn->remoteAddress;
if (!array_key_exists($subject, $this->subscribedTopics))
{
$this->subscribedTopics[$subject] = $topic;
}
$this->clients[] = $conn->resourceId;
echo sprintf("New Connection: %s" . PHP_EOL, $conn->remoteAddress);
}
/**
* #param string JSON'ified string we'll receive from ZeroMQ
*/
public function onMessage($jData)
{
$aData = json_decode($jData, true);
var_dump($aData);
if (!array_key_exists($aData['topic'], $this->subscribedTopics)) {
return;
}
$topic = $this->subscribedTopics[$aData['topic']];
// This sends out everything to multiple users, not what I want!!
// re-send the data to all the clients subscribed to that category
$topic->broadcast($aData);
}
JS code that receives data :
messages.html.twig :
var conn = new ab.Session(
'ws://mydomain:7979' // The host (our Ratchet WebSocket server) to connect to
, function() { // Once the connection has been established
conn.subscribe('message', function(topic, data)
{
console.log(topic);
console.log(data);
});
}
, function() { // When the connection is closed
console.warn('WebSocket connection closed');
}
, { // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers
'skipSubprotocolCheck': true
}
);
So everytings working perfectly, when I send a new Message, it goes to DB then it lands on the page of the chat.
PROBLEM :
The data lands wherever the JS script is, and the result is that all users can get the same recorded message
ASKING :
How can I make data lands in a specific user page ?
Thank you
You are using Ratchet on backend side, right?
So, here you have very good example of case you need:
http://socketo.me/docs/hello-world
You should keep your client connections inside $clients property (not collection of resources id!). So, you can choose one element from this collection and send a message only to this client.
Example:
public function onSubscribe(ConnectionInterface $conn, $topic)
{
// When a visitor subscribes to a topic link the Topic object in a lookup array
$subject = $topic->getId();
$ip = $conn->remoteAddress;
if (!array_key_exists($subject, $this->subscribedTopics))
{
$this->subscribedTopics[$subject] = $topic;
}
$this->clients[] = $conn; // you add connection to the collection
$conn->send("Hello new user!"); // you send a message only to this one user
}

Handling different php responses after a javascript http post request

I am developing an android application that uses the PHP/MySQL to send data from app to server in order to register/login users. I already wrote the Javascript and PHP files to send and receive JSON data an insert it into MySQL database. The problem I have is how to handle different responses from PHP.
Exemple:
<?php
//decode json object
$json = file_get_contents('php://input');
$obj = json_decode($json);
//variables
$user_firstname = $obj->{'user_firstname'};
$user_lastname = $obj->{'user_lastname'};
$user_email = $obj->{'user_email'};
$user_password = $obj->{'user_password'};
if([variables] != null){
//check for an existing email in db
mysql_query("Check if email exists");
if(email exist){
//pass a response to java file
return user_exists;
die();
}else{
//success
return success;
}
}
?>
All I want is to handle those different return values in order to interact with the user inside the android app.
I think you should user HTTP response codes for this. For example, your php script will return HTTP 200 - OK when user successfully created and HTTP 409 Conflict when user already exists. This is how RESTfull APIs usually works this. On Android you'll have to check the status code and decide what to do.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpget = new HttpPost("http://www.google.com/");
HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
You can craft a json response by creating an associative array and passing it to json_encode() which will return a string that you can echo to the java client. Don't forget to set the appropriate Content-Type header using the header() function. It's also a good idea to set the HTTP response code appropriately. I'm picturing something like this:
$responseArray = array('response' => 'success'); // or 'user_exists'
$responseJson = json_encode($responseArray);
header('HTTP/1.1 200 OK'); // or 4xx FAIL_TEXT on failure
header('Content-Type: application/json');
echo $responseJson;
You'll then have to parse this response on the java client.

Categories