Codeigniter - sending data via URL and getting response - php

what i am trying to do is send some data to a url and get a response like "success" that indicates that data is received in codeigniter. Do i need to configure an api in the codeigniter to test that. I tried the following code but not getting the expected result. To mention I am pretty new in codeigniter and php.
controller xmlPost.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class XmlPost extends CI_controller
{
public function index()
{
$this->load->model('xml_model','message');
$this->message->source = "14045" ;
$this->message->dst = "08887654657";
$this->message->msg = "Hi, this is test";
$this->message->url = 'http://localhost/codeigniter1/index.php/receive';
$data = $this->message->Send();
echo $data;
}
}
?>
and the model is xml_model.php
<?php
Class Xml_model extends CI_Model {
var $source; //Source address
var $dst; //Destination
var $msg; // Message
var $url;
var $api_url;
function __construct() {
parent::__construct();
}
function Send(){
$this->api_url = 'http://localhost/codeigniter1/index.php/receive';
$params = $this->source.'&destinationaddr='.$this->dst.'&shortmessage='.urlencode($this->msg).' '.urlencode($this->url).'';
$post_data = array(
"sourceaddr" => $params,
);
$stream_options = array(
'http' => array(
'method' => 'POST',
),
);
$context = stream_context_create($stream_options);
$response = file_get_contents($this->api_url, null, $context);
return $response;
}
}
?>

After url encoing Space[ ] can encoded as + sign.you have to manually replace as %20,then after execute your URL.
public function sendSMS($mobile,$code)
{
$stream_options = array(
'http' => array(
'method' => 'GET',
),
);
$context = stream_context_create($stream_options);
$url="http://api.smsbrain.in/1.2/appsms/send.php?user=satish123&passwd=123456&senderId=SATISH&recipients=".$mobile."&message=Your%20Verification%20code%20for%20facebook%20is%20".$code.".";
//echo "URL".$url;
$response = file_get_contents($url, null, $context);
echo print_r($response);
}

Related

Laravel returns 302 error when trying to send POST request to API route from Laravel Controller

A 302 error is returned when I'm trying to post to API Route, only in the second Post, using the function insereTelefone. When I'm using the Postman, it's working properly, so I think the problem is with Route, but I don't know what. I'm a newbie at the Laravel, so I'm learning how to implement things.
Here is the controller who calls the POST API:
class IndexClientes extends Controller
{
public function index()
{
$request = Request::create('/api/clientes', 'GET');
$response = Route::dispatch($request);
$clientes = json_decode($response->getContent(), true);
return view('index', compact('clientes'));
}
public function create()
{
return view('formulariocliente');
}
public function store(Request $request)
{
$nome = $request->nome;
$cpf = $request->cpf;
$email = $request->email;
$numerosTelefone = $request->telefone;
$tiposTelefone = $request->tipoTelefone;
$request = Request::create('/api/clientes', 'POST', array(
"nome" => $nome,
"cpf" => $cpf,
"email" => $email
));
$responseInicial = Route::dispatch($request);
$response = json_decode($responseInicial->getContent(), true);
$status = json_decode($responseInicial->status(), true);
if ($status !== 200) :
echo "ERRO";
die();
endif;
$idCliente = $response['id'];
if (!empty($numerosTelefone)) :
$i = 0;
foreach ($numerosTelefone as $numeroTelefone) :
$tipoTelefone = (int)$tiposTelefone[$i];
$numeroTelefone = (int)$numeroTelefone;
if (!empty($tipoTelefone) && !empty($numeroTelefone)) :
return self::insereTelefone($idCliente, $tipoTelefone, $numeroTelefone);
endif;
$i++;
endforeach;
endif;
}
public function insereTelefone($idCliente, $tipoTelefone, $numTelefone)
{
$array = array(
"cliente_id" => $idCliente,
"telefone_tipo_id" => $tipoTelefone,
"numero" => $tipoTelefone
);
$request = Request::create('api/telefones', 'POST', $array);
$responseInicial = Route::dispatch($request);
$response = json_decode($responseInicial->getContent(), true);
$status = json_decode($responseInicial->status(), true);
return $status;
}
}
TelefonesController.php
public function store(Request $request)
{
$request->validate(
[
'cliente_id' => 'required',
'telefone_tipo_id' => 'required',
'numero' => 'required|max:11'
]
);
}
api.php
Route::apiResource('telefones', \App\Http\Controllers\TelefonesController::class);
A 302 response usually means your request is being redirected by laravel.
If you are expecting a json response, you need to set the Accept: 'application/json' header along with your request just after the line:
$request = Request::create('api/telefones', 'POST', $array );
$request->headers->set('Accept', 'application/json');
the first
Route::dispatch
was redirecting the page, when I'm was trying to run the second Route::dispatch Laravel returns 302, to solve this I'm using the
app()->handle()
in the function insereTelefone to back to handle the request.
public function insereTelefone($idCliente, $tipoTelefone, $numTelefone) {
$array = array(
"cliente_id" => $idCliente,
"telefone_tipo_id" => $tipoTelefone,
"numero" => $numTelefone
);
$request_telefone = Request::create('api/telefones', 'POST', $array );
$responseInicial = app()->handle($request_telefone);
$status = json_decode($responseInicial->status(),true);
return $status;
}

