Sending POST data using cURL, by scanning QR code - php

I'm trying to pass some data (JSON) to another page by scanning a QR code.
The page where the data is send to, contains a HTML form. I want to use that form as a last chance to correct the data before sending it to the database.
I found here at S.O. a way to pass the data using cURL: (https://stackoverflow.com/a/15643608/2131419)
QR code library:
http://phpqrcode.sourceforge.net
I use the QR code execute this function:
function passData () {
$url = 'check.php';
$data = array('name' => 'John', 'surname' => 'Doe');
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode($data);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_exec($ch);
curl_close($ch);
# Print response.
return $result;
}
Create QR code:
QRcode::png(passData(), $tempDir.'007_4.png', QR_ECLEVEL_L, 4);
echo '<img src="'.$tempDir.'007_4.png" />';
Check.php
<?php $data = json_decode(file_get_contents("php://input"), true); ?>
<form method="post" action="handle.php">
<input type="text" name="name" value="<?php echo $data['name'];?>" /><br />
<input type="text" name="surname" value="<?php echo $data['surname'];?>" /><br />
<input type="submit" />
</form>
Problem:
I can pass the data to check.php, but it's returning plain text instead of a useable HTML form.
Hope someone can help!
EDIT
Some clarification:
What I actually want is, to scan the QR code, which executes the passData() function. Then the 'QR code scanner app', needs to open a browser, which shows check.php with the form AND the passed data as the values of the input fields.
Now, I get only the response of check.php (plain text).
When I pass an URL instead of the passData() function like:
QRcode::png("http://www.google.com", $tempDir.'007_4.png', QR_ECLEVEL_L, 4);
The app asks if I want to go to http://www.google.com.

QR codes cannot execute code. The only executable type of data you can put in a QR code is a URL. That is why using google.com as a URL opens a web browser to that URL. The QR code itself does not render anything.
What your code is doing is fetching the check.php page when the QR code is generated and then storing the output as the raw data. It isn't a webpage, it is a string like you are seeing in your question. You may be able to pass a javascript URL similar to a bookmarklet but its execution would depend on the QR code reader being used.
bookmarklet example
<?php
function passData() {
// javascript code in a heredoc, you may need to url encode it
return <<<JS
javascript:(function() {
//Statements returning a non-undefined type, e.g. assignments
})();
JS;
}
A better way to do it would be to have your QR code generate a URL like: http://your-site.com/check.php?name=John&surname=Doe and host check.php on your machine. You can use the $_GET data to populate your form and then use javascript to automatically post it as Jah mentioned.

Not the best way but you can do something like this.
Check.php:
<?php
$data = '<form method="post" action="handle.php">
<input type="text" name="name" value="name" /><br />
<input type="text" name="surname" value="surname" /><br />
<input type="submit" />
</form>';
$html = str_replace(PHP_EOL, ' ', $data);
$html = preg_replace('/[\r\n]+/', "\n", $html);
$html = preg_replace('/[ \t]+/', ' ', $html);
$html = str_replace('> <', '><', $html);
?>
<div id="placeholder">
Write HTML here
</div>
<script type="text/javascript">
function write_html(id,data){
var formHtml = data;
document.getElementById(id).innerHTML = formHtml;
}
</script>

Related

Capturing text elements as variables

I am trying to capture the first instance of particular elements from an object. I have an object $doc and would like to get the values of the following.
id, url, alias, description and label i.e. specifically:
variable1 - Q95,
variable2 - //www.wikidata.org/wiki/Q95,
variable3 - Google.Inc,
varialbe4 - American multinational Internet and technology corporation,
variable5 - Google
I've made some progress getting the $jsonArr string however I'm not sure this is the best way to go, and if so I'm not sure how to progress anyway.
Please advise as to the best way to get these. Please see my code below:
<HTML>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=$search&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
var_dump($doc);
echo "<p>";
$jsonArr = $doc->documentElement->nodeValue;
$jsonArr = (string)$jsonArr;
echo $jsonArr;
}
?>
</body>
</HTML>
Since the response to your API request is JSON, not HTML or XML, it's most appropriate to use cURL or Stream library to perform the HTTP request. You can even use something primitive like file_get_contents.
For example, using cURL:
// Make the request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.wikidata.org/w/api.php?action=wbsearchentities&search=google&format=json&language=en");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
// Decode the string into an appropriate PHP type
$contents = json_decode($output);
// Navigate the object
$contents->search[0]->id; // "Q95"
$contents->search[0]->url; // "//www.wikidata.org/wiki/Q95"
$contents->search[0]->aliases[0]; // "Google Inc."
You can use var_dump to inspect the $contents and traverse it like you would any PHP object.

