I create a rest-webservice with the php framework "tonic".
I have a User Class and handle it with the library.
According to CRUD i use HTTP_PUT to UPDATE the User:
function put($request) {
$response = new Response($request);
$split = explode ('&',$request);
$para = array();
foreach($split as $i) {
$names = explode('=',$i);
$para[$names[0]] = $names[1];
}
$response->body = var_dump($para);
return $response;
}
My Question is how do I access the calling parameters?
At the moment I parse it manually into an array.
PHP will not translate a classic "application/x-www-form-urlencoded" request into $_POST / $_GET if the method is PUT (and there is no $_PUT).
So if you use this content type you have to parse the query string manually:
<?php
$putdata = fopen("php://input", "r");
$para = parse_str($putdata);
http://www.php.net/manual/en/features.file-upload.put-method.php
Related
In magento as we use the rest url to access the data, as http://localhost/magento/api/rest/products it returns in xml format instead of that I need JSON.
I have tried below code, but no use
$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody($jsonData);
in the folder \magento\app\code\core\Mage\Api\Controller\Action.php
vinox, you should override the default file Request.php. copy \app\code\core\Mage\Api2\Model\Request.php to your local directory and add the following code just before end of the getAcceptTypes() Method.
unset($orderedTypes);
$orderedTypes=Array("application/json" => 1);
in other way your getAcceptTypes() method should look like this.
public function getAcceptTypes(){
$qualityToTypes = array();
$orderedTypes = array();
foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
$typeWithQ = explode(';', $definition);
$mimeType = trim(array_shift($typeWithQ));
// check MIME type validity
if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
continue;
}
$quality = '1.0'; // default value for quality
if ($typeWithQ) {
$qAndValue = explode('=', $typeWithQ[0]);
if (2 == count($qAndValue)) {
$quality = $qAndValue[1];
}
}
$qualityToTypes[$quality][$mimeType] = true;
}
krsort($qualityToTypes);
foreach ($qualityToTypes as $typeList) {
$orderedTypes += $typeList;
}
unset($orderedTypes);
$orderedTypes=Array("application/json" => 1);
return array_keys($orderedTypes);
}
I guess your $jsonData is not actually JSON. Try using a json helper
$jsonData = Mage::helper('core')->jsonEncode($data)
My php project is using the reddit JSON api to grab the title of the current page's submission.
Right now I am doing running some code every time the page is loaded and I'm running in to some problems, even though there is no real API limit.
I would like to store the title of the submission locally somehow. Can you recommend the best way to do this? The site is running on appfog. What would you recommend?
This is my current code:
<?php
/* settings */
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$reddit_url = 'http://www.reddit.com/api/info.{format}?url='.$url;
$format = 'json'; //use XML if you'd like...JSON FTW!
$title = '';
/* action */
$content = get_url(str_replace('{format}',$format,$reddit_url)); //again, can be xml or json
if($content) {
if($format == 'json') {
$json = json_decode($content,true);
foreach($json['data']['children'] as $child) { // we want all children for this example
$title= $child['data']['title'];
}
}
}
/* output */
/* utility function: go get it! */
function get_url($url) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
Thanks!
Introduction
Here is a modified version of your code
$url = "http://stackoverflow.com/";
$loader = new Loader();
$loader->parse($url);
printf("<h4>New List : %d</h4>", count($loader));
printf("<ul>");
foreach ( $loader as $content ) {
printf("<li>%s</li>", $content['title']);
}
printf("</ul>");
Output
New List : 7New podcast from Joel Spolsky and Jeff Atwood. Good site for example code/ Pyhtonstackoverflow.com has clearly the best Web code ever conceived in the history of the Internet and reddit should better start copying it.A reddit-like, OpenID using website for programmersGreat developer site. Get your questions answered and by someone who knows.Stack Overflow launched into publicStack Overflow, a programming Q & A site. & Reddit could learn a lot from their interface!
Simple Demo
The Problem
I see some things you want to achieve here namely
I would like to store the title of the submission locally somehow
Right now I am doing running some code every time the page is loaded
From what i understand you need is a simple cache copy of your data so that you don't have to load the url all the time.
Simple Solution
A simple cache system you can use is memcache ..
Example A
$url = "http://stackoverflow.com/";
// Start cache
$m = new Memcache();
$m->addserver("localhost");
$cache = $m->get(sha1($url));
if ($cache) {
// Use cache copy
$loader = $cache;
printf("<h2>Cache List: %d</h2>", count($loader));
} else {
// Start a new Loader
$loader = new Loader();
$loader->parse($url);
printf("<h2>New List : %d</h2>", count($loader));
$m->set(sha1($url), $loader);
}
// Oupput all listing
printf("<ul>");
foreach ( $loader as $content ) {
printf("<li>%s</li>", $content['title']);
}
printf("</ul>");
Example B
You can use Last Modification Date as the cache key as so that you would only save new copy only if the document is modified
$headers = get_headers(sprintf("http://www.reddit.com/api/info.json?url=%s",$url), true);
$time = strtotime($headers['Date']); // get last modification date
$cache = $m->get($time);
if ($cache) {
$loader = $cache;
}
Since your class implements JsonSerializable you can json encode your result and also store in a Database like MongoDB or MySQL
$data = json_encode($loader);
// Save to DB
Class Used
class Loader implements IteratorAggregate, Countable, JsonSerializable {
private $request = "http://www.reddit.com/api/info.json?url=%s";
private $data = array();
private $total;
function parse($url) {
$content = json_decode($this->getContent(sprintf($this->request, $url)), true);
$this->data = array_map(function ($v) {
return $v['data'];
}, $content['data']['children']);
$this->total = count($this->data);
}
public function getIterator() {
return new ArrayIterator($this->data);
}
public function count() {
return $this->total;
}
public function getType() {
return $this->type;
}
public function jsonSerialize() {
return $this->data;
}
function getContent($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
}
I'm not sure what your question is exactly but the first thing that pops is the following:
foreach($json['data']['children'] as $child) { // we want all children for this example
$title= $child['data']['title'];
}
Are you sure you want to overwrite $title? In effect, that will only hold the last $child title.
Now, to your question. I assume you're looking for some kind of mechanism to cache the contents of the requested URL so you don't have to re-issue the request every time, am I right? I don't have any experience with appFog, only with orchestra.io but I believe they have the same restrictions regarding writing to files, as in you can only write to temporary files.
My suggestion would be to cache the (processed) response in either:
APC shared memory with a short TTL
temporary files
database
You could use the hash of the URL + arguments as the lookup key, doing this check inside get_url() would mean you wouldn't need to change any other part of your code and it would only take ~3 LOC.
After this:
if($format == 'json') {
$json = json_decode($content,true);
foreach($json['data']['children'] as $child) { // we want all children for this example
$title = $child['data']['title'];
}
}
}`
Then store in a json file and dump it into your localfolder website path
$storeTitle = array('title'=>$title)
$fp = fopen('../pathToJsonFile/title.json'), 'w');
fwrite($fp, json_encode($storeTitle));
fclose($fp);
Then you can always call the json file next time and decode it and extract the title into a variable for use
i usually just store the data as is as a flat file, like so:
<?php
define('TEMP_DIR', 'temp/');
define('TEMP_AGE', 3600);
function getinfo($url) {
$temp = TEMP_DIR . urlencode($url) . '.json';
if(!file_exists($temp) OR time() - filemtime($temp) > TEMP_AGE) {
$info = "http://www.reddit.com/api/info.json?url=$url";
$json = file_get_contents($info);
file_put_contents($temp, $json);
}
else {
$json = file_get_contents($temp);
}
$json = json_decode($json, true);
$titles = array();
foreach($json['data']['children'] as $child) {
$titles[] = $child['data']['title'];
}
return $titles;
}
$test = getinfo('http://imgur.com/');
print_r($test);
PS.
i use file_get_contents to get the json data, you might have your own reasons to use curl.
also i don't check for format, cos clearly you prefer json.
I want to retrieve array value.
This is my array value:
overlay.txt:
{"title":"sss","description":"sss","code":"sss"}
{"title":"trtr","description":"trtr","code":"tyrytr"}
{"title":"ret54","description":"56tr","code":"ty76"}
{"title":"rgfdg","description":"dfgdfg","code":"dfgdfg"}
{"title":"asfafdsf","description":"sdfsdf","code":"sdfsdfsdf"}
This is my code: but this is not working.why?
How to retrieve value from overlay.txt file.
I did not get all title value.
I do not known how to get title value from overlay.txt
The $title is showing empty.
Where I want to change in my code to get $title value.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
$filecon = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays',$filecon);
//overlays page;
foreach($filecon as $files)
{
$title=$files['title'];
echo $title;
}
You're encoding your array to JSON, so at some point you need to decode it again into a PHP array. Since you actually have several JSON objects in the file, you need to decode each one individually. Assuming it's always one JSON object per line, this'll do:
$jsonObjects = file('overlay.txt', FILE_IGNORE_NEW_LINES);
foreach ($jsonObjects as $json) {
$array = json_decode($json, true);
echo $array['title'];
...
}
This will very quickly break if there are line breaks within the serialized JSON, e.g.:
{"title":"ret54","description":"foo
bar","code":"ty76"}
That way of storing the data is not very reliable.
make overlay.txt fully json format:
[
{"title":"sss","description":"sss","code":"sss"},
{"title":"trtr","description":"trtr","code":"tyrytr"},
...
]
and try this:
$raw = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays', array("filecon" => json_decode($raw)));
overlay page:
<?php
foreach($filecon as $files) {
echo $files['title'];
}
?>
If you want to use $filecon in view file,
set an array which has the key "filecon" in $this->load->view()'s second argument.
http://codeigniter.com/user_guide/general/views.html
I have a problem right now with CodeIgniter : I use the REST Controller library (which is really awesome) to create an API but I can not get PUT requests...
This is my code :
function user_put() {
$user_id = $this->get("id");
echo $user_id;
$username = $this->put("username");
echo $username;
}
I use curl to make the request :
curl -i -X PUT -d "username=test" http://[...]/user/id/1
The user_id is full but the username variable is empty. Yet it works with the verbs POST and GET.
Have you any idea please?
Thank you !
According to: http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/ we should consult https://github.com/philsturgeon/codeigniter-restserver/blob/master/application/libraries/REST_Controller.php#L544 to see that this method:
/**
* Detect method
*
* Detect which method (POST, PUT, GET, DELETE) is being used
*
* #return string
*/
protected function _detect_method() {
$method = strtolower($this->input->server('REQUEST_METHOD'));
if ($this->config->item('enable_emulate_request')) {
if ($this->input->post('_method')) {
$method = strtolower($this->input->post('_method'));
} else if ($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$method = strtolower($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
}
}
if (in_array($method, array('get', 'delete', 'post', 'put'))) {
return $method;
}
return 'get';
}
looks to see if we've defined the HTTP header HTTP_X_HTTP_METHOD_OVERRIDE and it uses that in favor of the actual verb we've implemented on the web. To use this in a request you would specify the header X-HTTP-Method-Override: method (so X-HTTP-Method-Override: put) to generate a custom method override. Sometimes the framework expects X-HTTP-Method instead of X-HTTP-Method-Override so this varies by framework.
If you were doing such a request via jQuery, you would integrate this chunk into your ajax request:
beforeSend: function (XMLHttpRequest) {
//Specify the HTTP method DELETE to perform a delete operation.
XMLHttpRequest.setRequestHeader("X-HTTP-Method-Override", "DELETE");
}
You can try to detect the method type first and seperate the different cases. If your controller only handles REST functions it could be helpful to put get the required information in the constructor.
switch($_SERVER['REQUEST_METHOD']){
case 'GET':
$var_array=$this->input->get();
...
break;
case 'POST':
$var_array=$this->input->post();
...
break;
case 'PUT':
case 'DELETE':
parse_str(file_get_contents("php://input"),$var_array);
...
break;
default:
echo "I don't know how to handle this request.";
}
In CodeIgniter 4 use getRawInput which will retrieve data and convert it to an array.
$data = $request->getRawInput();
look this issue in github
PUT parameters only work in JSON format
https://github.com/chriskacerguis/codeigniter-restserver/issues/362
Checkout this link in the official Code Igniter Docs Using the Input Stream for Custom Request Methods
This is the Code Igniter way to do it.
Just call the below if the body of the request is form-urlencoded
$var1 = $this->input->input_stream('var_key')
// Or
$var1 = $this->security->xss_clean($this->input->input_stream('var_key'));
Codeigniter put_stream has provided no help, instead I had to use php input stream as following method can be added to helpers, from there you can parse put request in any of the controllers:
function parsePutRequest()
{
// Fetch content and determine boundary
$raw_data = file_get_contents('php://input');
$boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));
// Fetch each part
$parts = array_slice(explode($boundary, $raw_data), 1);
$data = array();
foreach ($parts as $part) {
// If this is the last part, break
if ($part == "--\r\n") break;
// Separate content from headers
$part = ltrim($part, "\r\n");
list($raw_headers, $body) = explode("\r\n\r\n", $part, 2);
// Parse the headers list
$raw_headers = explode("\r\n", $raw_headers);
$headers = array();
foreach ($raw_headers as $header) {
list($name, $value) = explode(':', $header);
$headers[strtolower($name)] = ltrim($value, ' ');
}
// Parse the Content-Disposition to get the field name, etc.
if (isset($headers['content-disposition'])) {
$filename = null;
preg_match(
'/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/',
$headers['content-disposition'],
$matches
);
list(, $type, $name) = $matches;
isset($matches[4]) and $filename = $matches[4];
// handle your fields here
switch ($name) {
// this is a file upload
case 'userfile':
file_put_contents($filename, $body);
break;
// default for all other files is to populate $data
default:
$data[$name] = substr($body, 0, strlen($body) - 2);
break;
}
}
}
return $data;
}
CodeIgniter doesn't support reading incoming PUT requests and if it's not essential I would stick to GET/POST for your API as its probably not necessary.
If you do need to read PUT requests take a look at Accessing Incoming PUT Data from PHP.
I want to pass an image as a byte array from php to a .NET web serice.
The php client is as follows:
<?php
class Image{
public $ImgIn = array();
}
$file = file_get_contents('chathura.jpg');
$ImgIn = str_split($file);
foreach ($ImgIn as $key=>$val) { $ImgIn[$key] = ord($val); }
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage(new Image());
echo $result->PutImageResult;
//print_r($ImgIn);
?>
Here is the web method in ASP.NET web service:
[WebMethod]
public string PutImage(byte[] ImgIn)
{
System.IO.MemoryStream ms =
new System.IO.MemoryStream(ImgIn);
System.Drawing.Bitmap b =
(System.Drawing.Bitmap)Image.FromStream(ms);
b.Save("imageTest", System.Drawing.Imaging.ImageFormat.Jpeg);
return "test";
}
When I run this the image content is correctly read to ImgIm array in php client. (In this instance the image had 16992 elements.) However when the array is passed to the web service method it contains only 5 elements (the first 5 elements of the image)
Can I know what is the reason for the loss of data ? How can I avoid it ?
Thanks
file_get_contents returns the file contents as string which is not useful for binary files such as images. Try this:
$handle = fopen("chathura.jpg", "r");
$contents = fread($handle, filesize("chathura.jpg"));
fclose($handle);
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($contents);
Guys, it seems that it is not going to be any use to try and pass data as a byte array as PHP anyway converts it to a string when sending. This conversion seems to introduce control characters to the string, making it only send a part of the byte array. I got this to work by sending a base64 encoded string and decoding inside the server.
My client side code:
<?php
class Image{
public $ImgIn = '';
}
//ini_set("memory_limit","20M");
$imageData = file_get_contents('chathura.jpg');
$encodedData = base64_encode($imageData);
$Img = new Image();
$Img->ImgIn = $encodedData;
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($Img);
echo($result->PutImageResult);
?>
ASP .NET web service code:
[WebMethod]
public string PutImage(String ImgIn)
{
byte[] ImgInBytes = Convert.FromBase64String(ImgIn);
System.IO.MemoryStream ms =
new System.IO.MemoryStream(ImgInBytes);
System.Drawing.Bitmap b =
(System.Drawing.Bitmap)Image.FromStream(ms);
b.Save("C:\\imageTest.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
return "success";
}