add headers to file_get_contents in php - php

I am completely new PHP and want a client program to call an URL web service.I am using file_get_content to get the data.How do add additional headers to the request made using file_get_content.
I also was thinking of using cURL. I wanted to know how cURL can be used to do a GET request.

You can add headers to file_get_contents, it takes a parameter called context that can be used for that:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => "Host: www.example.com\r\n" .
"Cookie: foo=bar\r\n"
)
));
$data = file_get_contents("http://www.example.com/", false, $context);

As for cURL, the basic example from the PHP manual shows you how to perform a GET request:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>

Related

Modifying php script to have POST request in cURL for a JSON upload

I have an existing PHP script, which essentially connects to 2 databases each on a different server and performs a few MySQL queries on each. The ultimate results are stored in a data array which is used to write said results into a JSON file.
All of this works perfectly. The data is inserted into the mysql table correctly and the JSON file is exactly the way it should be.
However, I need to add a block to the end of my script that makes a POST request to one of our affiliate's API and upload the info there. We're currently manually uploading this JSON file to the api instance but we have the configuration data for their server to use in a POST request now so that when this script is run it automatically sends the data rather than us having to manually update it.
The main thing is I'm not exactly sure how to go about that. I've started with code for doing this but I'm not familiar with cURL so I don't know the best way to structure this in php.
Here is an example the affiliate gave me in cURL command line syntax:
curl \
-H "Authorization: Token AUTH_TOKEN" \
-H "Content-Type: CONTENT_TYPE" \
-X POST \
-d '[{"email": "jason#yourcompany.com", "date": "8/16/2016", "calls": "3"}]'
\
https://endpoint/api/v1/data/DATA_TYPE/
I have my auth token, my endpoint URL and my content type is JSON, which can be seen in my code below. Also, I have an array instead of the example for the body above.
and here's the affected part of my code:
//new array specifically for the final JSON file
$content2 = [];
//creating array for new fetch since it now has the updated extension IDs
while ($d2 = mysqli_fetch_array($data2, MYSQLI_ASSOC)) {
// Store the current row
$content2[] = $d2;
}
// Store it all into our final JSON file
file_put_contents('ambitionLog.json', json_encode($content2, JSON_PRETTY_PRINT ));
//Beginning code to upload to Ambition API via POST
$url = 'endpoint here';
//Initiate CURL
$ch = curl_init($url);
//JSON data
$jsonDataEncodeUpload = json_encode($content2, JSON_PRETTY_PRINT);
//POST via CURL
curl_setopt($ch, CURLOPT_POST, 1);
//attach JSON to post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncodeUpload);
//set content type
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//execuate request
$postResult = curl_exec($ch);
So, like I said, nothing about the file or the data needs to be changed, I just need to have this cURL section take the existing array that's being written to a JSON file and upload it to the API via post. I just need help making my php syntax for curl match the command line example.
Thanks for any possible help.
Have you tried with file_get_contents ( http://en.php.net/file_get_contents ).
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
I have found the answer on stackoverflow How to post data in PHP using file_get_contents?
Here is worked example of code. Check $err may be it will be helpful.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST('data'));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);

Retrieving URL formed by CURL POST

I want to retrieve the final URL formed using a CURL request, but none of them work what I want to retrieve.
for example - I directly paste an API call in the browser address bar, it works, but when using CURL request I get some errors.
To find that I want to retrieve the final request URL formed by CURL or all the request parameters included in CURL Request.
The various methods I have tried is like:
$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_STDERR => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);
Alternatively -
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$data = curl_exec($ch);
var_dump($data);
var_dump(curl_getinfo($ch));
Thanks.
Update:
My request should form url like this:
https://api-3t.sandbox.paypal.com/nvp/?METHOD=SetExpressCheckout&VERSION=86&PWD=9mypassword&USER=my_user_name&SIGNATURE=my_api_signature&L_BILLINGTYPE0=RecurringPayments&L_BILLINGAGREEMENTDESCRIPTION0=FitnessMembership&cancelUrl=http://localhost/recurring-payment/index.php&returnUrl=http://localhost/recurring-payment/review.php
Now I want to get all the info in the above URL being submitted to Paypal API.
So I can retrieve this info being sent through CURL.

How do I access a php file from another domain

