PHP PEAR HTTP PUT - php

I've got problems with PHP PEAR and HTTP PUT. I want to create a HTTP PUT request and attach a file to it and send it to a REST service. Here's my current code:
require_once ('includes/HTTP_Request/Request.php');
$url = 'http://myurl.com/';
$req =& new HTTP_Request();
$req->setMethod(HTTP_REQUEST_METHOD_PUT);
$req->setURL($url);
$req->addHeader('Content-type', 'multipart/form-data');
$tmp_file = 'temp.rdf';
$result = $req->addFile('metadata', $tmp_file, 'text/xml');
if (PEAR::isError($result))
{
echo $result->getMessage();
}
$response = $req->sendRequest();
if (PEAR::isError($response)) {
echo $response->getMessage();
} else {
echo $req->getResponseBody();
}
This code should work correctly, but obviously is doesn't. I always get the respond by the REST repository that the header doesn't contain multipart/form-data.
Does anyone know what I can do to get the code to work? Thanks in anticipation!

Use setBody( string $body) instead of addFile.
Sets the request body (for POST, PUT
and similar requests)

Related

Get a Soap request

Let me explain, I am doing something like a webservice in which I get information from a platform called Wialon, they use a section called repeaters where they send me a SOAP request to a specific address, I will be honest I have no idea how to use SOAP i never did something like this, so my question is how can i receive that SOAP data in PHP, so I can see it, I want to receive that SOAP request and i don't know save it in DB to see how it works or the structure, because these guys of wialon do not give information about what they send in that soap but I imagine it is an xml, so far I have tried to investigate but the truth is I do not know how soap works, im using this code that I found:
class MyClass {
public function helloWorld() {
require_once 'com.sine.controlador/Controlador.php';
$c = new Controlador();
$xml = $c->insertarResultado('06',func_get_args());
return 'Hello Welt ' . print_r(func_get_args(), true);
}
}
try {
$server = new SOAPServer(
NULL, array(
'uri' => 'http://localhost/WebserviceGLMS2/index.php'
)
);
$server->setClass('MyClass');
$server->handle();
} catch (SOAPFault $f) {
print $f->faultstring;
}
but it doesn't seem to work, hope you can help me, thanks
A soap request is nothing else than a xml post request. In PHP you can get the whole request body with the following code.
<?php
$content = file_get_contents('php://input');
var_dump($content);
You can use this unless it 's not multipart/formdata.

ZF2 - how to correctly set headers?

I have problem with setting headers in ZF2. My code looks like this:
public function xmlAction()
{
$headers = new \Zend\Http\Headers();
$headers->clearHeaders();
$headers->addHeaderLine('Content-type', 'application/xml');
echo $file; // xml file content
exit;
}
But headers are still text/html. I can set the proper header with:
header("Content-type: application/xml");
but I would like to do it with Zend Framework. Why code above doesn't work?
What you are doing is setting headers in a ZF2 Response object, but this response is later on never used. You are echoing a file and then exiting, so there is no chance for ZF2 to send the response (with its headers).
You have to use the response to send the file, which you can do like this:
public function xmlAction()
{
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Content-Type', 'application/xml');
$response->setContent($file);
return $response;
}
The idea of returning the response from a controller method is called "short circuiting" and is explained in the manual
Try -
public function xmlAction()
{
$this->getResponse()->getHeaders()->addHeaders(array('Content-type' => 'application/xml'));
echo $file; // xml file content
exit;
}

Instagram API: Get All User Media API and Store to File

I know the way to get all user media in instagram api with pagination. And we must request again with pagination url provided to get next photos.
I just wonder if i can save all of json api response include with next photos in pagination to one flat file for caching. The purpose is i can call all photos value from one file only, e.g: cache.json.
Is there a way to realize that in PHP Code if possible? Like using file_get and file_put function. Any help is appreciated so much :)
Here's my code, but need a tweak to fix it. Im using this wrapper https://github.com/cosenary/Instagram-PHP-API
require 'instagram.class.php';
$cache = './cache.json';
$instagram = new Instagram($accessToken);
$instagram->setAccessToken($accessToken);
$response = $instagram->getUserMedia($userID,$settings['count']);
do {
if($response){
file_put_contents($cache,json_encode($response)); //Save as json
}
} while ($response = $instagram->pagination($response));
echo 'finish';
With this code i getting the last pagination only. It seems the code overwrite the cache.json file, not adding.
Maybe you can suggest me how to fix it become adding, not overwriting.
-- Edit --
My code now working but not perfect, maybe you can try and fix it.
<?php
include('conf.php');
require 'instagram.class.php';
$cache = './cache_coba.json';
$instagram = new Instagram($accessToken);
$instagram->setAccessToken($accessToken);
$response = $instagram->getUserMedia($userID,$settings['count']);
while ($response = $instagram->pagination($response)) {
if($response){
$opn = file_get_contents($cache);
$opn .= json_encode($response);
file_put_contents($cache, $opn);
}
}
echo 'finish';
?>

