if is_numeric condition issue - php

I have a http_build_query array and file_get_contents that looks like this:
$optionValues = http_build_query( array(
'leadcomm' => getVariable('LEADCOMM'),
'CCID' => getVariable('CCID'),
'QTR' => getVariable('QTR'),
'CLK' => getVariable('CLK'),
'dck' => getVariable('DCK'),
'bal_one' => getVariable('BAL_ONE'),
'product' => getVariable('PRODUCT'),
'prop_st' => getVariable('PROP_ST'),
'cred_grade' => getVariable('CRED_GRADE'),
'prop_zip' => getVariable('PROP_ZIP'),
'prop_desc' => getVariable('PROP_DESC'),
'spec_home' => getVariable('SPEC_HOME'),
'purchase_contract' => getVariable('PURCHASE_CONTRACT'),
'est_val' => getVariable('EST_VAL'),
'down_pmt' => getVariable('DOWN_PMT'),
'loan_type' => getVariable('LOAN_TYPE'),
'buy_timeframe' => getVariable('BUY_TIMEFRAME'),
'agent_found' => getVariable('AGENT_FOUND'),
'va_status' => getVariable('VA_STATUS'),
'income' => getVariable('INCOME'),
'annual_verifiable_income' => getVariable('ANNUAL_VERIFIABLE_INCOME'),
'fha_bank_foreclosure' => getVariable('FHA_BANK_FORECLOSURE'),
'num_mortgage_lates' => getVariable('NUM_MORTGAGE_LATES'),
'email' => getVariable('EMAIL'),
'fname' => getVariable('FNAME'),
'lname' => getVariable('LNAME'),
'address' => getVariable('ADDRESS'),
'city' => getVariable('CITY'),
'state' => getVariable('STATE'),
'zip' => getVariable('ZIP'),
'pri_phon' => getVariable('PRI_PHON'),
'sec_phon' => getVariable('SEC_PHON'),
'capture_method' => getVariable('CAPTURE_METHOD'),
'aid' => getVariable('AID'),
'srlp' => getVariable('SRLP'),
'scid' => getVariable('SCID'),
'buyer_id' => getVariable('BUYER_ID'),
'cid' => getVariable('CID'),
'ppcid' => getVariable('PPCID')
)
);
$url = 'http://api.example.com/import-lead-data.php';
$options['http'] = array(
'method' => "POST",
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $optionValues,
);
$context = stream_context_create($options);
$result = file_get_contents($url, NULL, $context);
I need to check if $results returns a numeric value. If it does, I need to set a new variable ($lead_id) to equal $results, pass $lead_id through another http_build_query array and finally do another file_get_contents $results. The code above works fine. The second part of the code is where I need some assistance. This is what I have for the second part of my code:
if (is_numberic($result)) {
$lead_id(isset($results));
};
$leadValues = http_build_query( array(
'lead_id' => "LEAD_ID"
)
);
$leadurl = 'http://api.bankradar.com/import-lead-response.php';
$leadoptions['http'] = array(
'method' => "POST",
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $leadValues,
);
$leadcontext = stream_context_create($leadoptions);
$leadResult = file_get_contents($leadurl, NULL, $leadcontext);
I think my problem is with the isset part of the code but I'm not sure.