php - curl POST User Input and Hard-coded Query

How can I post some known queries (hard-coded) together with user input?
For example, if I did not need user input, the query would look like this:
$post = "userid=11&token=abcdef&action=set&name=cf_1&value=UserInput";
But, since I need the value from users, I make something like this:
<form action="submit.php" method="post>
Insert cf_1: <input name='value' type='text'>
<input value="submit" type="submit">
</form>
And the php script:
<?php
$url = someurl;
$post = "userid=11&token=abcdef&action=set&name=cf_1";
$options = array( CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS, $post
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
?>
However, using the above form and php script, the user input couldn't be submitted to the server
$post .= '&value='.$_POST['value'];
Make sure you do the necessary cleaning of the $_POST value, though.

Sent data to webservice using json from a form field after it is encrypted to a cipher

Im creating a web payment form.As according to pci I cant store a credit card number so i use a third party api for encrypting thr credit card number.According to that third party documentation,I have to add their script in my html form <script type="text/javascript" src="./-client-2.1.2.js"></script> and also to the form a unique value to the form
<input id="txtEncryptionKey" name="txtEncryptionKey" class="_encryptionkey"
type="hidden" value="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvWpIQFjQQCPpaIlJKpeg
irp5kLkzLB1AxHmnLk73D3TJbAGqr1QmlsWDBtMPMRpdzzUM7ZwX3kzhIuATV4Pe
7RKp3nZlVmcrT0YCQXBrTwqZNh775z58GP2kZs+gVfNqBampJPzSB/hB62KkByhE
Cn6grrRjiAVwJyZVEvs/********+aE16emtX12RgI5JdzdOiNyZEQteU6zRBRJE
ocPWVxExaOpVVVJ5+UnW0LcalzA+lRGRTrQJ5JguAPiAOzRPTK/lYFFpCAl/F8wt
oAVG1c8zO2NcQ0Pko+fmeidRFxJ/did2btV+9Mkze3mBphwFmvnxa35LF+Cs/XJH
DwIDAQAB" />
and to the field I wish to encrypt Credit card number:
<input type="text" name="txtCreditCard" id="txtCreditCard" class="_data"
and also to the submit button
<input type="submit" name="btn_process" value="Submit" id="btn_process" class="_submit btn btn-success">
and here is my entire code
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="./-client-2.1.2.js"></script>
</head>
<body>
<h2>Data Collection</h2><p>
<form action="process.php" method="post">
<input id="txtEncryptionKey" name="txtEncryptionKey" class="encryptionkey"
type="hidden" value="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvWpIQFjQQCPpaIlJKpeg
irp5kLkzLB1AxHmnLk73D3TJbAGqr1QmlsWDBtMPMRpdzzUM7ZwX3kzhIuATV4Pe
7RKp3nZlVmcrT0YCQXBrTwqZNh775z58GP2kZs+gVfNqBampJPzSB/hB62KkByhE
Cn6grrRjiAVwJyZVEvs/2vrxaEpO+aE16emtX12RgI5JdzdOiNyZEQteU6zRBRJE
ocPWVxExaOpVVVJ5+UnW0LcalzA+lRGRTrQJ5JguAPiAOzRPTK/lYFFpCAl/F8wt
oAVG1c8zO2NcQ0Pko+fmeidRFxJ/did2btV+9Mkze3mBphwFmvnxa35LF+Cs/XJH
DwIDAQAB" />
Name: <input type="text" name="name"><br>
Credit card number: <input type="text" name="credit" id="credit" class="_data"><br>
<input type="submit" name="btn_process" value="Submit" id="btn_process" class="_submit btn btn-success">
</form>
</body>
</html>
So what happens here is,my credit card number is taken by the javascript as soon as I click on submit and is converted into a cipher text in the page it self which returns a unique cipher text as something like this
_cipherText=EIQ4H1Tmmxb0wvyfX9HvbSg0SH0ez1GyZSZjQ8OQqKOI8wtY%2B06uq9XlsDSQdmvRtZtCwJv%2FFbo6xxQ4ClPQZN06nO%2BB8Hw3PddPFLqGtViOMCpBif9Tv0LXPy4%2FQ2L%2F5crTjVQa6WdoJABTgFlOcJ8x%2Bs%2FSSmR5Hd7R9SznfpJQp64IQ6FP%2F2ASxpU14YswgDvTumYZ%2BPElbdKG5u71snNWoQNUClWFn4d8yk6%2BaJ%2FDUGWqotpxchhOFvHMePXsdE8%2F2mGlmz5iiOSH5LlvHptenQMtTvHjBuwdMo4rnutjJ%2FRqaR3sWcndZIWYmEZ7OfA%3D%3D
Now usinng a php I need to store this cipher into a variable and sent it to a web service
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg()
{
echo "Hello world!";
}
//creates a token.
function Tokenize()
{
// see details here http:/.turnapi.com/docs/1.0/rest-tokenize
$_id = "763994532109974";
$api_key = "0za2fOfdWU8575BnTH";
$encrypted_data = "acAx/CwWGCURIhwf7gIw36TFmXoGFrFa5l9hCgcGEW4/mVQAAzZuT4XRjktb7XR0sAthHTuSPYegNYUy7g1stP+ypfVBcH0hNiI72N22yy3WYp0VUfAKDp33HBgUVQwg0TWAenRSNbUwC0Qv49E5bubYo4YBnERWi4JNLJZPlEQUfjMovvWQsQdFHd7U79XJZnZQdW92CKFDrTX8bCS4/n0LDEEVBILJGBnjnvKOQjQarsX8OuU6/73qpy36f9Gz3+X6IRfRhVbINNV0Seii6qSXT03NyvbERDsU/CiOrZ1tY0RuiKh4rsvCfPYrX2h67ZZ7nzrz0DeV+BYyo0e06A==";
// CC data to tokenize..
$data = array(
'ID' =>_id,
'APIKey' => $api_key,
'EncryptedData' => $encrypted_data,
'TokenScheme' => 4
);
//convert to JSON
$json = json_encode($data);
echo "Step1 done... ";
echo $json;
//curl config
$url = 'https://test-api..com:8081/TokenServices.svc/REST/TokenizeFromEncryptedValue';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', //we are using json in this example, you could use xml as well
'Content-Length: '.strlen($json),
'Accept: application/json') //we are using json in this example, you could use xml as well
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//call web service
$result = curl_exec($ch);
//decode result
$jsonResult = json_decode($result, true);
//handle result
if ($jsonResult['Success'] == FALSE)
{
echo "Error Message: ";
echo $jsonResult['Error'];
}
else
{
echo "your token is: ";
echo $jsonResult['Token'];
}
}
//writeMsg();
Tokenize();
?>
</body>
</html>
see here $encrypted_data = "acAx/CwWGCURIhwf7gIw36TFmXoGFrFa5l9hCgcGEW4/mVQAAzZuT4XRjktb7XR0sAthHTuSPYegNYUy7g1stP+ypfVBcH0hNiI72N22yy3WYp0VUfAKDp33HBgUVQwg0TWAenRSNbUwC0Qv49E5bubYo4YBnERWi4JNLJZPlEQUfjMovvWQsQdFHd7U79XJZnZQdW92CKFDrTX8bCS4/n0LDEEVBILJGBnjnvKOQjQarsX8OuU6/73qpy36f9Gz3+X6IRfRhVbINNV0Seii6qSXT03NyvbERDsU/CiOrZ1tY0RuiKh4rsvCfPYrX2h67ZZ7nzrz0DeV+BYyo0e06A=="
i need the cipher text i got using when i pressed the submit button..I need the statement in php to retieve this cipher text into the variable $encrypted_data (as of now I have given a standalone data there)
Also there is someproblem in the php section where some payloads are being sent to a webservice using JSON,but I dont seem getting a response( ie the token which is been sent bak as a response from the webservice wehn i sent my token_id,api key and encrypted data
can someone help in making this code working?Im actaully new to php and Im doing all this with the help of their documentation and online steps.Do bear this long question,im a begineer,so I have to present this compeletly.
Thanks in advance
If the CURL request is failing completely you should have an error in curl_error($ch) or if it returns a strange result you can get information about the last request made using curl_info($ch) so some combination of the two should help you work out where an error might be occurring.

Call an URL and send parameters as POST using PHP

I know this is maybe a very dummy question, but I'm facing a requirement with PHP, I've made some very simple things with it, but now I really need help.
I have this scenario:
I invoke a Java Rest WS using the following url:
http://192.168.3.41:8021/com.search.ws.module.ModuleSearch/getResults/jsonp?xmlQuery=%3C?xml%20version%3D'1.0'%20encoding%3D'UTF-8'?%3E%3Cquery%20ids%3D%2216535%22%3E%3CmatchWord%3Ehave%3C/matchWord%3E%3CfullText%3E%3C![CDATA[]]%3E%3C/fullText%3E%3CquotedText%3E%3C!...
But for this I had to use a Java util class to replace some special chars in the xml parameter, because the original xml is something like:
<?xml version='1.0' encoding='UTF-8'?><query ids="16914"><matchWord>avoir</matchWord><fullText><![CDATA[]]></fullText><quotedText><![CDATA[]]></quotedText><sensitivity></sensitivity><operator>AND</operator><offsetCooc>0</offsetCooc><cooc></cooc><collection>0</collection><searchOn>all</searchOn><nbResultDisplay>10</nbResultDisplay><nbResultatsParAspect>...
Now, I've been asked to create a PHP page in which I can set the XML as input and request it to the REST WS using a submit button. I made an approach but not seems to be working, here I paste my code:
<?php
if($_POST['btnSubmit'] == "Submit")
{
$crudXmlQuery = $_POST['inputXml'];
echo $crudXmlQuery;
echo "=================================================";
$xml = str_replace("%", "%25", $crudXmlQuery);
$xml = str_replace("&", "%26", $crudXmlQuery);
$xml = str_replace("=", "%3D", $crudXmlQuery);
echo $xml;
//$ch = curl_init($url);
//curl_setopt ($ch, CURLOPT_POST, 1);
//curl_setopt ($ch, CURLOPT_POSTFIELDS,'inputXml='.$xml);
//$info = curl_exec ($ch);
//curl_close ($ch);
}
?>
<form action="sampleIndex.php" method="post">
Please insert your XML Query
<input type='text' name='inputXml' value='<?=$crudXmlQuery?>'/>
<input type='submit' name='btnSubmit' value='Submit' />
</form>
I commented the part of the cURL since it was giving me some problems, I'm not sure how to handle this requirement yet, if somebody could help me please, I will really appreciate it. Thanks in advance. Best regards.
curl_setopt ($ch, CURLOPT_POSTFIELDS,'inputXml='.$xml);
this is not going to work, you shoud url encode $xml first. (using urlencode function)
The other part - not sure what exactly not working there :) But I do not see you taking the value of input field anywhere in your code:
$crudXmlQuery = $_POST['inputXml'];

sending all $_POST[] value to "nextpage."

Suppose i have many values here with form method POST
$_POST["value1"]
$_POST["value2"]
$_POST["value3"]
$_POST["value4"]
$_POST["value5"]
$_POST["value6"]
$_POST["value7"]
and i want to send them to nextpage.php
any function to do that? Besides using
<form method="POST" action="nextpage.php">
<input type="hidden" name="value1" value="value1 />
</form>
Passing without session
If there is no security concern and your post data contains something like search parameters . For example $_POST has
array('query'=>'keyword', 'orderby' => 'name', 'range' => '4-10' )
You can generate a query string from that data using http_build_query and create anchor tag for user to click and pass on that data to next page along with url.
$url = 'nextpage.php?' . http_build_query($_POST);
it will generate a url like nextpage.php?query=keyword&orderby=name&range=4-10 that you can use in html anchor tag and in next page you can get it from $_GET.
Using session
Alternatively you already have the option you storing it in $_SESSION and after using destroy the session in order to keep your site performance up.
store all your values in $_SESSION and use it in next page, or you can create URL using these values and redirect your page to nextpage.php
For passing post values to next page store the complete $_POST superglobal array variable into session and then on next page you can access those values using $_SESSION variable
Alternatively you can use curl to send HTTP request to next page using POST method
Then those variables will be accessible using $_POST variable on next page
Please refer the code snippet mentioned below as an example for sending HTTP request using post method through curl
$url='http://203.114.240.77/paynetz/epi/fts';
$data = array('login' => '11','pass' => 'Test#123','ttype' =>'NBFundTransfer','prodid'=>'NSE','amt'=>50,'txncurr'=>'INR','txnscamt'=>0,'clientcode'=>007,'txnid'=>uniqid(),'date'=>date('d/m/Y H:i:s'),'custacc'=>'123456789');
$datastring = http_build_query($data);
//die($url.'?'.$datastring);
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
$output = curl_exec($ch);
//echo $output; die;
curl_close($ch);
you can use Session or cookie to access to other page
Use this code.
<!DOCTYPE HTML>
<html>
<head>
<title>First page</title>
</head>
<body onload="document.getElementById('send').submit()">
<form id="send" action="next_page.php" style="display: none;">
<?PHP
foreach($_POST as $key => $val)
{
echo '<input type="hidden" name="'.$key.'" value="'.$val.'" />';
}
?>
</form>
</body>
</html>

Categories