Using recent selenium server (2.41) cannot open url in Firefox - php

I have been running unit tests using Selenium Server 2.32 and Firefox 24.4 (on CentOS 5) -- just updated Firefox, and moved to Selenium 2.41, and now Selenium won't open a URL. I assume something has changed in either Firefox or Selenium that I need to adapt to, but can't figure out what.
I created as clean a test program as I could, which follows. It works (opens google.com in a Firefox window) using Selenium 2.32, but not in Selenium 2.41. As best I can tell from looking at the Selenium output it is getting a 404 error, but no idea way.
Any help gratefully appreciated !
Test Case in php:
$seleniumUrl = "http://mydomain.com:4444/wd/hub";
$desired_capabilities = array('browserName' => 'firefox');
$results = mycurl(
$seleniumUrl,
'POST',
'/session',
array('desiredCapabilities' => $desired_capabilities),
array(CURLOPT_FOLLOWLOCATION => true));
$seleniumUrl = $results['info']['url'];
$goToUrl = "http://google.com";
mycurl($seleniumUrl, 'POST', '/url', array('url' => $goToUrl));
Here is the source to mycurl function:
function mycurl(
$seleniumUrl,
$http_method,
$command,
$params = null,
$extra_opts = array()) {
if ($params && is_array($params) && $http_method !== 'POST') {
throw new Exception(sprintf(
'The http method called for %s is %s but it has to be POST' .
' if you want to pass the JSON params %s',
$command,
$http_method,
json_encode($params)));
}
$url = sprintf('%s%s', $seleniumUrl, $command);
if ($params && (is_int($params) || is_string($params))) {
$url .= '/' . $params;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$curl,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json;charset=UTF-8',
'Accept: application/json'));
if ($http_method === 'POST') {
curl_setopt($curl, CURLOPT_POST, true);
if ($params && is_array($params)) {
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
}
} else if ($http_method == 'DELETE') {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
foreach ($extra_opts as $option => $value) {
curl_setopt($curl, $option, $value);
}
$raw_results = trim(curl_exec($curl));
$info = curl_getinfo($curl);
if ($error = curl_error($curl)) {
$msg = sprintf(
'Curl error thrown for http %s to %s',
$http_method,
$url);
if ($params && is_array($params)) {
$msg .= sprintf(' with params: %s', json_encode($params));
}
throw new Exception($msg . "\n\n" . $error);
}
curl_close($curl);
$results = json_decode($raw_results, true);
$value = null;
if (is_array($results) && array_key_exists('value', $results)) {
$value = $results['value'];
}
$message = null;
if (is_array($value) && array_key_exists('message', $value)) {
$message = $value['message'];
}
return array('value' => $value, 'info' => $info);
}

Related

Trying to access array offset on value of type null & isset problem in API call loop - 504 Gateway Time-out server

