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);
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 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;
}
}
I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz
I have cobbled together a class that checks links. It works but it is slow:
The class basically parses a HTML string and returns all invalid links for href and src attributes. Here is how I use it:
$class = new Validurl(array('html' => file_get_contents('http://google.com')));
$invalid_links = $class->check_links();
print_r($invalid_links);
With HTML that has a lot of links it becomes really slow and I know it has to go through each link and follow it, but maybe someone with more experience can give me a few pointers on how to speed it up.
Here's the code:
class Validurl{
private $html = '';
public function __construct($params){
$this->html = $params['html'];
}
public function check_links(){
$invalid_links = array();
$all_links = $this->get_links();
foreach($all_links as $link){
if(!$this->is_valid_url($link['url'])){
array_push($invalid_links, $link);
}
}
return $invalid_links;
}
private function get_links() {
$xml = new DOMDocument();
#$xml->loadHTML($this->html);
$links = array();
foreach($xml->getElementsByTagName('a') as $link) {
$links[] = array('type' => 'url', 'url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
}
foreach($xml->getElementsByTagName('img') as $link) {
$links[] = array('type' => 'img', 'url' => $link->getAttribute('src'));
}
return $links;
}
private function is_valid_url($url){
if ((strpos($url, "http")) === false) $url = "http://" . $url;
if (is_array(#get_headers($url))){
return true;
}else{
return false;
}
}
}
First of all I would not push the links and images into an array, and then iterate through the array, when you could directly iterate the results of getElementsByTagName(). You'd have to do it twice for <a> and <img> tags, but if you separate the checking logic into a function, you just call that for each round.
Second, get_headers() is slow, based on comments from the PHP manual page. You should rather use cUrl in some way like this (found in a comment on the same page):
function get_headers_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$r = curl_exec($ch);
$r = split("\n", $r);
return $r;
}
UPDATE: and yes, some kind of caching could also help, e.g. an SQLITE database with one table for the link and the result, and you could purge that db like each day.
You could cache the results (in DB, eg: a key-value store), so that your validator assumes that if a link was valid it's going to be valid for 24 hours or a week or something like that.