you put
if (is_numberic($result)) {
should be
if (is_numeric($result)) {
But, i use this way
if (ctype_digit($result)) {
that way it can only containt digits, no decimals or any other characters... not sure if thats what your after

You are calling $lead_id as a function. Just change
$lead_id(isset($results));
to
$lead_id = $results;

You misspelled is_numeric (there's a b in yours) - is_numberic

Related

Identifying unknown structured data formats – what could be class-oriented JSON

I'm currently working with a Sophos UTM, pushing the wireless statistics to another platform and trying to digest this data format.
It's clearly structured and looks like class-oriented JSON, but cannot quite figure out what it is or how to convert it to something usable. Any ideas? I thought about just writing a JSON-converter in PHP, but I'm afraid that I might just be missing a puzzle piece.
{
'clients' => {
'0c:2c:54:xx:xx:xx' => {
'ap' => '',
'connected_time_sec' => 1720,
'connected_time_str' => '00:28:40',
'hwaddr' => '0c:2c:54:xx:xx:xx',
'ip' => '172.16.28.206',
'last_rxrate_bps' => '1048576',
'last_rxrate_str' => '1024.0 kbit/s',
'last_txrate_bps' => '6815744',
'last_txrate_str' => '6.5 Mbit/s',
'lastseen_str' => '2018-11-04 18:06:37',
'lastseen_ts' => 1541351197,
'mesh_id' => '',
'mesh_mode' => 'none',
'name' => 'HUAWEI_P20_Pro',
'radio_id' => '0',
'signal_per' => '39',
'ssid' => 'ssid',
'vendor' => 'unknown'
},
'44:d8:84:xx:xx:xx' => {
'ap' => 'A40001AXX8FXXXX',
'connected_time_sec' => 534992,
'connected_time_str' => '06:04:36:32',
'hwaddr' => '44:d8:84:xx:xx:xx',
'ip' => '172.16.28.149',
'last_rxrate_bps' => '1048576',
'last_rxrate_str' => '1024.0 kbit/s',
'last_txrate_bps' => '60607488',
'last_txrate_str' => '57.8 Mbit/s',
'lastseen_str' => '2018-11-04 20:44:28',
'lastseen_ts' => 1541360668,
'mesh_id' => '',
'mesh_mode' => 'none',
'name' => 'iMac-OBC',
'radio_id' => '0',
'signal_per' => '65',
'ssid' => 'ssid',
'vendor' => 'Apple'
}
},
'connected' => {
'A40001AXX8FXXXX' => {
'associated_clients' => [
'ab:cd:ef:gh:ij:kl',
'44:d8:84:xx:xx:xx',
],
'bss' => undef,
'id' => 'A40001AXX8FXXXX',
'ip' => '192.168.10.11',
'lan_mac' => '00:1a:8c:xx:xx:xx',
'location' => 'AP30',
'type' => 'AP30',
'wifi_mac' => '00:1a:8c:xx:xx:xx'
},
'A4000EASIJDFSDOI' => {
'associated_clients' => [],
'bss' => undef,
'id' => 'A4000EASIJDFSDOI',
'ip' => '192.168.10.12',
'lan_mac' => '00:1a:8c:xx:xx:xx',
'location' => 'AP30',
'type' => 'AP30',
'wifi_mac' => '00:1a:8c:xx:xx:xx'
}
},
'disconnected' => {},
'lastupdate' => 1541360678
}
Your sample data has 4 repairs to make on the road to valid json town.
Make the following replacements:
=> to :
' to "
remove all trailing , that are followed by zero or more whitespace characters then a ]
wrap your undef values in double quotes
Code: (Demo)
$almostjson = <<<ALMOSTJSON
...your input string
ALMOSTJSON;
$json = preg_replace(["~=>~", "~'~", "~,(?=\s*])~", "~:\s+\Kundef~"], [':', '"', '', '"$0"'], $almostjson);
var_export(json_decode($json, true));
Calling regex functions on strings that contain key-value relationships is vulnerable to unintended matching. This "solution" should be considered a "bandaid" until the source of the data can be improved. This solution may silently fail in the future if the wrong quality of text is in the string.

How Do I Prevent Duplicates When Adding Leads to SuiteCRM?

The developer guide for SuiteCRM is kind of incomplete (at least here in Q4 2017) compared to the old SugarCRM one that it was based on before the software fork. So, by downloading the WordPress Plugin for SugarCRM, I was able to figure out the REST API and JSON for adding a sales lead into SuiteCRM with the following code.
Now how do I prevent duplicates by home phone, mobile phone, or email address?
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
header('Content-Type: text/plain');
CRM::loginCRM('admin','xxxxPASSWORDxxxxxx');
$aResult = CRM::addLead(array(
'name' => 'John Doe',
'description' => 'sample description',
'salutation' => 'Mr.',
'first_name' => 'John',
'last_name' => 'Doe',
'do_not_call' => 'No',
'phone_home' => '202-111-2222',
'phone_mobile' => '202-111-2222',
'email1' => 'test#example.com',
'primary_address_street' => '123 Main Street',
'primary_address_street2' => '',
'primary_address_street3' => '',
'primary_address_city' => 'New York',
'primary_address_state' => 'NY'
));
print_r($aResult);
CRM::logoutCRM();
die('OK');
/////////////////////////
class CRM {
private static $SessionID = '';
private static $URL = 'https://mycrmserver-example.com/service/v4_1/rest.php';
private static $User = '';
private static $Shadow = '';
public static function sendJSON($a) {
$s = file_get_contents(
self::$URL,
false,
stream_context_create(
array(
'http' => array (
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => http_build_query($a)
)
)
)
);
$a2 = json_decode($s);
return $a2;
}
public static function loginCRM($sUser,$sPass) {
$sShadow = md5($sPass);
self::$User = $sUser;
self::$Shadow = $sShadow;
$asLogin = array (
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'user_auth' => array(
'user_name' => $sUser,
'password' => $sShadow,
'version' => 1
),
'application_name' => 'RestTest',
'name_value_list' => array()
))
);
$a = self::sendJSON($asLogin);
self::$SessionID = $a->id;
}
public static function logoutCRM() {
$asLogin = array (
'method' => 'logout',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'user_auth' => array(
'user_name' => self::$User,
'password' => self::$Shadow,
'version' => 1
),
'application_name' => 'RestTest',
'name_value_list' => array()
))
);
self::sendJSON($asLogin);
}
public static function addLead($a) {
$asNameValueList = array();
foreach($a as $sKey => $sVal) {
$asNameValueList[] = array('name'=>$sKey,'value'=>$sVal);
}
$asAddEntry = array (
'method' => 'set_entry',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'session' => self::$SessionID,
'module_name' => 'Leads',
'name_value_list' => $asNameValueList
))
);
$a = self::sendJSON($asAddEntry);
return $a;
}
} // end CRM
Add these functions into your CRM class and check them before adding a lead. I had a little help from this answer that incidentally gave me some insights. Also, I recommend you do things to tighten down your security such as add an .htaccess or NGINX rule that only allows certain IP addresses or require certain headers to reach anything in your /service folder, and /service/* subfolders either over HTTP or HTTPS.
public static function leadExistsByPhone($sHomePhone,$sMobilePhone) {
$sHomePhone = (empty($sHomePhone)) ? 'xxxxxinvalid' : $sHomePhone;
$sMobilePhone = (empty($sMobilePhone)) ? 'xxxxxinvalid' : $sMobilePhone;
$asCheck = array (
'method' => 'get_entry_list',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'session' => self::$SessionID,
'module_name' => 'Leads',
'query' => "
leads.phone_home = '$sHomePhone'
OR leads.phone_mobile = '$sMobilePhone'
",
'order_by' => 'leads.date_entered DESC',
'offset' => '0',
'select_fields' => array(),
'link_name_to_fields_array' => array(),
'max_results' => 999999,
'deleted' => false
))
);
$a = self::sendJSON($asCheck);
$nCount = # $a->result_count;
$nCount = intval($nCount);
return ($nCount > 0);
}
public static function leadExistsByEmail($sEmail) {
if (!filter_var($sEmail, FILTER_VALIDATE_EMAIL)) {
die('DENIED: invalid email address format');
}
$asCheck = array (
'method' => 'get_entry_list',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'session' => self::$SessionID,
'module_name' => 'Leads',
'query' => "
leads.id IN
(
SELECT email_addr_bean_rel.bean_id
FROM email_addr_bean_rel
JOIN email_addresses
ON email_addr_bean_rel.email_address_id = email_addresses.id
WHERE
email_addresses.email_address = '$sEmail'
)
",
'order_by' => 'leads.date_entered DESC',
'offset' => '0',
'select_fields' => array(),
'link_name_to_fields_array' => array(),
'max_results' => 999999,
'deleted' => false
))
);
$a = self::sendJSON($asCheck);
$nCount = # $a->result_count;
$nCount = intval($nCount);
return ($nCount > 0);
}

AddOrder issue on WHMCS Local API

I'm adding a new order using WHMCS local API. Everything works fine except custom fields.
$command = 'AddOrder';
$postData = array(
'clientid' => $client_id,
'pid' => array($product_id),
'billingcycle' => array('monthly'),
'customfields' => array(base64_encode(serialize(array(1 => $site_id)))),
'paymentmethod' => 'stripe',
);
return localAPI($command, $postData);
My custom field ID is 53 but I set the key to 1 because of tutorials. Also I tried 53 as key array(base64_encode(serialize(array(53 => $site_id)))) but nothing changed.
Do you have any suggestion?
Try this:
$command = 'AddOrder';
$postData = array(
'clientid' => $client_id,
'pid' => array($product_id),
'billingcycle' => array('monthly'),
'customfields[0]' => array(base64_encode(serialize(array(1 => $site_id)))),//changes here
'paymentmethod' => 'stripe',
);
return localAPI($command, $postData);ode here

Elastica add documents overrides existing ones

When i try to add new documents to an index type , i loose existing documents which are overwritten by the new added ones . The problem can be related to the id of each added document ??
Here is the code :
$elasticaClient = new \Elastica\Client(array(
'host' => $this->container->getParameter('elastic_host'),
'port' => $this->container->getParameter('elastic_port')
));
$elasticaIndex = $elasticaClient->getIndex('app');
$elasticaIndex->create(
array(
'number_of_shards' => 4,
'number_of_replicas' => 1,
'analysis' => array(
'analyzer' => array(
'indexAnalyzer' => array(
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => array('lowercase', 'mySnowball')
),
'searchAnalyzer' => array(
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => array('standard', 'lowercase', 'mySnowball')
)
),
'filter' => array(
'mySnowball' => array(
'type' => 'snowball',
'language' => 'German'
)
)
)
),
true
);
$elasticaType = $elasticaIndex->getType('type');
$mapping = new \Elastica\Type\Mapping();
$mapping->setType($elasticaType);
$mapping->setParam('index_analyzer', 'indexAnalyzer');
$mapping->setParam('search_analyzer', 'searchAnalyzer');
$mapping->setProperties(array(
'id' => array('type' => 'string'),
'title' => array('type' => 'string'),
'duration' => array('type' => 'string'),
'start' => array('type' => 'string'),
'end' => array('type' => 'string'),
));
// Send mapping to type
$mapping->send();
$documents = array();
foreach($medias as $media) {
$id = uniqid() ;
$documents[] = new \Elastica\Document(
$id,
array(
'id' => $id,
'title' => $media['title'],
'duration' => $media['duration'],
'start' => $media['start'],
'end' => $media['end'],
)
);
}
$elasticaType->addDocuments($documents);
$elasticaType->getIndex()->refresh();
Please i need your help . Thank you
PHP does not recommend using uniqid for this use case. Since you are wanting a random, safe id, let Elasticsearch do it for you. The Elastica Document construct method notes that the id field is optional. So don't pass it and let Elasticsearch issue the id.
Several things
$elasticaIndex->create (....) you only have to enter it once. Index is unique after creating the index that you can comment or generate a different index and other things. I leave an example that works.
class PersistencyElastic
{
private $conection;
public function __construct()
{
$this->conection = new \Elastica\Client(['host' => '127.0.0.1', 'port' => 9200]);
}
public function save($ msg)
{
// $ msg is an array with whatever you want inside
$index = $this->conection->getIndex('googlephotos');
// This is the index I created, it's called googlephotos
// $index->create(array (), true);
$type = $index->getType('googlephotos');
$type->addDocument(new Document (uniqid ('id _', false), $msg, $type, $index));
$index->refresh();
}
}

POST request only with http_build_query in php

I need to create a POST request with http_build_query. Following are my codes:
$uri_args = array (
'name' => 'Jack',
'surname' => 'Jackson',
'username' => 'jackson12',
'email' => 'Jack#mail.com',
);
$uri = http_build_query($uri_args);
header("Location: http://samplesite.com?$uri");
At the moment it generates a request like GET, but I need POST.
Consider that I do not want to use curl, ... only http_build_query.
<?php
$data = array(
'name' => 'Jack',
'surname' => 'Jackson',
'username' => 'jackson12',
'email' => 'Jack#mail.com',
);
$query = http_build_query($data);
// create context
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL,
'content' => $query,
),
));
// send request and collect data
$response = file_get_contents(
$target = "http://example.com/target.php",
$use_include_path = false,
$context);
//some actions with $response
//...
// redirect
header("Location: http://samplesite.com");

Categories