Wordpress custom endpoints (WP_REST_Controller) 404 only on mobile

I currently have a working controller that extends WP_REST_Controller in a file under the current theme. These are being called using jQuery ajax. (all code below)
The issue I am facing is that I receive this error ONLY when accessing with a mobile device.
{"code": "rest_no_route", "message": "No route was found matching the URL and request method" "data": {"status": 404}}
settings -> permalinks -> save changes
tried using controller namespace "api/v1" and "wp/v2"
javascript
function getAllClients() {
jQuery.ajax({
url: "http://myurl.com/index.php/wp-json/wp/v2/get_all_clients",
type: "GET",
data: { /*data object*/},
success: function (clientList) {
// success stuff here
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.statusText);
}
})
}
api/base.php
<?php
class ApiBaseController extends WP_REST_Controller
{
//The namespace and version for the REST SERVER
var $my_namespace = 'wp/v';
var $my_version = '2';
public function register_routes()
{
$namespace = $this->my_namespace . $this->my_version;
register_rest_route(
$namespace,
'/get_all_clients',
array(
array(
'methods' => 'GET',
'callback' => array(new ApiDefaultController('getAllClients'), 'init'),
)
)
);
$ApiBaseController = new ApiBaseController();
$ApiBaseController->hook_rest_server();
api/func.php
<?php
class ApiDefaultController extends ApiBaseController
{
public $method;
public $response;
public function __construct($method)
{
$this->method = $method;
$this->response = array(
// 'Status' => false,
// 'StatusCode' => 0,
// 'StatusMessage' => 'Default'
// );
}
private $status_codes = array(
'success' => true,
'failure' => 0,
'missing_param' => 150,
);
public function init(WP_REST_Request $request)
{
try {
if (!method_exists($this, $this->method)) {
throw new Exception('No method exists', 500);
}
$data = $this->{$this->method}($request);
$this->response['Status'] = $this->status_codes['success'];
$this->response['StatusMessage'] = 'success';
$this->response['Data'] = $data;
} catch (Exception $e) {
$this->response['Status'] = false;
$this->response['StatusCode'] = $e->getCode();
$this->response['StatusMessage'] = $e->getMessage();
}
return $this->response['Data'];
}
public function getAllClients()
{
// db calls here
return json_encode($stringArr,true);
}
}
These are registered in the Functions.php file
require get_parent_theme_file_path('api/base.php');
require get_parent_theme_file_path('api/func.php');
Turns out the issue was a plugin my client installed called "oBox mobile framework" that was doing some weird routing behind the scenes. Disabling it resolved the issue, though there is probably a way to hack around this and get both to play together.

Can not access method in CakePHP

I am working in CakePHP 2.6.1 and I have a project in which I have to create an API. So I have created a function and its working fine when I am logged in but when I try to access without login, it redirects to the login page.
My function looks like :
class AndroidController extends AppController {
public function admin_survey_question()
{
$this->loadModel('Question');
Configure::write('debug', '2');
$survey_id = $_REQUEST['survey_id'];
$this->layout = "";
//$condition = "Question.survey_id = '".$survey_id."'";
$this->Question->unbindModel(
array('hasMany' => array('Result'))
);
$info = $this->Question->find('all', array(
'fields' => array('Question.id,Question.question, Question.options'),
'conditions' => array(
"Question.survey_id" => $survey_id /*dont use array() */
)
));
echo json_encode($info);
exit;
}
}
Here,In core.php there is a Routing.prefixes used as admin.
Configure::write('Routing.prefixes', array('admin','services'));
When I call this api
http://navyon.com/dev/mt/admin/android/survey_question?survey_id=2
then it redirects to the login page.
I need access api without login.So how can I resolve this problem?
To make accessible this method admin_survey_question without authentication, you need to allow it in beforeFilter
class AndroidController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('admin_survey_question');
}
public function admin_survey_question()
{
$this->loadModel('Question');
Configure::write('debug', '2');
$survey_id = $_REQUEST['survey_id'];
$this->layout = "";
//$condition = "Question.survey_id = '".$survey_id."'";
$this->Question->unbindModel(
array('hasMany' => array('Result'))
);
$info = $this->Question->find('all', array(
'fields' => array('Question.id,Question.question, Question.options'),
'conditions' => array(
"Question.survey_id" => $survey_id /*dont use array() */
)
));
echo json_encode($info);
exit;
}
}
See Docs

PHP Post Data Formatting

As per the Eventbrite API v3 documentation, the preferred way to submit the data is as JSON. I am attempting to update via ExtJS grid simple organizer data. The changes are not being processed.
The solution is in MODX and the updateFromGrid.class.php looks like this:
class UpdateOrganizerFromGridProcessor extends modProcessor {
public function initialize() {
$data = $this->getProperty('data');
if (empty($data)) return $this->modx->lexicon('invalid_data');
$data = $this->modx->fromJSON($data);
if (empty($data)) return $this->modx->lexicon('invalid_data');
$this->id = $data['id'];
$this->params = array ();
// build JSON content for form submission...cooking key names
$this->formData = array (
'organizer.name' => $data['name'],
'organizer.description.html' => $data['description'],
'organizer.logo.id' => $data['logo_id'],
);
$this->formJSON = $this->modx->toJSON($this->formData);
$this->args = array('id' => $this->id, 'params' => $this->params);
return parent::initialize();
}
public function process() {
// call to main class to save changes to the Eventbrite API
$this->mgr_client = new Ebents($this->modx);
$this->output = $this->mgr_client->postData('organizers', $this->args, $this->formJSON);
$response = json_decode(json_encode($this->output), true);
return $this->outputArray($response);
}
}
return 'UpdateOrganizerFromGridProcessor';
The json output from the above is:
{"organizer.name":"Joe Organizer","organizer.description":"Joe is the Uberest Organizer."}
And my post function is:
//send data to Eventbrite
function postData($method, $args, $JSONdata) {
error_log("JSON Payload : " . $JSONdata);
// Get the URI we need.
$uri = $this->build_uri($method, $args);
// Construct the full URL.
$request_url = $this->endpoint . $uri;
// This array is used to authenticate our request.
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n"
. "Accept: application/json\r\n",
'method' => 'POST',
'content' => $JSONdata,
'header' => "Authorization: Bearer " . $this->token
)
);
// Call the URL and get the data.
error_log("URL: " . $request_url);
error_log("Content: " . $options['http']['content']);
$resp = file_get_contents($request_url, false, stream_context_create($options));
// parse our response
if($resp){
$resp = json_decode( $resp );
if( isset( $resp->error ) && isset($resp->error->error_message) ){
error_log( $resp->error->error_message );
}
}
// Return it as arrays/objects.
return $resp;
}
function build_uri($method, $args) {
// Get variables from the $args.
extract($args);
// Get rid of the args array.
unset($args);
// Create an array of all the vars within this function scope.
// This should be at most 'method', 'id' and 'data'.
$vars = get_defined_vars();
unset($vars['params']);
// Put them together with a slash.
$uri = implode($vars, '/');
if (!empty($params)) {
return $uri ."?". http_build_query($params);
}
return $uri;
}
The post is working however there is no update to the data and the response back is the original data set. What am I missing here?
I figured it out. It was an issue with a missing slash right before the query string. I also removed the JSON data payload and am submitting as form encoded. The final class is below:
class UpdateOrganizerFromGridProcessor extends modProcessor {
public function initialize() {
$data = $this->getProperty('data');
if (empty($data)) return $this->modx->lexicon('invalid_data');
$data = $this->modx->fromJSON($data);
if (empty($data)) return $this->modx->lexicon('invalid_data');
$this->id = $data['id'];
$this->params = array (
'organizer.name' => $data['name'],
'organizer.description.html' => $data['description'],
'organizer.logo.id' => $data['logo_id'],
);
$this->args = array('id' => $this->id, 'data'=> '', 'params' => $this->params);
return parent::initialize();
}
public function process() {
// call to main class to save changes to the Eventbrite API
$this->mgr_client = new Ebents($this->modx);
$this->output = $this->mgr_client->postData('organizers', $this->args);
$response = json_decode(json_encode($this->output), true);
return $this->outputArray($response);
}
}
return 'UpdateOrganizerFromGridProcessor';