PHP webservice request and response

I'm using PHP 5.3, and trying to develop a simple web service that gets some parameters with POST method and has a response.
function start(){
getAndValidateParams();
global $response;
echo json_encode($response);
}
function getAndValidateParams(){
// token (mandatory)
if(isset($_POST[PARAM_TOKEN])){
echo 'got your token';
}else{
$response[ERROR_CODE] = ERR2_INVALID_TOKEN;
$response[DESCRIPTION] = CODE2_DESC;
}
}
I'm trying to test that with Postman:
The problems:
1. About the Xdebug HTML I saw the following question, If I turn the var_dump off, will it disable usage of var_dump() inside my php code? (I want to be able use it for debugging but not seeing that in the response).
2.Also I have a problem to pass the parameter 'token', I don't see it in getAndValidateParams().
Any help will be appreciated.
I have used your function to just get insight in this and for tesing you can use also there is Advanced REST client in chrome similar to postMAN that you are using --
use the below lines to debug this --
function start(){
$response = getAndValidateParams();
return json_encode($response);
}
// calling function ends here
// statrt another function that is being called
function getAndValidateParams(){
// token (mandatory)
// print_r($_POST);die; // just for debug purpose
if(isset($_POST[PARAM_TOKEN])){
$response[ERROR_CODE] = 0;
$response[DESCRIPTION] = "Success";
$response[DEtail] = $yourdetailarr; // array of data that you want to retuen
}else{
$response[ERROR_CODE] = ERR2_INVALID_TOKEN;
$response[DESCRIPTION] = CODE2_DESC;
}
return $response;
}
/// ends here
check the response here by calling start function .

PHP get data from DELETE request

I am using jquery plugin for multiple file upload. Everything is working fine, except delete the images. Firebug say that JS it is sending DELETE request to the function. How can I get data from delete request?
PHP delete code:
public function deleteImage() {
//Get the name in the url
$file = $this->uri->segment(3);
$r = $this->session->userdata('id_user');
$q=$this->caffe_model->caffe_get_one_user($r);
$cff_name= $q->name;
$cff_id = $q->id_caffe;
$w = $this->gallery_model->gallery_get_one_user($gll_id);
$gll_name = $w->name;
$success = unlink("./public/img/caffe/$cff_name/$gll_name/" . $file);
$success_th = unlink("./public/img/caffe/$cff_name/$gll_name/thumbnails/" . $file);
//info to see if it is doing what it is supposed to
$info = new stdClass();
$info->sucess = $success;
$info->path = $this->getPath_url_img_upload_folder() . $file;
$info->file = is_file($this->getPath_img_upload_folder() . $file);
if (IS_AJAX) {//I don't think it matters if this is set but good for error checking in the console/firebug
echo json_encode(array($info));
} else { //here you will need to decide what you want to show for a successful delete
var_dump($file);
}
}
and JS is using jQuery-File-Upload plugin: link
Generally, if the DELETE request sends data in the request body, you can read the data by using the following code:
$data = file_get_contents("php://input");
Depending on the encoding of the data (usually JSON or form-encoded), you use json_decode or parse_str to read the data into usable variables.
For a simple example, see this article, where the author uses form-encoded data to handle a PUT request. DELETE works similarly.
In your case however, it looks like the file name is read from the request URL (the call to $this->uri->segment(3);). When I look at your code, it seems that the variable $gll_id is not initailized and you don't check if the resulting object $w and the variable $gll_name are empty. Maybe this is causing the delete to fail. Turn on error logging with ini_set("log_errors",1); and have a look at your server error log. If the unlink fails, the error log should contain the path PHP tried to unlink - it's likely that the path is not correct.

Categories