Say I got 3 websites. Every time I do an action on site (1), I need to access file.php from (2) and (3) with the parameter of the site the action has been done ( (1) in this case ), so, for this example, I need to access:
(2).com/file.php?site=1
(3).com/file.php?site=1
The same applies if the action is done from the website (2) and (3).
What is the best way to approach this? ( I don't want to manually access the file from my browser every time said action happens on the website (x) )
I tried doing a simple:
<form method="get" action="(2).com/file.php?site=1"> </form>
<form method="get" action="(3).com/file.php?site=1"> </form>
It doesn't work.
I tried doing some kind of ajax/XMLHttpRequest and also tried using the "file" PHP function.
So, my question is, how do I approach this? What is the best way to "virtually" open a browser, and load a PHP file?
Use curl via a proxy for cross-domain queries.
Here's an example taken from another SO question ( How to use CURL via a proxy? )
<?php
$url = 'http://www.php.net';
$proxy = '10.10.10.101:8080';
//$proxyauth = 'user:password';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
echo $curl_scraped_page;
I'm sorry because I haven't used the Search function enough :(
I would've tried curl, but the code Prefix used didn't work on my site and when I tried it locally, it said that curl was not installed, so I proceeded to try the next thing that was in sight. I ended up using this code, from another SO thread: How do I send a POST request with PHP?
$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result)
You can use PHP files from other domains normally (to handle requests, echo results etc.), but you need to add the following headers to the PHP files on your other domains. This is needed for ajax or xmlhttprequests.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");

post data with file_get_content

I have done some research regarding on how to use file_get_content with post. And I have also read this one which is I honestly don't understand since I am not that familiar with PHP. Below is my php code in getting my json and used it for my ajax request, using methog GET.:
<?php
echo(file_get_contents("http://localhost:8001/" . $_GET["path"] . "?json=" . urlencode($_GET["json"])));
?>
Now, I am using method POST and I dont know how to modify my php code to post my data from my javascript. Below is my data which I wanted to post in my url request (that is also what I used as json in method GET):
{"SessionID":"9SQLF17XcFu0MTdj5n",
"operation":"add",
"transaction_date":"2011-7-28T00:00:00",
"supplier_id":"10000000108",
"wood_specie_id":"1",
"lines": [{"...":"...","..":"..."},{"...":"...","..":"..."}],
"scaled_by":"SCALED BY",
"tallied_by":"TALLIED BY",
"checked_by":"CHECKED BY",
"total_bdft":"23.33",
"final":"N"}
I just need to change this code
echo(file_get_contents("http://localhost:8001/" . $_GET["path"] . "?json=" . urlencode($_GET["json"])));
with POST to send my post my data.
EDIT:
I need to produce a request like this:
http://localhost/jQueryStudy/RamagalHTML/processjson.php?path=getData/supplier?​json={"SessionID":"KozebJ4SFqdqsJtRpG6t1o3uQxgoeLjT"%2C"dataType":"data"}
You can pass a Stream Context as the third argument to file_get_contents. With the Stream Context, you can influence how the HTTP request will be made, e.g. you can change the Method, add Content or arbirtrary headers.
file_get_contents($url, false, stream_context_create(
array (
'http' => array(
'method'=>'POST',
'header' => "Connection: close\r\nContent-Length: $data_len\r\n",
'content'=>$data_url
)
)
));
After each request, PHP will automatically populate the $http_response_header which will contain all the information about the request, e.g. Status Code and stuff.
$data_url = http_build_query (array('json' => $_GET["json"]));
$data_len = strlen ($data_url);
echo file_get_contents("http://localhost:8001/" . $_GET["path"], false, stream_context_create(
array (
'http' => array(
'method'=>'POST',
'header' => "Connection: close\r\nContent-Length: $data_len\r\n",
'content'=>$data_url
)
)
));
What you need is cURL.
Example:
$dataString = "firstName=John&lastname=Smith";
$ch = curl_init();
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,2); // number of variables
curl_setopt($ch,CURLOPT_POSTFIELDS,$dataString);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
If i understand you correctly(I might not) you should use CURL.
CURL is the way to submit POST requests within PHP. (but it is not the only way)
What you are doing is sending the data by the GET method
some think like this, please read about it, this one will not work out of the box
<?php
$ch = curl_init("http://localhost:8001/" . $_GET["path"] );
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "json=".urlencode($_GET["json"]));
curl_exec ($ch);
curl_close ($ch);
?>

Make HTTP/1.1 request with PHP

My code is using file_get_contents() to make GET requests to an API endpoint. It looks like it is using HTTP/1.0 and my sysadmin says I need to use HTTP/1.1. How can I make an HTTP/1.1 request? Do I need to use curl or is there a better/easier way?
Update
I decided to use cURL since I am using PHP 5.1.6. I ended up forcing HTTP/1.1 by doing this:
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
If I was using 5.3 or later I would have tried doing something like this:
$ctx = stream_context_create(array(
'http' => array('timeout' => 5, 'protocol_version' => 1.1)
));
$res = file_get_contents($url, 0, $ctx);
echo $res;
http://us.php.net/manual/en/context.http.php
Note: PHP prior to 5.3.0 does not
implement chunked transfer decoding.
If this value is set to 1.1 it is your
responsibility to be 1.1 compliant.
Another option I found which might provide HTTP/1.1 is to use the HTTP extension
I'd use cURL in either case, it gives you more control and in particular it gives you the timeout option. That's very important when calling an external API so as not to allow your application to freeze whenever a remote API is down.
Could like this:
# Connect to the Web API using cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.url.com/api.php?123=456');
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xmlstr = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
cURL will use HTTP/1.1 per default, unless you specify something else using curl_setopt($s,CURLOPT_HTTPHEADER,$headers);, where $headers is an array.
Just so others who want to use stream_context_create/file_get_contents know, if your server is configured to use keep-alive connections, the response will not return anything, you need to add 'protocol_version' => 1.1 as well as 'header' => 'Connection: close'. Example below:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 5,
'protocol_version' => 1.1,
'header' => 'Connection: close'
)
));
$res = file_get_contents($url, 0, $ctx);

Categories