I am building cron job with API calls in loop for DB entries and Have performance issues.
Particularly in this part:
if (!empty($sudCode) && !empty($sudBroj) && isset($sudCode) && isset($sudBroj)) {
// echo $sudCode . "<br>";
// echo $sudBroj . "<br>";
$epredmet = ePredmeti($sudCode, $sudBroj);
// print_r($epredmet);
// echo "<br>";
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) {
$lastUpdateTime = $epredmet["data"]["prvi"]["lastUpdateTime"];
$dateTime = str_replace("T", " ", $lastUpdateTime);
echo $nas . " - " . $dateTime . "<br>";
}
}
on line:
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) {
I have few Databases and on one when this line is reached sever goes to 504 Gateway Time-out after 2 minutes.
Hosting company said that it goes in timeout because Apache web server waits for PHP parser to process data, what ever that means.
What is strange, is if I leave out that if check i script finishes and I get results but with Notice: Trying to access array offset on value of type null in
because I expect that $epredmet after API call looks like this:
- array(1) { ["data"]=> array(1) { ["prvi"]=> NULL } } // case not found
- array(1) { ["data"]=> array(1) { ["prvi"]=> array(1) { ["lastUpdateTime"]=> NULL } } } // case found but lastUpdateTime is not set, null
- array(1) { ["data"]=> array(1) { ["prvi"]=> array(1) { ["lastUpdateTime"]=> string(23) "2021-06-14T22:51:22.171" } } } // case found and lastUpdateTime is set
So what I need to do is filter out just last case where lastUpdateTime is set, and all that I read is suggesting to solve it with isset but that breaks my script for some reason.
PHP V 7.4
Please advise.
Im attaching full script in case someone notices problem somewhere else:
function eSudovi()
{
$endpoint = "xxx";
$qry = '{"query":"query{sudovi {id, sudNaziv}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$eSudovi = eSudovi()["data"]["sudovi"];
function findSudCode($val, $eSudovi)
{
foreach ($eSudovi as $key => $value) {
if ($value["sudNaziv"] == $val) {
return $value["id"];
}
}
}
function ePredmeti($sud, $pred)
{
$endpoint = "xxx";
$qry = '{"query":"query{ prvi:predmet(sud: ' . $sud . ', oznakaBroj: \"' . $pred . '\") {lastUpdateTime}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$results = mysqli_query($con, "
SELECT DISTINCT predf_nas_br, predf_odv, predf_SUD, predf_SUDBROJ
FROM PREDMETIFView
WHERE predf_SUD <> '' AND predf_SUDBROJ <> '' AND predf_SUDBROJ NOT LIKE '% %'
UNION ALL
SELECT DISTINCT predp_nas_br, predp_odv, predp_SUD, predp_SUDBROJ
FROM PREDMETIPView
WHERE predp_SUD <> '' AND predp_SUDBROJ <> '' AND predp_SUDBROJ NOT LIKE '% %'
;");
while ($row = $results->fetch_assoc()) {
foreach ($row as $key => $value) {
if ($key == "predf_nas_br") {
$nas = $value;
}
if ($key == "predf_SUD") {
$sud = trim($value);
if (!empty($sud) && isset($sud)) {
$sudCode = findSudCode($sud, $eSudovi);
}
};
if ($key == "predf_SUDBROJ") {
$sudBroj = trim($value);
};
if (!empty($sudCode) && !empty($sudBroj) && isset($sudCode) && isset($sudBroj)) {
// echo $sudCode . "<br>";
// echo $sudBroj . "<br>";
$epredmet = ePredmeti($sudCode, $sudBroj);
print_r($epredmet);
echo "<br>";
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) {
$lastUpdateTime = $epredmet["data"]["prvi"]["lastUpdateTime"];
$dateTime = str_replace("T", " ", $lastUpdateTime);
echo $nas . " - " . $dateTime . "<br>";
}
}
}
};
// preg_match('/\s/', $sudBroj)
Edit:
I also tried this:
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"]) && !empty($epredmet["data"]["prvi"]["lastUpdateTime"])) {
and this:
if (isset($epredmet["data"]["prvi"]) && !empty($epredmet["data"]["prvi"])) {
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"]) && !empty($epredmet["data"]["prvi"]["lastUpdateTime"])) {
Same thing, it hangs, but without it all it work with erros.
Something like this would do to reuse the curl handle (note: haven't had time to test it, but you'll get the idea).
class ePredmeti{
public $epredmet;
private $curl,$ini_opt;
function __construct(){
$endpoint ='xxx';
$headers = ['Content-Type: application/json'];
$timeout = 30;
$this->curl= curl_init();
$this->ini_opt=[
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_TIMEOUT => $timeout
];
}
public function _exec($sud, $pred){
$start=microtime(true);
$this->epredmet = null;
$query_opt=[
CURLOPT_POSTFIELDS=>
'{"query":"query{ prvi:predmet(sud: ' . $sud . ', oznakaBroj: \"' . $pred . '\") {lastUpdateTime}}"}'
];
curl_reset($this->curl);
curl_setopt_array($this->curl, $this->ini_opt);
curl_setopt_array($this->curl, $query_opt);
$ret = curl_exec($ch);
if (!curl_errno($this->curl)){
if(curl_getinfo($this->curl, CURLINFO_HTTP_CODE)!==200){
echo 'HTTP error: '.$http_code.'<br>';
}
else{
$this->epredmet = json_decode($ret,true);
}
}
else{
echo curl_error($this->curl).'<br>';
}
echo 'Took: '.(microtime(true)-$start).'<br>';
}
}
before the while() put something like:
$mycurl = new ePredmeti();
and instead of $epredmet = ePredmeti($sudCode, $sudBroj); use
$mycurl->_exec($sudCode, $sudBroj);
Finally, instead of if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) { you can use
if( isset($mycurl->epredmet["data"]["prvi"]["lastUpdateTime"]) ) {
The last one works because the class returns null on any error and isset() checks if a variable exists and is not null.

how do i integrate paynow zimbabwe api with a localhost system?

Can you please help me to integrate paynow zimbabwe gateway with my localhost system.I have tried to follow their documentation https://developers.paynow.co.zw/docs/quickstart.html but I failed. I want the user to be redirected to the paynow page to pay penalties.Also the result or status must be obtained in order to update the system database. Is it possible to link a localhost system to the paynow api or my system have to be live?. Thank you in advance
<?php
include "./includes/tables_header.php";
include "./includes/db.php";
require_once "./paynow/autoloader.php";
use Paynow\Payments\Paynow;
if(isset($_POST['Paynow']))
{
class Payow{
public function paynows($amount)
{
$siteurl="http://localhost/online_offenceTracking_system/payment1.php?";//substitute with your own return url
define('ps_error', 'Error');
define('ps_ok','Ok');
define('ps_created_but_not_paid','created but not paid');
define('ps_cancelled','cancelled');
define('ps_failed','failed');
define('ps_paid','paid');
define('ps_awaiting_delivery','awaiting delivery');
define('ps_delivered','delivered');
define('ps_awaiting_redirect','awaiting redirect');
define('site_url', $siteurl);
$int_key="###########";//get from paynow.co.zw
$int_id=#######;//get from paynow.co.zw, it should be an intenger
$paymentid="testID1234hs";
$url="https://www.paynow.co.zw/interface/initiatetransaction/?";
$reference=sha1(Paynow\Payments\Paynow::$app->user->identity->email);
$amount=6.25;
$returnurl="http://localhost/online_offenceTracking_system/payment1.php?r=credit/index"; //substitute with your own return urls
$resulturl="http://localhost/online_offenceTracking_system/payment1.php?r=credit/index"; //substitute with your own return urls
$authemail="acmwamuka#gmail.com";//This is the buyer's email address
$additionalinfo="Paying for canteen meals.";
$concat=$int_key.$int_id.$paymentid.$url.$reference.$returnurl.$resulturl.$authemail.$additionalinfo;
$concat=$concat.$int_key;
$values = array('resulturl' => $resulturl,
'returnurl' => $returnurl,
'reference' => $reference,
'amount' => $amount,
'id' => $int_id,
'additionalinfo' => $additionalinfo,
'authemail' => $authemail,
'authphone' => "07777777777",
'status' => 'Message'); //just a simple message
$fields_string = $this->CreateMsg($values,$int_key);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); //need fixing
$result = curl_exec($ch);
if($result)
{
$msg = $this->ParseMsg($result);
if ($msg["status"] == ps_error){
header("Location: $checkout_url");
exit;
}
else if ($msg["status"] == "Ok"){
$validateHash = $this->CreateHash($msg, $int_key);
if($validateHash != $msg["hash"]){
$error = "Paynow reply hashes do not match : " . $validateHash . " - " . $msg["hash"];
echo $error;
}
else
{
$theProcessUrl = $msg["browserurl"];
//echo $theProcessUrl;
//header("Location: ".$theProcessUrl);
Paynow\Payments\Paynow::$app->response->redirect($theProcessUrl);
$orders_array = array();
}
}
else {
//unknown status or one you dont want to handle locally
$error = "Invalid status from Paynow, cannot continue.";
}
}
else
{
$error = curl_error($ch);
echo $error;
}
//print_r($result);
//close connection
curl_close($ch);
}
public function ParseMsg($msg) {
$parts = explode("&",$msg);
$result = array();
foreach($parts as $i => $value) {
$bits = explode("=", $value, 2);
$result[$bits[0]] = urldecode($bits[1]);
}
return $result;
}
function CreateMsg($values, $MerchantKey){
$fields = array();
foreach($values as $key=>$value) {
$fields[$key] = urlencode($value);
}
$fields["hash"] = urlencode($this->CreateHash($values, $MerchantKey));
$fields_string = $this->UrlIfy($fields);
return $fields_string;
}
public function UrlIfy($fields) {
$delim = "";
$fields_string = "";
foreach($fields as $key=>$value) {
$fields_string .= $delim . $key . '=' . $value;
$delim = "&";
}
return $fields_string;
}
public function CreateHash($values, $MerchantKey){
$string = "";
foreach($values as $key=>$value) {
if( strtoupper($key) != "HASH" ){
$string .= $value;
}
}
$string .= $MerchantKey;
$hash = hash("sha512", $string);
return strtoupper($hash);
}
}}
?>
You can use a free service like ngrok to expose your localhost environment to the world wide web. Just make sure your returnurl and resulturl are using your ngrok address so that Paynow can callback your application.

Error in creating record in zohocrm contacts using php 7.1

I am trying to create a record in zohocrm. i am using API version2 code.
i recieve this following error which i stated below. I tried stackoverflow for solutions but can't find relevant solution. I tried this Stackoverflow answer Zoho API V2 Update Record. It doesn't work for me. Help me with some solution. i use php version
7.1
Here's the Code i used:
public function createRecord($module, $module_fields)
{
global $HelperObj;
$WPCapture_includes_helper_Obj = new WPCapture_includes_helper_PRO();
$activateplugin = $WPCapture_includes_helper_Obj->ActivatedPlugin;
$moduleslug = $this->ModuleSlug = rtrim(strtolower($module), "s");
$zohoapi = new SmackZohoApi();
$module_field['data'] = array($module_fields);
$module_field['Owner']['id'] = $module_fields['SMOWNERID'];
$fields_to_skip = ['Digital_Interaction_s', 'Solution'];
foreach ($module_fields as $fieldname => $fieldvalue) {
if (!in_array($fieldname, $fields_to_skip)) {
continue;
}
$module_fields[$fieldname] = array();
if (is_string($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
} else if (is_array($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
}
}
//$fields = json_encode($module_fields);
$attachments = $module_fields['attachments'];
$body_json = array();
$body_json["data"] = array();
array_push($body_json["data"], $module_fields);
$record = $zohoapi->Zoho_CreateRecord($module, $body_json, $attachments);
if ($record['code'] == 'INVALID_TOKEN' || $record['code'] == 'AUTHENTICATION_FAILURE') {
$get_access_token = $zohoapi->refresh_token();
if (isset($get_access_token['error'])) {
if ($get_access_token['error'] == 'access_denied') {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "Access Denied to get the refresh token";
return $data;
}
}
$exist_config = get_option("wp_wpzohopro_settings");
$config['access_token'] = $get_access_token['access_token'];
$config['api_domain'] = $get_access_token['api_domain'];
$config['key'] = $exist_config['key'];
$config['secret'] = $exist_config['secret'];
$config['callback'] = $exist_config['callback'];
$config['refresh_token'] = $exist_config['refresh_token'];
update_option("wp_wpzohopro_settings", $config);
$this->createRecord($module, $module_fields);
} elseif ($record['data'][0]['code'] == 'SUCCESS') {
$data['result'] = "success";
$data['failure'] = 0;
} else {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "failed adding entry";
}
return $data;
}
API Call Code:
public function Zoho_CreateRecord($module = "Lead",$data_array,$extraParams) {
try{
$apiUrl = "https://www.zohoapis.com/crm/v2/$module";
$fields = json_encode($data_array);
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', $this->access_token),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
curl_close($ch);
$result_array = json_decode($result,true);
if($extraParams != "")
{
foreach($extraParams as $field => $path){
$this->insertattachment($result_array,$path,$module);
}
}
}catch(\Exception $exception){
// TODO - handle the error in log
}
return $result_array;
}
error i got:
Array
(
[data] => Array
(
[0] => Array
(
[code] => INVALID_DATA
[details] => Array
(
[expected_data_type] => jsonarray
[api_name] => Solution_Interest
)
[message] => invalid data
[status] => error
)
)
)
By the details which you gave ,
(1)you said you wish to create "Contacts" , but the url you are using to create contact doesn't seems to create "Contacts" either by
**converting leads to account and contact , or
**directly creating contact
(2)you mentioned module name as "Lead" , try changing it to "Leads".
(3)variables $data_array & $extraParams , doesn't seems to hold any value , they seems to be null.
(4)Here is a help doc. for you
Create Contact
If that still doesn't solve your problem ,you could ask your queries at zoho crm community , people will definitely solve your queries Ask here

curl headers multipart/form already sent

Dear Stackoverflow users,
I am running into a problem. It is as follows:
Currently i am programming a management tool for pfsense, which needs to send a multipart form that the server needs to validate and process. It should enable the voucher based acces control on the interface. However, i am getting the error that my headers are already sent. I did not sent them.
my code is as follows:
protected function doCurl($resourceID=null, $post=null)
{
//volledige url
$url = Yii::app()->params->pfsense['host'].$resourceID;
$ch = curl_init();
if($post != null)
{
$post_string = "";
foreach($post as $key=>$value)
{
if($key != 'enctype')
{
$post_string .= $key.'='.$value.'&';
}
else
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data'
));
}
}
rtrim($post_string, '&');
//var_dump($post);
/**/
curl_setopt($ch,CURLOPT_POST, count($post));
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
//var_dump($post_string);
}
else
{
curl_setopt($ch, CURLOPT_HEADER, true);
}
curl_setopt($ch, CURLOPT_URL, $url);
//omdat het certificaat niet klopt zetten we de verificatie uit.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//we setten de useragent en de timeout. Useragent omdat sommige websites iets anders voorschotelen per browser.
//timeout voor als er iets gebeurd wat niet moet
curl_setopt($ch,CURLOPT_USERAGENT,Yii::app()->params->pfsense['useragent']);
curl_setopt($ch,CURLOPT_COOKIEJAR, Yii::app()->params->pfsense['cookiepath']);
curl_setopt($ch,CURLOPT_COOKIEFILE, Yii::app()->params->pfsense['cookiepath']);
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
$result = array( 'header' => '',
'body' => '',
'http_code' => '',
'last_url' => '');
$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
$result['header'] = substr($response, 0, $header_size);
$result['body'] = substr( $response, $header_size );
$result['http_code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
$result['last_url'] = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
//curl_close($ch);
return $result;
}
public function curl($resourceID=null, $post=null)
{
$result = $this->doCurl($resourceID, $post);
if(strpos($result['body'], 'Login') == false && $result['http_code'] != 403)
{
//echo $result['body'];
return $result;
}
else
{
$loginpost = array(
'__csrf_magic' => substr($result['body'], strpos($result['body'],'sid:') , 55),
'login' => urlencode('Login'),
'usernamefld' => urlencode(Yii::app()->params->pfsense['pfuser']),
'passwordfld' => urlencode(Yii::app()->params->pfsense['pfpass'])
);
$result = $this->doCurl('',$loginpost);
$result = $this->doCurl($resourceID, $post);
return $result;
}
}
This is the code that allows a curl request to be sent to the server. If the page that is returned is the login page, the login info needs to be sent and the original post request needs to be sent again.
the code that follows is the code to insert a zone:
public function insertZone($post)
{
$description = $post['description'];
$interface = $post['interfaces'];
$name = $post['name'];
$post=null;
$post['zone'] = $name;
$post['descr'] = $description;
$post['Submit'] = 'Continue';
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoinsertzone']);
$post['__csrf_magic'] = substr($result['body'], strpos($result['body'],'sid:') , 55);
var_dump($post);
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoinsertzone'], $post);
var_dump($result['body']);
//exit;
if(strpos($result['body'], 'The following input errors were detected') == false)
{
$post = null;
$post['enable'] = 'yes';
$post['interfaces'] = $interface;
$post['Submit'] = 'Save';
$post['name'] = $name;
$result = $this->editZone($post);
if($result != false)
{
$post = null;
$post['zone'] = $name;
$post['enable'] = 'yes';
$post['Submit'] = 'Save';
$result = $this->curl(Yii::app()->params->pfsense['pfpathtovoucherroll'].$name);
$post['__csrf_magic'] = substr($result['body'], strpos($result['body'],'sid:') , 55);
$doc = new DOMDocument();
$doc->loadHTML($result['body']);
$doc->preserveWhiteSpace = false;
if($childs = $doc->getElementsByTagName("textarea"))
{
foreach($childs as $child)
{
if($child->nodeType == XML_TEXT_NODE)
{
continue;
}
if(strpos(trim($child->nodeValue),'BEGIN RSA PRIVATE KEY'))
{
$post['privatekey'] = trim($child->nodeValue);
}
elseif(strpos(trim($child->nodeValue),'BEGIN PUBLIC KEY'))
{
$post['publickey'] = trim($child->nodeValue);
}
}
}
$post['charset'] = $doc->getElementById('charset')->attributes->getNamedItem('value')->nodeValue;
$post['rollbits'] = $doc->getElementById('rollbits')->attributes->getNamedItem('value')->nodeValue;
$post['ticketbits'] = $doc->getElementById('ticketbits')->attributes->getNamedItem('value')->nodeValue;
$post['checksumbits'] = $doc->getElementById('checksumbits')->attributes->getNamedItem('value')->nodeValue;
$post['magic'] = $doc->getElementById('magic')->attributes->getNamedItem('value')->nodeValue;
$result = $this->curl(Yii::app()->params->pfsense['pfpathtovoucherroll'].$name, $post);
if($result['http_code'] >= 100 && $result['http_code'] <= 299)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
public function editZone($post)
{
$zone = $post['name'];
$interfaces = $post['interfaces'];
$post = null;
//$post['localauth_priv'] = 'yes';
//$post['radiussrcip_attribute'] = strtolower($interfaces);
if(is_array($interfaces))
{
$post['cinterface[]'] = array_map('strtolower', $interfaces);
}
else
{
$post['cinterface[]'] = strtolower($interfaces);
}
$post['auth_method'] = 'local';
$post['radiussrcip_attribute'] = 'wan';
$post['radiusvendor'] = 'default';
$post['radmac_format'] = 'default';
$post['enable'] = 'yes';
$post['Submit'] = 'Save';
$post["maxprocperip"] = '';
$post["idletimeout"] = '';
$post["timeout"] = '';
$post["freelogins_count"] = '';
$post["freelogins_resettimeout"] = '';
$post["preauthurl"] = '';
$post["redirurl"] = '';
$post["blockedmacsurl"] = '';
$post["bwdefaultdn"] = '';
$post["bwdefaultup"] = '';
$post["radiusip"] = '';
$post["radiusport"] = '';
$post["radiuskey"] = '';
$post["radiusip2"] = '';
$post["radiusport2"] = '';
$post["radiuskey2"] = '';
$post["radiusip3"] = '';
$post["radiusport3"] = '';
$post["radiuskey3"] = '';
$post["radiusip4"] = '';
$post["radiusport4"] = '';
$post["reauthenticateacct"] = '';
$post["radmac_secret"] = '';
$post["radiusvendor"] = 'default';
$post["radiusnasid"] = '';
$post["radmac_format"] = 'default';
$post["httpsname"] = '';
$post['certref'] = '';
$post['enctype'] = true;
$post['zone'] = $zone;
$post['enable'] = 'yes';
$post['Submit'] = 'Save';
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoupdatezone'].$zone);
//echo $result['last_url'];
$post['__csrf_magic'] = substr($result['body'], strpos($result['body'],'sid:') , 55);
//var_dump($post);
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoupdatezone'].$zone, $post);
ini_set('xdebug.var_display_max_depth', -1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
var_dump($result['body']);
exit;
if($result['http_code'] >= 100 && $result['http_code'] <= 299)
{
return true;
}
else
{
//var_dump($result);
///exit;
return $result;
}
}
This code works by first inserting a zone with the name and description and then updating it to set the interface active and enabling the captive portal page to be displayed. However, if i sent the page without the multipart form(it seems to be that this is the issue) then the authentication is not set correctly. It is set, but it does not work. If i then manually change the authentication setting (it is a radio button, if i choose another radio button and then choose my original radio button it suddenly works)
has anyone have a clue about what i am doing wrong? because with the following code i get the result that my headers are already sent:
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoupdatezone'].$zone, $post);
ini_set('xdebug.var_display_max_depth', -1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
var_dump($result['body']);
exit;
i would appreciate all the help i can get.
thanks in advance!
What got my request to work:
it turned out that there was no enctype needed in the request. It was however, needed that the update request was sent a 3th time. Do'nt ask me why.
If anything, anything at all, is output, e.g. echo, var_dump, you will get this error.
curl sets the headers to application/x-www-form-urlencoded. If the post data is sent as a string.
If it is sent as an array, it uses a Content-Type: multipart/form-data
If that is not it, add this to see the Request header:
Now I am not sure exactly how you fixed it, but you may have a problem.
It appears your data is in an array and then sent as a sting for some unknown reason.
It should have stayed in the array. This code is off.
The else will be executed for every foreach loop. Probably will not hurt anything it is just a mistake
foreach($post as $key=>$value)
{
if($key != 'enctype')
{
$post_string .= $key.'='.$value.'&';
}
else
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
}
}
Should have been:
if($key == 'enctype'){
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
}
else{
foreach($post as $key=>$value){
$post_string .= $key.'='.$value.'&';
}
}
I think you sent the data as a string, or not at all.
This is the big question: if($key != 'enctype') Why? Is this open source?
The above loop would be used only if the post data had to be sent encoded.
And this part:
if($key == 'enctype'){
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
}
Should just be:
if($key == 'enctype'){
$post_string = $post;
}
This way, because the post data is in an array curl will automatically use Content-Type: multipart/form-data
The problem is if it is sent as a string curl will use application/x-www-form-urlencoded, then you have to add this after the loop:
$post_string = urlencode($post_string);
Like this:
else{
foreach($post as $key=>$value){
$post_string .= $key.'='.$value.'&';
}
$post_string = urlencode($post_string);
}

Send JSON HTTP query without CURL

Can anyone help with the following
I'm trying to make a JSON request to a RESTful API. The code below is kindly shared by Wes Furlong
The code seems to be able to decode to JSON fine but sends as a URL encoded string
<?php
function rest_helper($url, $params = null, $verb = 'GET', $format = 'json')
{
$cparams = array(
'http' => array(
'method' => $verb,
'ignore_errors' => true
)
);
if ($params !== null) {
$params = http_build_query($params);
if ($verb == 'POST') {
$cparams['http']['content'] = $params;
} else {
$url .= '?' . $params;
}
}
$context = stream_context_create($cparams);
$fp = fopen($url, 'rb', false, $context);
if (!$fp) {
$res = false;
} else {
// If you're trying to troubleshoot problems, try uncommenting the
// next two lines; it will show you the HTTP response headers across
// all the redirects:
// $meta = stream_get_meta_data($fp);
// var_dump($meta['wrapper_data']);
$res = stream_get_contents($fp);
}
if ($res === false) {
throw new Exception("$verb $url failed: $php_errormsg");
}
switch ($format) {
case 'json':
$r = json_decode($res);
if ($r === null) {
throw new Exception("failed to decode $res as json");
}
return $r;
case 'xml':
$r = simplexml_load_string($res);
if ($r === null) {
throw new Exception("failed to decode $res as xml");
}
return $r;
}
return $res;
}
I need to be able to:
Add a content type of application/json
Convert params to JSON
Can't use curl in this environment
The main thing is the content type -- currently defaults to urlencoded
Any tips or ideas appreciated - Thanks
Latest attempt
function restHelper($url, $params = null, $verb = 'GET', $format = 'json'){
$cparams = array(
'http' => array(
'method' => $verb,
'ignore_errors' => true,
'header' =>"Content-type: application/json \r\n"
)
);
if ($params !== 'None') {
$jparams = json_encode($params);
if ($verb == 'POST') {
$cparams['http']['content'] = $jparams;
} elseif ($verb =='PUT') {
$cparams['http']['content'] = $jparams;
} else {
$params = http_build_query($params);
$url .= '?' . $params;
}
}
Still not working -- API tests fine from REST IDE Seems to be from how the content type is working for JSON
In the end found a way of including CURL in scriptcase.
Here is what worked (prototype)
(Thanks Lorna Jane http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl)
Thanks everyone that looked at this
$service_url = 'http://dev.eventplus.co.nz/api/logon';
$ch = curl_init($service_url);
$data = '[
{
"Header": {
"Username": "testapi#teamprema.co.nz",
"SessionId": "123"
}
},
{
"Config": {}
},
{
"Params": {"Query": {"Password": "test12345"}}
}
]';
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$response = curl_exec($ch);
if ($response === false) {
$info = curl_getinfo($ch);
curl_close($ch);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($ch);
print $response;

Categories