How to create a php keyed array with variables for values - php

I’m using drupal to create some custom form that submit to a third party, and I’m trying to bundle my form results - some of which have some conversion functions applied to them - to send to the form recipient.
I’ve used Drupal’s drupal_http_request function on simple forms and its’ worked well, but now that some of my results give value to vars, I’m not sure how to create a keyed array that continues to pass the value of the var.
I know that when I send my form directly to my third party, they receive the correct result, however I am trying to send them the results but redirect to a page in my own site, so i know my form works at least - and it’s just this function of using the trying encode so i have control over redirect that doesn’t.
but I don't even know if a keyed Array can have variables as it's values or not, or if it's a matter of syntax
This is my code:
function formshare_nameform_submit($form_id, &$form_state) {
// Lookup share matrix return value
$shareMatrixValue = setShareMatrixValue($form_state['values']['image_id']);
$langResultsCode = setLangForShare($langCode);
$gender = setGenderForShare($form_state['values']['gender']);
$first_name = $form_state['values']['first_name'];
$last_name = $form_state['values']['last_name'];
$email = $form_state['values']['email'];
$email_friend1 = $form_state['values']['email_friend1'];
$email_friend2 = $form_state['values']['email_friend2'];
$email_friend3 = $form_state['values']['email_friend3'];
$message = $form_state['values']['massage'];
$optin = $form_state['values']['optin'];
$category = $form_state['values']['category'];
$image_id = $shareMatrixValue;
$id_langue = $form_state['values']['id_langue'];
// Make an array of values to pass to 3rd party.
$pass_these = array();
$pass_these['shareMatrixValue'] = $shareMatrixValue;
$pass_these['langResultsCode'] = $langResultsCode;
$pass_these['gender'] = $gender;
$pass_these['first_name'] = $first_name;
$pass_these['last_name'] = $last_name;
$pass_these['email'] = $email;
$pass_these['email_friend1'] = $email_friend1;
$pass_these['email_friend2'] = $email_friend2;
$pass_these['email_friend3'] = $email_friend3;
$pass_these['message'] = $message;
$pass_these['optin'] = $optin;
$pass_these['category'] = $category;
$pass_these['image_id'] = $image_id;
$pass_these['id_langue'] = $id_langue;
// Post the data to 3rd party.
$url = 'http://mythirdpartysite.com';
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
$data = drupal_query_string_encode($pass_these);
drupal_http_request($url, $headers, 'POST', $data);
}

you can either store the variable by reference with &$var or simply store the name of the variable in the array and use $$array['key']; to get the $var value
best thing is create an stdClass object and store the vars as atributes, it works like an associative array but it's cleaner

Related

How to deal with unencoded URL redirects to my website correctly?

