Guzzle HTTP request error - php

I am trying to send my form data from one domain to another domain using API with Guzzle HTTP.
But when I am sending any file field that time it gives me error.
My First server Code
$inputs = $request->all();
$scan_2 = 'user_scan_2_' . $request->file('fileToUpload')->getClientOriginalExtension();
$destination = base_path() . '/public/files/uploaded/user/temp/';
$request->file('fileToUpload')->move($destination, $scan_2);
$inputs['fileToUpload'] = $this->makeCurlFile($destination.'/'.$scan_2);
$response = Http::post('"http://msite.test/api/test', $inputs,$headers);
My Guzzle Code Over HTTP facade
public function send($method, $url, $data, $headers = ["Content-Type" => "application/json"]) {
$method = strtoupper($method);
$contentType = $headers['Content-Type'] ?? ($headers['content-type'] ?? '');
$requestData['headers'] = $headers;
if(in_array($method, ['GET', 'DELETE'])){
$requestData['query'] = $data;
}elseif(in_array($method, ['POST','PUT', 'PATCH'])){
switch(strtolower($contentType)){
case 'application/json':
$requestData['json'] = $data;
break;
case 'application/x-www-form-urlencoded':
$requestData['form_params'] = $data;
break;
case 'multipart/form-data':
$requestData['multipart'] = $data;
break;
default:
$requestData['body'] = $data;
break;
}
}
$response = $this->client->request($method, $url, $requestData);
return $response;
}
public function post($url, $data = [], $headers = ["Content-Type" => "application/json"]) {
return $this->send('post', $url, $data, $headers);
}
I am using content type as multipart/form-data
Now when I run my code that time got error
Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string given, called in

Related

How can I deactivate cookies used for authentication in php?

