I want to create function which will execute other url (this url generate file on server) and get responce and then send message to user, but I want not to use ajax, I try to user Reqeust object but it don't work.
public function testCreateFile() {
$uri = 'http://someuri/somefuncition';
$method = 'POST';
$paramaters = array(
'csv' => '20190102212655-product-test.csv',
'type' => '5',
);
$request = new Request();
$request->create($uri,$method,$paramaters);
return new Response("Message to user") ;
}
How I should do coreectly?
Thanks for help in advance.
What you need is curl.
The best way is to use bellow code as Service, so I'll give the complete Class
The Service class
<?php
App\Services;
class PostRequest
{
static function get_data(String $url, Array $post_parameters)
{
//url-ify the data for the POST
$parameters_string = "";
foreach($post_parameters as $key=>$value) {
$parameters .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POST, count($post_parameters));
curl_setopt($ch,CURLOPT_POSTFIELDS, $parameters);
//execute post
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
?>
So after including use App\Services\PostRequest; inside your Controller, you can do this
public function testCreateFile() {
$uri = 'http://someuri/somefuncition';
$paramaters = [
'csv' => '20190102212655-product-test.csv',
'type' => '5',
];
$request = PostRequest::get_data($uri, $paramaters);
return new Response("Message to user") ;
}
Related
I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);
I'm trying to connect my account with PHONEGAP REST API by implementing CURL with laravel framework. Somehow I could do things with GET but never done with POST and PUT. Is there anything wrong with my code? here's my example for uploading:
App\Http\Controllers\BuildApiController#testBuild:
use...
public function testBuild(Request $request)
{
$build = new PgBuild('myemail#test.us','mypassword');
$title = $request->title;
$file = $request->file;
$method = 'file';
$data = $build->uploadApp($file, $title, $method);
return response()->json($data);
}
App\PgBuild#uploadApp:
public function uploadApp($file, $title, $createMethod) {
$link = "https://build.phonegap.com/api/v1/apps";
CURL_SETOPT($this->ch, CURLOPT_POST, 1);
CURL_SETOPT($this->ch, CURLOPT_URL, $link);
$post = array(
"data" => array('create_method' => $createMethod, 'title' => $title),
"file" => $file
);
CURL_SETOPT($this->ch, CURLOPT_POSTFIELDS, $post);
$output = curl_exec($this->ch);
$obj = json_decode($output);
if (is_object($obj) && isset($obj->id)) {
return json_encode($obj->id);
} else {
return false;
}
}
Thank you,
I am using a rest api in yii2 with Authorization : Bearer and my update action requires sending data using PUT. I have configured the actionUpdate completely but somehow i am not getting any data in Request PUT.
I found few articles online about problems with Yii2 PUT but could not find out weather there is any solution to that yet or not?
One of the article or issue is github issue and it points to this github issue
Ad if no solution yet than what alternative should i use for Update action.
Here is my actionUpdate code
public function actionUpdate($id)
{
$params = Yii::$app->request->bodyParams;
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id' => Yii::$app->user->id])->one();
if($model !== null){
$model->load($params, '');
$model->partner_id = Yii::$app->user->id;
$model->updated_date = time();
if ($model->save()) {
$this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>array_filter($model->attributes)),JSON_PRETTY_PRINT);
}
}
}
This is a screenshot of debug screen. See the event_name attribute.
That was screenshot after the execution of $model->load($params,'') line.
I am calling the service like following and not able to Update the data properly. My service works fine through postman.So i guess i am missing something in CURL request.
$service_url = 'http://localhost/site-api/api/web/v1/events/'.$eventDetailDBI->gv ('id');
$curl = curl_init($service_url);
$curl_post_data = array(
"event_name" => $eventDetailDBI->gv ('name'),
);
$header = array();
$header[] = 'Authorization: Bearer 4p9mj82PTl1BWSya7bfpU_Nm';
$header[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
curl_setopt($curl, CURLOPT_PUT, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
$json = json_decode($curl_response, true);
curl_close($curl);
I am getting correct data in my POST fields and passing correct data but the service doesnt update any data.
Thank you
try this:
public function actionUpdate($id)
{
// this will get what you did send as application/x-www-form-urlencoded params
// note that if you are sending data as query params you can use Yii::$app->request->queryParams instead.
$params = Yii::$app->request->bodyParams;
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id' => Yii::$app->user->id])->one();
if($model !== null){
// This will load data to your safe attribute as defined in your model rules using your default scenario.
$model->load($params, '');
$model->partner_id = Yii::$app->user->id;
$model->updated_date = time();
if ($model->save()) {
/*
you can use Yii::$app->getResponse()->setStatusCode(200) here but no need to do that.
response will be 200 by default as you are returning data.
*/
// yii\rest\Serializer will take care here of encoding model's related attributes.
return [
'status' => 1,
'data' => $model
];
}
else {
// when validation fails. you model instance will hold error messages and response will be auto set to 422.
return $model;
}
}
}
I'm currently working on some automatization script in PHP (No HTML!).
I have two PHP files. One is executing the script, and another one receive $_POST data and returns information.
The question is how from one PHP script to send POST to another PHP script, get return variables and continue working on that first script without HTML form and no redirects.
I need to make requests a couple of times from first PHP file to another under different conditions and return different type of data, depending on request.
I have something like this:
<?php // action.php (first PHP script)
/*
doing some stuff
*/
$data = sendPost('get_info');// send POST to getinfo.php with attribute ['get_info'] and return data from another file
$mysqli->query("INSERT INTO domains (id, name, address, email)
VALUES('".$data['id']."', '".$data['name']."', '".$data['address']."', '".$data['email']."')") or die(mysqli_error($mysqli));
/*
continue doing some stuff
*/
$data2 = sendPost('what_is_the_time');// send POST to getinfo.php with attribute ['what_is_the_time'] and return time data from another file
sendPost('get_info' or 'what_is_the_time'){
//do post with desired attribute
return $data; }
?>
I think i need some function that will be called with an attribute, sending post request and returning data based on request.
And the second PHP file:
<?php // getinfo.php (another PHP script)
if($_POST['get_info']){
//do some actions
$data = anotherFunction();
return $data;
}
if($_POST['what_is_the_time']){
$time = time();
return $time;
}
function anotherFunction(){
//do some stuff
return $result;
}
?>
Thanks in advance guys.
Update: OK. the curl method is fetching the output of php file. How to just return a $data variable instead of whole output?
You should use curl. your function will be like this:
function sendPost($data) {
$ch = curl_init();
// you should put here url of your getinfo.php script
curl_setopt($ch, CURLOPT_URL, "getinfo.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
Then you should call it this way:
$data = sendPost( array('get_info'=>1) );
I will give you some example class , In the below example you can use this as a get and also post call as well. I hope this will help you.!
/*
for your reference . Please provide argument like this,
$requestBody = array(
'action' => $_POST['action'],
'method'=> $_POST['method'],
'amount'=> $_POST['amount'],
'description'=> $_POST['description']
);
$http = "http://localhost/test-folder/source/signup.php";
$resp = Curl::postAuth($http,$requestBody);
*/
class Curl {
// without header
public static function post($http,$requestBody){
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $http ,
CURLOPT_USERAGENT => 'From Front End',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $requestBody
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
// with authorization header
public static function postAuth($http,$requestBody,$token){
if(!isset($token)){
$resposne = new stdClass();
$resposne->code = 400;
$resposne-> message = "auth not found";
return json_encode($resposne);
}
$curl = curl_init();
$headers = array(
'auth-token: '.$token,
);
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_HTTPHEADER => $headers ,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $http ,
CURLOPT_USERAGENT => 'From Front End',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $requestBody
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
}
Any idea how one would update a user's Twitter status with an image - using the Twitter-Async class?
This is what I have
$twitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET,$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
$array = array('media[]' => '#/img/1.jpg','status' => $status);
$twitter->post('/statuses/update_with_media.json', $array);
With thanks to #billythekid, I have managed to do this. This is what you need to do:
Look these functions up in the EpiOAuth file and see what I've added and alter it where necessary.
EpiOAuth.php
//I have this on line 24
protected $mediaUrl = 'https://upload.twitter.com';
//and altered getApiUrl() to include check for such (you may wish to make this a regex in keeping with the rest?)
private function getApiUrl($endpoint)
{
if(strpos($endpoint,"with_media") > 0)
return "{$this->mediaUrl}/{$this->apiVersion}{$endpoint}";
elseif(preg_match('#^/(trends|search)[./]?(?=(json|daily|current|weekly))#', $endpoint))
return "{$this->searchUrl}{$endpoint}";
elseif(!empty($this->apiVersion))
return "{$this->apiVersionedUrl}/{$this->apiVersion}{$endpoint}";
else
return "{$this->apiUrl}{$endpoint}";
}
// add urldecode if post is multiPart (otherwise tweet is encoded)
protected function httpPost($url, $params = null, $isMultipart)
{
$this->addDefaultHeaders($url, $params['oauth']);
$ch = $this->curlInit($url);
curl_setopt($ch, CURLOPT_POST, 1);
// php's curl extension automatically sets the content type
// based on whether the params are in string or array form
if ($isMultipart) {
$params['request']['status'] = urldecode($params['request']['status']);
}
if($isMultipart)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params['request']);
else
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->buildHttpQueryRaw($params['request']));
$resp = $this->executeCurl($ch);
$this->emptyHeaders();
return $resp;
}
Post image
// how to post image
$twitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET,$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
$array = array('#media[]' => '#/img/1.jpg','status' => $status);
$twitter->post('/statuses/update_with_media.json', $array);