We are using CleverReach to redirect people to our website after they have double opt-in their mail account. We redirect the email as a query parameter to our website, like: example.com/thanks?email=foo#bar.com (by setting up a redirect in the CleverReach backend like example.com/thanks?email={EMAIL}). Apparently, the email parameter doesnt get urlencoded by cleverreach.
Now, in Drupal, if the URL is like so: example.com/thanks?email=hello+world#bar.com and using this code:
$request = \Drupal::request();
$email = $request->query->get('email');
$email is hello world#bar.com. Now, I dont know what the correct processing is here. Obviously, I cant tell CleverReach to urlencode their redirects beforehand. I dont even know if that would be best practice or if I need to imlement something...
The only thing I found out is that $_SERVER['QUERY_STRING'] contains the "real" string, which I can urlencode and then redirect, and then, by reading the query params, urldecode them. But I feel like I am missing some crucial inbuilt functionality.
TL;DR
If a website redirects to my website using not urlencoded query params, how do I read them?
My current approach:
<?php
public function redirectIfIllegalUri() {
$request = \Drupal::request();
$email = $request->query->get('email', '');
$needsRedirect = (false !== strpos($email, ' ') || false !== strpos($email, '#'));
if ($needsRedirect && isset($_SERVER['QUERY_STRING']) && false !== strpos($_SERVER['QUERY_STRING'], 'email=')) {
$sqs = $_SERVER['QUERY_STRING'];
$sqs = htmlspecialchars($sqs);
$sqs = filter_var($sqs, FILTER_SANITIZE_STRING);
$sqs = filter_var($sqs, FILTER_SANITIZE_ENCODED);
$sqs = urldecode($sqs);
$sqs = explode('&', $sqs);
foreach ($sqs as $queryParam) {
if (false === strpos($queryParam, 'email=')) continue;
$values = explode('=', $queryParam);
$email = $values[1];
}
$emailEncoded = urlencode($email);
$query = $request->query->all();
$query['email'] = $emailEncoded;
$refreshUrl = Url::fromRoute('<current>');
$refreshUrl->setOptions([
'query' => $query,
]);
$response = new RedirectResponse($refreshUrl->toString(), 301);
$response->send();
return;
}
}
$request = \Drupal::request();
$email = urldecode($request->query->get('email', false));
drupal request() docs
The problem you are facing is that the + will be treated as a space when you get the value from $_GET global variable.
Currently in PHP doesn't exist a method that returns these values without urldecoding and you need to build a custom function to achieve what you are asking:
A simple function will return not encoded input is by using this function:
function get_params() {
$getData = $_SERVER['QUERY_STRING'];
$getParams = explode('&', $getData);
$getParameters = [];
foreach ($getParams as $getParam) {
$parsed = explode('=', $getParam);
$getParameters[$parsed[0]] = $parsed[1];
}
return $getParameters;
}
This solution can be used if you do not have any other option. By using this function you will always get the data encoded.
If you can encode the value from cleverreach then the best approach is to encode it there.
Encoding the value in cleverreach for email hello+world#bar.com will give you this url example.com/thanks?email=hello%2Bworld%40bar.com and in $_GET you will have the email containing the + sign.

How to pass posted data in form of a variable to function?

I am developing an API and I want to send some PHP variables with the posted data through to the API. So far this is how it's working:
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
$cardNumber = $_POST['order_payment_number'];
$oldExpirationDate = $_POST['order_payment_expire_month'] . $_POST['order_payment_expire_year'];
$date = date('m/d/Y', strtotime('+01 months'));
$expirationDate = substr($oldExpirationDate, 2);
When I actually place these variables inside of functions though, the code breaks. Example:
$subscription->setName("Sample Name"); //sends to API perfectly
$subscription->setName($firstName); //Hits an error, does not submit
However when I echo the variables, they print just fine.
echo $firstName; //returns stored data in $_POST['first_name'];

Problems with replacing CiviCRM tokens in API

I'm currently developing a CiviCRM extension, where I need to replace CiviCRM-Tokens (used in pdf and mailing generation) in html code.
I did a little bit of research in the core files and tried to recreate the behaviour in the PDFLetterCommon.php (/civicrm/CRM/Contact/Form/Task/PDFLetterCommon.php) where it replaces the tokens in the postProcess function.
Here is the original CiviCRM Code:
list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($form);
$skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE;
$skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE;
foreach ($form->_contactIds as $item => $contactId) {
$params = array('contact_id' => $contactId);
list($contact) = CRM_Utils_Token::getTokenDetails($params,
$returnProperties,
$skipOnHold,
$skipDeceased,
NULL,
$messageToken,
'CRM_Contact_Form_Task_PDFLetterCommon'
);
...
}
And here is my version for testing:
(this code is located inside an api function in my extension)
$messageToken = CRM_Utils_Token::getTokens($params["html"]);
$returnProperties = array();
if (isset($messageToken['contact'])) {
foreach ($messageToken['contact'] as $key => $value) {
$returnProperties[$value] = 1;
}
}
$skipOnHold = FALSE;
$skipDeceased = TRUE;
$tokenParams = array("contact_id" => 67450);
list($contact) = CRM_Utils_Token::getTokenDetails($tokenParams,
$returnProperties,
$skipOnHold,
$skipDeceased,
NULL,
$messageToken,
'CRM_Contact_Form_Task_PDFLetterCommon'
);
I'm using the default values for $skipOnHold (false) and $skipDeceased (true) and also just passing one (existing) user id into the $params array ($tokenParams in my code).
Here is my problem:
My $messageToken and $returnProperties variables are being filled correctly via CiviCRM's core functions but when I pass them all into CRM_Utils_Token::getTokenDetails() the returned $contact variable holds an empty array.
I'm really out of ideas, I've been looking into CRM/Utils/Token.php where getTokenDetails() is located, but have been unsuccessful in finding the problem with my code.
Thanks in advance for any help!