Codeigniter - How to send API data via URL and get the response immediately without redirect and form action

Below is my code:
$sourceaddr = 14045; // Sender ID
$destinationaddr = 08887654657; // Destination Address
$shortmessage = "Hi, this is test"; // Message
$url = http://xyz.li/cdk; //Short URL
And I send above data via below URL (provided by SMS Broadcast API)
// API for sending SMS
$sent_url = 'http://username:password#ip:port/smsgateway/infobulk?sourceaddr='.$sourceaddr.'&destinationaddr='.$destinationaddr.'&shortmessage='.urlencode($shortmessage).' '.urlencode($url).'';
And If the message received (success) by destination address, I will get this response:
<?xml version="1.0" encoding="iso-8859-1" ?>
<message>
<TrxID>13349105571516524200</TrxID>
<Status>SENT</Status>
</message>
How to do that in Codeigniter way?
I have try using redirect($sent_url) but it doesn't get any response,
It's a backend process, so I don't need any Form action, thank you.
MODEL
class Sms_model extends CI_Model {
var $source; //Source address
var $dest; //Destination
var $msg; // Message
var $url;
var $api_url;
function __construct() {
parent::__construct();
}
function Send(){
$this->api_url = 'http://username:password#ip:port/smsgateway/infobulk';
$params = $this->source.'&destinationaddr='.$this>dest.'&shortmessage='.urlencode($this->msg).' '.urlencode($this->url).'';
$post_data = array(
"sourceaddr" => $params,
);
$stream_options = array(
'http' => array(
'method' => 'POST',
),
);
$context = stream_context_create($stream_options);
$response = file_get_contents($this->api_url, null, $context);
return $response;
}
}
CONTROLLER
class Sms extends CI_Controller {
function __construct() {
parent::__construct();
}
function Index(){
$this->load->model('Sms_model','sms_m');
$this->sms_m->source = 14045 ;
$this->sms_m->dest = 08887654657;
$this->sms_m->msg = "Hi, this is test";
$this->sms_m->url = 'http://xyz.li/cdk';
$data = $this->sms_m->Send();
print_r($data);
}
}
This will work on CI. Cheers.

Categories