TLDR: I want to use get_theme_mod() inside a PHP file other than functions.php in WordPress to use a value added through customizer.
Long version:
I am making an API call using cURL in a separate PHP file. I want to create a new panel in customizer with an inputfield that accepts the API-key for my custom PHP API call. Basically I need to know if I can use the get_theme_mod() method to call the value into my custom PHP file, store it in a variable and use it to append it to my API call.
This is my API call code
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://maps.googleapis.com/maps/api/place/details/json?placeid=< GOOGLE PLACE ID >&key=< MY API KEY>",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Once the call is made, I AJAX this file into a JavaScript file where I work with the data. Which is initially why I put the API call into a separate file. My goal is for the person working on the site to simply paste an API key, or the place id for Google and have the entire process execute without having to monkey around in the source code. I have all the infrastructure in place and the call works I just wanted to eliminate the need for us to touch the source code and simply drop an API key value in the customizer and let the code do the rest.
I'm assuming you mean the theme customizer? Maybe instead save settings using the Settings API. But you should also do AJAX the "wordpress way" or use the newer REST stuff.
Directly answering your question of "how to use Wordpress functions in external PHP" see https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files
<?php
define('WP_USE_THEMES', false); // although you might want that to be true if you're using theme data?
require('./wp-load.php');
?>
Or maybe consider doing all that stuff in a shortcode that takes the place key and/or api key, e.g. [get-place-info placekey="xxxxx" apiKey="xxxx"] so your user can dump it anywhere, unless you specifically need it available to javascript (heck, you could have the shortcode dump JSON into the page).
Related
I have searched a lot, and found many related questions and forums related to this, but this one is a challenging one.
I'm trying to POST a complex array via curl. It has to be form-data while the first value in the array is of type JSON.
The two other values of array are two images which are uploaded and ready to send.
I tried to run it in Postman, and works perfectly fine. I used the generated PHP code from Postman, but it is not working. Seems like postman is handling some of its tricks without revealing them to us.
Any way, I'm posting a Postman image to illustrate what I mean:
As you can see, I'm sending the data in form-data tab, my first value (param1) is a JSON with content-type application/json, the second and third values are images uploaded in Postman.
This works just fine in Postman.
The problem is, if I set Content-Type:multipart/form-data in header, the destination server throws an error saying the content-type must be JSON.
If I set the Content-Type:application/json in header, the destination server says content must be of type Multipart.
Somehow, I need to set both content-types. The main one as form-data and the one for param1 as JSON.
I paste the Postman code as well, may that be a good start for you fellas to help out with the code.
Postman Code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://xxxxx.com/xxxx/xxx/xxxx',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('param1' => '{
"AgentId":"1414",
"ContractId":36529,
"Files":[
{
"FileName":"car_card_front_image.png",
"FileTypeId":2
},
{
"FileName":"car_card_back_image.png",
"FileTypeId":2
}
]
}','param2'=> new CURLFILE('/C:/images/icons/car_card_back_image.png'),'param3'=> new CURLFILE('/C:/images/icons/car_card_front_image.png')),
CURLOPT_HTTPHEADER => array(
'authenticationToken: xxxx-xxx-xx-xxxxxxxx'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
The PHP generated code by postman, is not working. One of the reasons can be that there's no content-type mentioned in it.
I tried modifying the code, adding content-types in header and in parameter, nothing seems to work.
If Postman can do it, we should be able it too, right?
Go ahead, make as much changes as you would or suggest anything that comes to your mind, I will test them all.
Cheeeeers...
May i suggest the ixudrra/curl library ?
It would make your life easier ....
$response = Curl::to('http://example.org')
->withData( array( 'Foo' => 'Bar' ) )
->withFile( 'image_1', '/path/to/dir/image1.png', 'image/png', 'imageName1.png' )
->withFile( 'image_2', '/path/to/dir/image2.png', 'image/png', 'imageName2.png' )
->post();
Everything I look at online is showing how to use OAuth & Curl to make a POST request, but I want to make a get request to the Mailchimp API and I'm not getting any response it seems. I've already managed to go through the authentication and get the user's token & api URL. Now I'm just trying to pull in their lists. Here's the CURL code I've got currently:
$headers = array(
"Content-type: application/json",
"Authorization: OAuth ".$user['mct']
);
$curl = curl_init();
curl_setopt_array($curl,array(
CURLOPT_URL => "https://".$user['dc'].".api.mailchimp.com/3.0/lists",
CURLOPT_USERAGENT => "oauth2-draft-v10",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_ENCODING => ''
));
$tresp = curl_exec($curl);
$lists = json_decode($tresp,true);
curl_close($curl);
Assuming $user['mct'] and $user['dc'] contain the proper values, any idea what I'm doing wrong here?
In case anyone ends up googling and finding this, my problem was that the user information I was getting from wordpress' get_results() function was an object and not an array. Took me forever to realize because for some reason this part of my plugin is preventing me from using print_r().
Now that it's actually going to the Mailchimp API I'm able to get and debug whatever error they're sending back.
have a look at below snippet inside my PHP code :
function SMS(){
$msg1="".$bookingNo."\n".$guestName."\n".$guestEmail."\n".$guestPhone."\n".$guestAddress."\n".$place."\n".$account."\n".$reportingDate."\n".$reportingTime."";
file('http://sms.xxxxxxxxxxxxx.co.in/api/webxxxx.php?workingkey=76565xxxxxx&sender=ILUVU&to=9897xxxxxxx&message='.$msg1.'');}
The problem is this that this http link is sending SMS successfully when run on browser window,
with some dummy text in &message=.
But when I am assigning all defined and tested variables inside $msg1 & calling it in same url.
Woosh, it shows NO ERROR & nothing happens, on calling this function. NO SMS.
I wonder where m wrong ?
Thanks
UPDATED CODE :
function SMS(){
$bookingNo=$_REQUEST['bookingNo'];
$guestName=$_REQUEST['guestName'];
$guestEmail=$_REQUEST['guestEmail'];
$guestPhone=$_REQUEST['guestPhone'];
$guestAddress=$_REQUEST['guestAddress'];
$place=$_REQUEST['place'];
$account=$_REQUEST['account'];
$reportingDate=$_REQUEST['reportingDate'];
$reportingTime=$_REQUEST['reportingTime'];
$msg1="".$bookingNo."\n".$guestName."\n".$guestEmail."\n".$guestPhone."\n".$guestAddress."\n".$place."\n".$account."\n".$reportingDate."\n".$reportingTime."";
file('http://sms.xxxxxxxxxxxxx.co.in/api/webxxxx.php?workingkey=76565xxxxxx&sender=ILUVU&to=9897xxxxxxx&message='.$msg1.'');}
}
SMStoDriver();
Newline characters are not allowed in URLs. You need to encode the message:
function SMS(){
$bookingNo=$_REQUEST['bookingNo'];
$guestName=$_REQUEST['guestName'];
$guestEmail=$_REQUEST['guestEmail'];
$guestPhone=$_REQUEST['guestPhone'];
$guestAddress=$_REQUEST['guestAddress'];
$place=$_REQUEST['place'];
$account=$_REQUEST['account'];
$reportingDate=$_REQUEST['reportingDate'];
$reportingTime=$_REQUEST['reportingTime'];
$msg1=urlencode("Booking No: $bookingNo\nName: $guestName\n Email: $guestEmail\nPhone: $guestPhone\nAddress: $guestAddress\nPlace: $place\nAccount: $account\nDate: $reportingDate\nTime: $reportingTime");
file('http://sms.xxxxxxxxxxxxx.co.in/api/webxxxx.php?workingkey=76565xxxxxx&sender=ILUVU&to=9897xxxxxxx&message='.$msg1.'');}
}
It looks like you are trying to use the file method to make the web request. Perhaps your PHP ini is configured to not allow file I/O requests to URLs.
You would be better off making the web request with something like cURL.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://sms.xxxxxxxxxxxxx.co.in/api/webxxxx.php?workingkey=76565xxxxxx&sender=ILUVU&to=9897xxxxxxx&message=test',
));
$resp = curl_exec($curl);
curl_close($curl);
I'm currently building a project based on the Parse.com backend that includes uploading files.
Users can upload files and then access a list of these/download them, this all works fine.
However, I'm not sure how to implement the command to delete an upload. From the Parse.com forums as well as the Parse support document, the call is:
curl -X DELETE \
-H "X-Parse-Application-Id: <YOUR_APPLICATION_ID>" \
-H "X-Parse-Master-Key: <YOUR_MASTER_KEY>" \
https://api.parse.com/1/files/<FILE_NAME>
I've had a bit of a look online but the only curl commands I can find to execute commands is curl_setopt. I imagine the above needs to be converted, can anybody help with this or point me in the right direction?
So basically I need to be able to press a button on a website (through PHP) and have it run the above command.
Thanks in advance
According to given info you have to set custom request method 'DELETE' (by CURLOPT_CUSTOMREQUEST option) as well as custom headers (by CURLOPT_HTTPHEADER option).
So the code should look like this:
$options = array(
CURLOPT_NOBODY => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_HTTPHEADER => array(
'X-Parse-Application-Id: <YOUR_APPLICATION_ID>',
'X-Parse-Master-Key: <YOUR_MASTER_KEY',
),
CURLOPT_URL => 'https://api.parse.com/1/files/<FILE_NAME>',
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
echo $response;
If it's useful I made a simple class to handle the api calls request via Curl
https://github.com/niklongstone/php-api
I’m using a REST API which, among other things, uses the DELETE method like this:
DELETE /resources/whatever/items/123
To access this using PHP I’m using cURL like this:
self::$curl = curl_init();
curl_setopt_array(self::$curl, array(
CURLOPT_AUTOREFERER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
));
As you can see, my cURL instance is static and will be reused for subsequent calls. This works fine when switching between “builtin” request methods. For example, in my get() method, I do something like this:
curl_setopt_array(self::$curl, array(
CURLOPT_HTTPGET => true,
CURLOPT_URL => self::BASE . 'whatever',
));
and then run curl_exec(). By explicitly setting the request method via CURLOPT_HTTPGET, a possible previous CURLOPT_POST will be cleared.
However, setting CURLOPT_CUSTOMREQUEST (for example to DELETE) will override any other builtin request method. That’s fine as long as I want to DELETE things, but calling for example curl_setopt(self::$curl, CURLOPT_HTTPGET, true) will not reset the custom method; DELETE will still be used.
I have tried setting CURLOPT_CUSTOMREQUEST to null, false or the empty string, but this will only result in a HTTP request like
/resources/whatever/items/123
i.e. with the empty string as method, followed by a space, followed by the path.
I know that I could set CURLOPT_CUSTOMREQUEST to GET instead and do GET requests without any problems, but I wonder whether there is a possiblity to reset CURLOPT_CUSTOMREQUEST.
This is actually a bug in PHP, since the original documentation states the following:
Restore to the internal default by setting this to NULL.
Unfortunately, as you can see from the source code, the option value gets cast to a string before it's passed to the underlying library.
Solution
I've written a pull request that addresses the issue and allows for NULL to be passed for the CURLOPT_CUSTOMREQUEST option value.
The above patch will take some time to get merged into the project, so until then you would have to explicitly set the method yourself once you start using this option.
Update
The fix has been applied to 5.5.11 and 5.6.0 (beta1).
Set CURLOPT_CUSTOMREQUEST to NULL and CURLOPT_HTTPGET to TRUE to reset back to an ordinary GET.
(Shrug ...) And what I wound up doing in my API is to simply, "set it every time." My POST routine simply sets a custom-header of "POST", and so on. Works great.
I found that, once you do set a custom-header, it "sticks." Future calls which then attempt to do ordinary GET, POST, PUT start to fail. I experimented with the suggestions listed earlier in this post (with PHP-7), and didn't very-quickly meet with success ... so: "to heck with it, this isn't elegant, but it works."