How to make an automatic code generator in codeigniter

How to make an automatic code generator so that I can send it to a mobile using my API then verify it after checking in php codeigniter
My one related controller looks like:
public function print_patientdetails($id,$veri,$phone,$username) {
if($veri == 0){
$verifycode = "12345"; // here I need an automatic code generator function
$result['verifycode'] = "12345";//and here need to keep the code and pass hidden throughout the pages
echo $this->sendverifymsg($phone, $verifycode);
$result['query'] = $this->panel_model->hospitaldetails($sess_id);
$result['query1'] = $this->register_model->view_register($phone, $username);
$this->load->view('innerheader', $result);
$this->load->view('verify', $result);
$this->load->view('footer', $result);
}else{
$sess_id = $this->session->userdata('id');
$result['query'] = $this->panel_model->hospitaldetails($sess_id);
$result['query1'] = $this->register_model->edit_patient($id);
foreach ($result['query1'] as $row)
{
$phone = $row->phone;
$username = $row->userid;
$email = $row->email;
$this->load->view('print_patientdetail', $result);
echo $this->sendregistermsg($phone, $username);
echo $this->mail($email, $phone, $username);
}
}
}
Just use php uniqid() native function like this:
$verifycode = uniqid();
what i understood is you just need something which can generate a random code for you.
if this is purpose you can use rand(0,99999); function which generates random numbers.
Moreover if you need that this random number should not b one from already generated then you can use db to store random numbers, enter it when it generates and at the time of new generating compare it with already stored random numbers.

How do I pass value via URL to thia PHP code.

<?php
require_once ("RestHandler.php");
$param="";
if(isset($_GET["param"]))
{
$param = $_GET["param"];
}
//var_dump($param);
if(strpos($param,'studentlogin')!==false) // for handling student login requests
{
$param = explode("-",$param);
$param = explode(",",$param[1]);
$stuID = explode("=",$param[0]);
$stuID = $stuID[1];
$pass = explode("=",$param[1]);
$pass = $pass[1];
$restHandler = new RestHandler();
$restHandler->checkStudentLogin($stuID,$pass);
}
else if(strpos($param,'teacherslist')!==false)
{
$restHandler = new RestHandler();
$restHandler->getTeachersList();
}
else if(strpos($param,'questionslist')!==false)
{
$restHandler = new RestHandler();
$restHandler->getQuestionsList();
}
?>
This is the URL to get vale.
If I call this then it works properly.
http://localhost/xampp/api/index.php?param=questionslist
Response in JSON
[{"questionID":"1","statement":"How are you?"},{"questionID":"2","statement":"What is your name?"}]
However for log in (studentlogin) I can't figure out how to pass the value.
To pass array in url do like this
http://localhost/path/index.php?param[]=param1&param[]=param2&param[key]=param3&name=name etc.
To pass values to via url, use whole details when click the link(submit or anything).
for example in your category:
try this:
http://localhost/xampp/api/index.php?param=text-text=[studentID],text=[password]
remove [studentID] with ID and [password] with PASSWORD.
the student details was send via url. this may work.

Categories