I would like to apologize in advance if this is a stupid question, but I am a junior developer starting a new job (and yes, very afraid of making a huge mistake). Most of my expertise is in Python, SQL, JavaScript, CSS and HTML. However, in my job I've been tasked with deactivating cookies in their website (they have to because of privacy laws in Europe). Some of the pages' backends are written in javascript and I was able to find the cookies and deactivate them, but some are written in php. I can tell what the code is and what it does, but since I've never dealt with php before, I'm not sure if I should just delete the script or if I should modify it in any way. Any help or advice will be greatly appreciated. This is the code (it is in its own file):
<?php
// Real-time Data Aggregation (RDA)
// error_reporting( E_ALL );
// ini_set('display_errors', 1);
class RDA {
private $session_cookie = '';
private $log_site = '';
private $config = array();
private $raw_payload = '';
private $payload = array();
private $publish_path_map = array();
public function __construct($config){
$this->config = $config;
}
public function process(){
$this->raw_payload = file_get_contents('php://input');
if(!$this->is_json($this->raw_payload)){
echo 'Expected payload was not provided. Script has been aborted.';
return;
}
$this->payload = json_decode($this->raw_payload);
if(array_key_exists('passed_through_rda', $this->payload) && $this->payload->passed_through_rda == 'true') return; // If this had previously passed through a RDA script so let's abort to prevent recursion.
if($this->is_test_payload()) return; // When the Test button is clicked from account settings simply echo back the payload and abort.
$this->send_next_webhook_request(); // forward payload to another webhook listener.
if($this->payload->finished != 'true') return; // we only want to react when the event has finished and not when it has been started.
$this->set_publish_path_map(); // sets up an index of publish paths to use as reference to prevent publish recursion.
foreach($this->config['actions'] as $action){
if(!$this->payload_contains_trigger_path($action)) continue; // payload does not contain trigger path so end execution.
$this->authenicate();
$this->publish($action);
}
$this->log_request();
}
private function authenicate(){
if($session_cookie != '') return; // session cookie was already created so exit authenication.
$endpoint = $this->config['ouc_base_url'] . '/authentication/login';
$config = array(
'skin' => $this->config['skin'],
'account' => $this->config['account'],
'username' => $this->config['username'],
'password' => $this->config['password']
);
$post_fields = http_build_query($config);
$cURLConnection = curl_init($endpoint);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURLConnection, CURLOPT_HEADER, true);
$api_response = curl_exec($cURLConnection);
$header = curl_getinfo( $cURLConnection );
curl_close($cURLConnection);
$header_content = substr($api_response, 0, $header['header_size']);
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$this->session_cookie = implode("; ", $matches['cookie']);
}
private function publish($action){
$endpoint = '/files/publish';
$config = array(
'site' => $action['site'],
'path' => $action['publish_path'],
'include_scheduled_publish' => 'true',
'include_checked_out' => 'true'
);
$this->log_site = $action['site']; // set a site to use to create log files if logging is turned on.
$this->send($endpoint, $config);
}
private function set_publish_path_map(){
foreach($this->config['actions'] as $action){
$this->publish_path_map[$action['site'] . $action['publish_path']] = 1;
}
}
private function log_request(){
if($this->config['log'] != 'true' || $this->log_site == '') return; // don't log when logging turned or if log_site not set
$log_id = uniqid();
$endpoint = '/files/save';
$config = array(
'site' => $this->log_site,
'path' => $this->config['config_file'], // uses the config PCF to do a "save as" to a log file
'new_path' => $this->get_root_relative_folderpath() . '_log/' . $log_id . '.txt',
'text' => $this->raw_payload
);
$this->send($endpoint, $config);
}
private function send_next_webhook_request(){
$next_webhook_url = trim($this->config['next_webhook_url']);
if($next_webhook_url == '') return; // next_webhook_url not entered so just return.
$this->payload->passed_through_rda = 'true';
$connection = curl_init($next_webhook_url);
curl_setopt($connection, CURLOPT_POSTFIELDS, json_encode($this->payload, JSON_UNESCAPED_SLASHES));
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
$api_response = curl_exec($connection);
curl_close($connection);
}
private function send($endpoint, $config){
$endpoint = $this->config['ouc_base_url'] . $endpoint;
$post_fields = http_build_query($config);
$connection = curl_init($endpoint);
curl_setopt($connection, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($connection, CURLOPT_COOKIE, $this->session_cookie);
$api_response = curl_exec($connection);
curl_close($connection);
}
private function payload_contains_trigger_path($action){
$site = $action['site'];
$success = array(); // the success node in the webhook payload contains files that were published.
if(!array_key_exists($site, $this->payload->success)) return false; // no success array so just return false.
$success = $this->payload->success->{$site};
$published_paths = array();
foreach($success as $i){
if(!array_key_exists($site . $i->path, $this->publish_path_map)) $published_paths[] = $i->path; // only include paths that aren't also publish targets configured in this script to avoid publish recursion.
}
$trigger_paths = $action['trigger_path'];
$trigger_paths = explode(',', $trigger_paths);
foreach($trigger_paths as $trigger_path){
$trigger_path = trim($trigger_path);
$trigger_path = preg_replace('/(.)[\/]+$/', '$1', $trigger_path); // removes trailing slash unless the value is the string length is 1, for instance: '/'
if($trigger_path == '') continue;
foreach($published_paths as $path){
if($this->starts_with($path, $trigger_path)) return true;
}
}
return false;
}
private function is_test_payload(){
$account = $this->payload->account;
if($account == '<account name>'){ // This is the account name value used by the test http request.
echo $this->raw_payload;
return true;
}
return false;
}
private function is_json($string){
if(trim($string) == '') return false;
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
private function starts_with($string, $startString){
$len = strlen($startString);
return (substr($string, 0, $len) === $startString);
}
private function get_root_relative_folderpath(){
$result = $this->get_root_relative_filepath();
$result = str_replace('\\', '/', $result);
$result = preg_replace('/[^\/]+$/', '', $result);
return $result;
}
private function get_root_relative_filepath(){
$result = str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME']);
return $result;
}
}
?>
For clarification: they have a service that manages cookies and they were able to turn those off, but there are a number of cookies that are persisting, and they are being generated by scripts leftover from years ago (I have no idea who wrote this code, or how old it is) and they need to be deleted. I just want to make sure that if I delete something it won't cause other bugs on the website
Method to close all the cookies and sessions
i think you have start the sessions session_start()
session_start();
you can read the documentation here
//http://php.net/manual/en/function.setcookie.php#73484
To destory and close the sessions try the code below
the below method will help to unset the cookies serving in your php program
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
session_destroy();

Sending Image via Telegram-Bot API with PHP

I have this function
function suspendido($chat_id,$foo)
{
$TOKEN = "blablalbal";
$TELEGRAM = "https://api.telegram.org:443/bot$TOKEN";
$url. = "https://zrabogados-pruebas.xyz/bot/404.png";
$query = http_build_query(array(
'chat_id'=> $chat_id,
'photo'=> $url,
'text'=> $foo,
'parse_mode'=> "HTML", // Optional: Markdown | HTML
));
$response = file_get_contents("$TELEGRAM/sendMessage?$query");
return $response;
}
I try to sending an Image without using curl, tried to use file_get_contents but nothing works. Is something missing?.
Apparently, there is some problem with telegram servers.
If you put some image attributes into url it works.
function suspendido($chat_id,$foo)
{
$TOKEN = "blablalbla";
$TELEGRAM = "https://api.telegram.org:443/bot$TOKEN";
$url = "https://zrabogados-pruebas.xyz/bot/404.png?center=140.50,36.15&width=1024&height=576";
$query = http_build_query(array(
'chat_id'=> $chat_id,
'photo'=> $url,
'text'=> $foo,
'parse_mode'=> "HTML", // Optional: Markdown | HTML
));
$response = file_get_contents("$TELEGRAM/sendMessage?$query");
return $response;
}
I know its just silly but it works that way if you send the image url without this then you will receive a 400 error.
You used sendMessage method, And this method isn't accept photo parameter.
And $url shouldn't be concatenated with another link.
To send photo use sendPhoto method like this:
<?php
function suspendido($chat_id, $url, $foo)
{
$TOKEN = "<bot_token>";
$TELEGRAM = "https://api.telegram.org:443/bot$TOKEN";
$url = "https://zrabogados-pruebas.xyz/bot/404.png";
$query = http_build_query(array(
'chat_id'=> $chat_id,
'photo'=> $url,
'text'=> $foo,
'parse_mode'=> 'HTML' // Optional: Markdown | HTML
));
# Use sendPhoto here, Not sendMessage
$response = file_get_contents("$TELEGRAM/sendPhoto?$query");
return $response;
}

Phonegap Build API with CURL php

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,

Post request cakephp

I'm trying to send a post request that header is json and the response also is json. What i have tried so far. This always return a status code 400. what i'm doing wrong?Thanks
private function requestPOST($url,$data)
{
App::uses('HttpSocket', 'Network/Http');
App::uses('Json', 'Utility');
$this->layout = 'default';
$this->autoRender = true;
$HttpSocket = new HttpSocket();
$jsonData = json_encode($data);
$request = array('header' => array('Content-Type' => 'application/json'));
debug($url);
$response = $HttpSocket->post($url, $jsonData, $request);
debug($response->code);
//$this->render('index');
$jsonString = json_decode($response['body'], true);
debug($jsonString);
return $jsonString;
}
I have solved myself. I was doing twice json_encode of the $data.

PHP PROXY having tough time for "POST" Data but able to use GET

http://benalman.com/code/projects/php-simple-proxy/examples/simple/
I am exactly following above Blog for Using PHP Proxy setting for Cross Domain. I am using XHR. I am able to successful to use GET method. But While using POST I am getting error CODE 200 and Empty XML in reply object.
However when i am using the simple XHR Code without phpproxy with below setting of google. chrome.exe --disable-web-security. I am successful for GET and POST both.
I am sure i am wrong somewhere in XHR.Send(Mydata). But if i was wrong in this method than i could not have been able to send success full post method.
Please help. I am novice in PHP i am sure i am missing something in PHP code that would enable me to post successfull. Below is crux of PHP code.
$enable_jsonp = true;
$enable_native = false;
$valid_url_regex = '/.*/';
$url = $_GET['url'];
if (!$url)
{
// Passed url not specified.
$contents = 'ERROR: url not specified';
$status = array(
'http_code' => 'ERROR'
);
}
else if (!preg_match($valid_url_regex, $url)) {
// Passed url doesn't match $valid_url_regex.
$contents = 'ERROR: invalid url';
$status = array(
'http_code' => 'ERROR'
);
}
else
{
$ch = curl_init($url);
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
}
if ($_GET['send_cookies'])
{
$cookie = array();
foreach ($_COOKIE as $key => $value)
{
$cookie[] = $key . '=' . $value;
}
if ($_GET['send_session'])
{
$cookie[] = SID;
}
$cookie = implode('; ', $cookie);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_GET['user_agent'] ? $_GET['user_agent'] : $_SERVER['HTTP_USER_AGENT']);
list($header, $contents) = preg_split('/([\r\n][\r\n])\\1/', curl_exec($ch), 2);
$status = curl_getinfo($ch);
curl_close($ch);
}
// Split header text into an array.
$header_text = preg_split('/[\r\n]+/', $header);
if ($_GET['mode'] == 'native')
{
if (!$enable_native)
{
$contents = 'ERROR: invalid mode';
$status = array(
'http_code' => 'ERROR'
);
}
// Propagate headers to response.
foreach ($header_text as $header)
{
if (preg_match('/^(?:Content-Type|Content-Language|Set-Cookie):/i', $header))
{
header($header);
}
}
print $contents;
}
else
{
// $data will be serialized into JSON data.
$data = array();
// Propagate all HTTP headers into the JSON data object.
if ($_GET['full_headers'])
{
$data['headers'] = array();
foreach ($header_text as $header)
{
preg_match('/^(.+?):\s+(.*)$/', $header, $matches);
if ($matches)
{
$data['headers'][$matches[1]] = $matches[2];
}
}
}
// Propagate all cURL request / response info to the JSON data object.
if ($_GET['full_status'])
{
$data['status'] = $status;
}
else
{
$data['status'] = array();
$data['status']['http_code'] = $status['http_code'];
}
// Set the JSON data object contents, decoding it from JSON if possible.
$decoded_json = json_decode($contents);
$data['contents'] = $decoded_json ? $decoded_json : $contents;
// Generate appropriate content-type header.
$is_xhr = strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
header('Content-type: application/' . ($is_xhr ? 'json' : 'x-javascript'));
// Get JSONP callback.
$jsonp_callback = $enable_jsonp && isset($_GET['callback']) ? $_GET['callback'] : null;
// Generate JSON/JSONP string`enter code here`
$json = json_encode($data);
print $jsonp_callback ? "$jsonp_callback($json)" : $json;
}

Categories