AJAX & PHP:GET parameters causing Flickr api key error - php

I'm trying to send a URL with aFLickr API key to fetch results for a given photo tag. The Ajax code should return the XML to my browser. However the URL structure with parameters seems to cause a problem in my setup:
**the HTML file:**
...
url="api.flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=paris"
request.open("GET","xmlget.php?url=" + url + nocache, true)
...
**the 'xmlget.php' file:**
...
echo file_get_contents($_GET['url']);
...
error: code="100" msg="Invalid API Key (Key has invalid format)">
the link works fine if tested in the adress bar so there must be a breakdown somewhere when the URL is processed.
i tried wrapping it into encodeURI but no luck :(
Note: related post

You need to use encodeURIComponent instead of encodeURI to actually get that string encoded.
May I make 2 suggestions?
just pass the search parameters to xmlget.php and do the rest there even if it means having to pass a service type if you are using that generically
I don't remember what all a Flickr api key gets you, but it's generally a bad thing to post anything called an "api key" in public. In addition to the question, that includes sticking it in javascript that an end user can access.

Related

HTTP protocol's PUT and DELETE and their usage in PHP

Introduction
I've read the following:
Hypertext Transfer Protocol (HTTP) is the life of the web. It's used every time you transfer a document, or make an AJAX request. But HTTP is surprisingly a relative unknown among some web developers.
The HTTP verbs comprise a major portion of our “uniform interface” constraint and provide us the action counterpart to the noun-based resource. The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, and DELETE.
Huh?
Well, we came to the point I lost track of things.
PUT and DELETE, they say. I've only ever heard of POST and GET and never saw something like $_PUT or $_DELETE passing by in any PHP code I've ever viewed.
My question
What are these methods (PUT) and (DELETE) for and if it's possible to use them in PHP, how would I go about this.
Note: I know this is not really a problem but I always grab a learning opportunity if I see one and would very much like to learn to use these methods in PHP if this is possible.
What are these methods (PUT) and (DELETE) for...
There are a lot of words to spend to explain this, and I'm not skilled enough to do it, but as already posted, a quick recap of what the HTTP specification describes.
The protocol basically says this:
use GET when you need to access a resource and retrieve data, and you don't have to modify or alter the state of this data.
use POST when you need to send some data to the server. Ex. from a form to save these data somewhere.
use HEAD when you need to access a resource and retrieve just the Headers from the response, without any resource data.
use PUT when you need to replace the state of some data already existing on that system.
use DELETE when you need to delete a resource (relative to the URI you've sent) on that system.
use OPTIONS when you need to get the communication options from a resource, so for checking allowed methods for that resource. Ex. we use it for CORS request and permissions rules.
You can read about the remaining two methods on that document, sorry I've never used it.
Basically a protocol is a set of rules you should use from your application to adhere to it.
... and if it's possible to
use them in PHP, how would I go about this.
From your php application you can retrieve which method was used by looking into the super global array $_SERVER and check the value of the field REQUEST_METHOD.
So from your php application you're now able to recognize if this is a DELETE or a PUT request, ex. $_SERVER['REQUEST_METHOD'] === 'DELETE' or $_SERVER['REQUEST_METHOD'] === 'PUT'.
* Please be also aware that some applications dealing with browsers that don't support PUT or DELETE methods use the following trick, a hidden field from the html form with the verb specified in its value attribute, ex.:
<input name="_method" type="hidden" value="delete" />
Follow an example with a small description on a possible way to handle those 2 http requests
When you (your browser, your client) request a resource to an HTTP server you must use one of the method that the protocol (HTTP) accepts. So your request needs to pass:
A METHOD
An Uri of the resource
Request Headers, like User-Agent, Host, Content-Length, etc
(Optional body of the request)
Now, while you would be able to get data from POST and GET requests with the respective globals ($_GET, $_POST), in case of PUT and DELETE requests PHP doesn't provide these fast access globals; But you can use the value of $_SERVER['REQUEST_METHOD'] to check the method in the request and handle your logic consequently.
So a PUT request would look like:
PUT /something/index.php
(body) maybe=aparameter
and you can access those data in PHP by reading the php://input stream, ex. with something like:
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
$myEntireBody = file_get_contents('php://input'); //Be aware that the stream can only be read once
}
and a DELETE request would look like:
DELETE /something/index.php?maybe=aparameter
and again you can build your logic after have checked the method:
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// do something
}
Please pay attention that a DELETE request has no Body and pay very attention to Response Status Code too (ex. if you received a PUT request and you've updated that resource without error you should return a 204 status -No content-).
Way to use PUT data from PHP:
$method = $_SERVER['REQUEST_METHOD'];
if ('PUT' === $method) {
parse_str(file_get_contents('php://input'), $_PUT);
var_dump($_PUT); //$_PUT contains put fields
}
PHP's $_GET and $_POST are poorly named. $_GET is used to access the values of query string parameters, and $_POST lets you access the request body.
Using query string parameters is not limited to GET requests, and other kinds of requests than just POST can come with a request body.
If you want to find out the verb used to request the page, use $_SERVER['REQUEST_METHOD'].
Most suitable place to use these (PUT and DELETE) methods is REST API. Where we use http methods to define the mode of operation for example you want to fetch any resources then you can use following:
GET http://api.example.com/employee/<any_id>
to add a new item:
POST http://api.example.com/employee/
to Update or Edit:
PUT http://api.example.com/employee/
to Delete an existing resource:
DELETE http://api.example.com/employee/1
etc.
Now on PHP side you just need to read what HTTP method used so that you can make an action according to that.
There are lots of libraries available which can do that for you.
What are these methods (PUT) and (DELETE)
There are described in the HTTP spec.
In a nutshell, and simplifying somewhat, PUT is for uploading a file to a URL and DELETE is for deleting a file from a URL.
never sawy something like $_PUT or $_DELETE passing by in any PHP code I've ever viewed
$_POST and $_GET are terribly named superglobals. $_POST is for data parsed from the request body. $_GET is for data parsed from the URL. There's nothing that strictly ties data in either of those places (especially the URL) to a particular request method.
DELETE requests only care about the URL's path, so there is no data to parse.
PUT requests usually care about the entire request body (not a parsed version of it) which you would access with file_get_contents('php://input');.
for and if it's possible to use them in PHP, how would I go about this.
You'd need to map the URL onto a PHP script (e.g. with URL rewriting), test the request method, work out what URL you were actually dealing with, and then write code to do the appropriate action.
$GLOBALS["_PUT"]=null;
if($_SERVER['REQUEST_METHOD'] == 'PUT') {
$form_data= json_encode(file_get_contents("php://input"));
$key_size=52;
$key=substr($form_data, 1, $key_size);
$acc_params=explode($key,$form_data);
array_shift($acc_params);
array_pop($acc_params);
foreach ($acc_params as $item){
$start_key=' name=\"';
$end_key='\"\r\n\r\n';
$start_key_pos=strpos($item,$start_key)+strlen($start_key);
$end_key_pos=strpos($item,$end_key);
$key=substr($item, $start_key_pos, ($end_key_pos-$start_key_pos));
$end_value='\r\n';
$value=substr($item, $end_key_pos+strlen($end_key), -strlen($end_value));
$_PUT[$key]=$value;
}
$GLOBALS["_PUT"]=$_PUT;
}
if (!function_exists("getParameter")){
function getParameter($parameter)
{
$value=null;
if(($_SERVER['REQUEST_METHOD'] == 'POST')&& (isset($_POST[$parameter]))){
$value=$_POST[$parameter];
}
else if(($_SERVER['REQUEST_METHOD'] == 'PUT')&& (isset($GLOBALS["_PUT"][$parameter])))
{
$value=$GLOBALS["_PUT"][$parameter];
}
else if(($_SERVER['REQUEST_METHOD'] == 'DELETE')&& (isset($_DELETE[$parameter]))){
$value=$_DELETE[$parameter];
}
else if(($_SERVER['REQUEST_METHOD'] == 'PATCH')&& (isset($_PATCH[$parameter]))){
$value=$_PATCH[$parameter];
}
else if(isset($_GET[$parameter])){
$value=$_GET[$parameter];
}
return $value;
}
}

403 Forbidden nginx when use method GET ajax

I'm doing a an ajax request to the following path:
http://example.com/dir/ajax/index.php
http://example.com/dir/ajax/index.php=123
that works. But when I'm calling
http://example.com/dir/ajax/index.php=http://example.net/ the request is answered withan error 403 forbidden,
Whats wrong with this call?
Your URL seems to be malformed. Have a look at the typical structure of a query string. You're not specifying the name of the query parameter to be parsed by the server. A sample of a valid URL would be
http://example.com/dir/ajax/index.php?query_name=http://example.net/
or even
http://example.com/dir/ajax/index.php?http://example.net/
If you're interested in more details about query strings, you should have a look at the standards
URI: https://www.rfc-editor.org/rfc/rfc3986#section-3.4
HTTP: http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html
I think in your case you don't have to distinguish between these two standards. If you're interested in building a query string automatically from javascript, have a look at this stackoverflow post.

Facebook SDK and Graph API Comment Deleting Error

Working with the Facebook php SDK's, I am having a lot of trouble figuring out how to delete comments, given its id and xid.
At first I was using the REST API, where you can call 'comments_remove($xid, $id);' to delete a comment. The problem with this method came when the xid parameter only accepts alphanumeric characters and underscores.
Based on the documentation (http://developers.facebook.com/docs/reference/fbml/comments ) a valid XID can be the result of any url_encode.
Now I am testing my luck with the new GRAPH api. Looking at http://developers.facebook.com/docs/api under 'Deleting Objects', It seems that comment deleting is definitely supported. However, I have tried sending a DELETE request, and I have also tried sending POST and GET to the object url with the argument 'method=delete'.
No matter how I try it, I always get the same error:
{"error":{"type":"GraphMethodException","message":"Unsupported delete request."}}
I am sending the access token as a parameter as well. The access token that I am sending is the access token saved in the facebook cookie from the single sign on javascript cookie. These are all comments made on my application. Does this happen to anyone else, or am I simply not doing this right?
Any help or guidance is GREATLY appreciated.
Fixed!
You have to prepend the userid to the object ID when deleting:
DELETE https://graph.facebook.com/673509687_104812882909249?access_token={access_token}
where
673509687 is my userID and 104812882909249 is the objectID
Hopefully we can get this looked at:
http://bugs.developers.facebook.com/show_bug.cgi?id=10413
or
http://bugs.developers.facebook.com/show_bug.cgi?id=10434
Try with this:
FB.api('/'+_idComment, 'get', { method:'delete' }, function(response){
//Your code
}

Receiving and handling a GET request in PHP

I'm trying to replace RSS polling with PubSubHubbub on my site. I'm able to use the subscriber library that google offers to send the subscription request. From the code it looks like it sends a post request via cURL with the RSS URL and a callback URL.
So this is where I need some direction:
In order to complete the subscription request my callback URL has to receive a GET request and then echo back a value from the GET request along with a 200 response. How do I get the parameters from the GET request? Is the echo done again via cURL? If so what option should include the 200 response?
This very simple script should be a start:
echo $_GET["request_name"];
this will output the GET parameter request_name and (implicitly) send a 200.
It's also a good idea to explicitly declare a content type before echoing, to prevent the default content type (usually "text/html") from kicking in:
header("Content-type: text/plain");
Note that when echoing external data, you may need to sanitize the output first - if the for example the output format is HTML, you would want to do something like echo htmlspecialchars($_GET["request_name"]); to prevent Cross-Site Scripting.
There was recently a thread on the php-dev mailing list about this. The reason you can't access 'hub.challenge' in the $_GET superglobal is due to register_globals. Basically PHP cleans up any argument names before creating the superglobals. Any dots will be converted to underscores. It's looking to be 'fixed' in PHP 6, but not before due to BC issues.
Here's the thread about it.

Post to twitter help - using php

I am trying to post a url to twitter but the url is user generated and dynamic...
TWEET THIS REQUEST
i started with that but its not catching the actual url- then i tried a few others but they seem to be for static urls
do i have to use the api or is there a way for this urlencode to read the specific url we want the users to publish?
thanks
UPDATE
TWEET THIS REQUEST
<p> <img target="Borrow this from someone on twitter" src="PHOTOBUCKET direct URL HERE" alt="TWEET THIS (IMPROVE YOUR SELECTION)" title="" border="0" /></p>
basically i want a combination of both- if you see "item=22" that is always changing- so i want a button where the code will actually read the CURRENT url not just a static one i added at the beginning... is this possible?
probably something like this?
<?php
$posts = array (
'i\'d like to borrow this item #neighborrow',
'test this very carefully',
'enough!!!'
);
foreach( $posts as $post )
{
?>
tweet this request <small>[<?php echo $post; ?>]</small> <br/>
<?php
}
?>
Liveview at codecookie.net
hope i understood it correct!
There's a pretty handy PHP Twitter API library here: http://lab.arc90.com/2008/06/03/php-twitter-api-client/
That'll make sure you don't have to solve problems that have already been solved and you can concentrate on writing your code.
I think a problem might be that you used "[ ]" the square brackets to surround the string, and you ended it with a period.
Other than that, I might suggest using something like htmlentities () or htmlspecialchars().
Alternatively, you might want to look into using the API to do this. For one thing, unless you're checking somewhere else, there's no way to guarantee the user is signed into twitter, and the API allows you to authenticate with twitter, plus the API is more likely to be supported longer than the query string request.
UPDATE:
I think the problem would be in this part of the code:
TWEET THIS REQUEST
You call a function called urlencode, but it's in the HTML part of the code, so the PHP is not going to execute that function, and the HTML simply parses it as plain text.
You'd want to replace it with this:
TWEET THIS REQUEST
That should let the php code parse that and return the encoded string.

Categories