Call an URL and send parameters as POST using PHP - 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'];

Related

how to get unknown string in $_GET method through URL

I want to pass a string from one PHP file to another using $_GET method. This string has different value each time it is being passed. As I understand, you pass GET parameters over a URL and you have to explicitly tell what the parameter is. What if you want to return whatever the string value is from providing server to server requesting it? I want to pass in json data format. Additionally how do I send it as Ajax?
Server (get.php):
<?php
$tagID = '123456'; //this is different every time
$tag = array('tagID' => $_GET['tagID']);
echo json_encode($tag);
?>
Server (rec.php):
<?php
$url = "http://192.168.12.169/RFID2/get.php?tagID=".$tagID;
$json = file_get_contents($url);
#var_dump($json);
$data = json_decode($json);
#var_dump($data);
echo $data;
?>
If I understand correctly, you want to get the tagID from the server? You can simply pass a 'request' parameter to the server that tells the server what to return.
EDIT: This really isn't the proper way to implement an API (like, at all), but for the sake of answering your question, this is how:
Server
switch($_GET['request']) {
case 'tagID';
echo json_encode($tag);
break;
}
You can now get the tagID with a URL like 192.168.12.169/get.php?request=tagId
Client (PHP with CURL)
When it comes to the client it gets a bit more complicated. You mention AJAX, but that will only work for JavaScript. Your php file can't use AJAX, you'll have to use cURL.
$request = "?request=tagID";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '192.168.12.169/get.php' . $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
EDIT: added the working cURL example just for completeness.
Included cURL example from: How to switch from POST to GET in PHP CURL
Client (Javascript with AJAX)
$.get("192.168.12.169/get.php?request=tagId", function(data) {
alert(data);
});

Sending POST data using cURL, by scanning QR code

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>

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.

Parsing XML with PHP?

This has been driving me insane for about the last hour. I'm trying to parse a bit of XML out of Last.fm's API, I've used about 35 different permutations of the code below, all of which have failed. I'm really bad at XML parsing, lol. Can anyone help me parse the first toptags>tag>name 'name' from this XML API in PHP? :(
http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Owl+city&track=fireflies
Which in that case ^ would be 'electronic'
Right now, all I have is this
<?
$xmlstr = file_get_contents("http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Owl+city&track=fireflies");
$genre = new SimpleXMLElement($xmlstr);
echo $genre->lfm->track->toptags->tag->name;
?>
Which returns with, blank. No errors either, which is what's incredibly annoying!
Thank You very Much :) :) :)
Any help greatly, and by greatly I mean really, really greatly appreciated! :)
The <tag> tag is an array, so you should loop through them with a foreach or similar construct. In your case, just grabbing the first would look like this:
<?
$xmlstr = file_get_contents("http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Owl+city&track=fireflies");
$genre = new SimpleXMLElement($xmlstr);
echo $genre->track->toptags->tag[0]->name;
Also note that the <lfm> tag is not needed.
UPDATE
I find it's much easier to grab exactly what I'm looking for in a SimpleXMLElement by using print_r(). It'll show you what's an array, what's a simple string, what's another SimpleXMLElement, etc.
Try using
$url = "http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Owl+city&track=fireflies";
$xml = simplexml_load_file($url);
echo $xml->track->toptags->tag[0]->name;
Suggestion: insert a statement to echo $xmlstr, and make sure you are getting something back from the API.
You don't need to reference lfm. Actually, $genre already is lfm. Try this:
echo $genre->track->toptags->tag->name;
if you wan't to read xml data please follow those steps,
$xmlURL = "your xml url / file name goes here";
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $xmlURL);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: text/xml'
));
$content = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
$obj = new SimpleXMLElement($content);
echo "<pre>";
var_dump($obj);
echo "</pre>";
}
catch(Exception $e){
var_dump($e);exit;
}
You will get array formate of whole xml file.
Thanks.

PHP Regex for IP to Location API

How would I use Regex to get the information on a IP to Location API
This is the API
http://ipinfodb.com/ip_query.php?ip=74.125.45.100
I would need to get the Country Name, Region/State, and City.
I tried this:
$ip = $_SERVER["REMOTE_ADDR"];
$contents = #file_get_contents('http://ipinfodb.com/ip_query.php?ip=' . $ip . '');
$pattern = "/<CountryName>(.*)<CountryName>/";
preg_match($pattern, $contents, $regex);
$regex = !empty($regex[1]) ? $regex[1] : "FAIL";
echo $regex;
When I do echo $regex I always get FAIL how can I fix this
As Aaron has suggested. Best not to reinvent the wheel so try parsing it with simplexml_load_string()
// Init the CURL
$curl = curl_init();
// Setup the curl settings
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
// grab the XML file
$raw_xml = curl_exec($curl);
curl_close($curl);
// Setup the xml object
$xml = simplexml_load_string( $raw_xml );
You can now access any part of the $xml variable as an object, with that in regard here is an example of what you posted.
<Response>
<Ip>74.125.45.100</Ip>
<Status>OK</Status>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
<RegionCode>06</RegionCode>
<RegionName>California</RegionName>
<City>Mountain View</City>
<ZipPostalCode>94043</ZipPostalCode>
<Latitude>37.4192</Latitude>
<Longitude>-122.057</Longitude>
<Timezone>0</Timezone>
<Gmtoffset>0</Gmtoffset>
<Dstoffset>0</Dstoffset>
</Response>
Now after you have loaded this XML string into the simplexml_load_string() you can access the response's IP address like so.
$xml->IP;
simplexml_load_string() will transform well formed XML files into an object that you can manipulate. The only other thing I can say is go and try it out and play with it
EDIT:
Source
http://www.php.net/manual/en/function.simplexml-load-string.php
You really are better off using a XML parser to pull the information.
For example, this script will parse it into an array.
Regex really shouldn't be used to parse HTML or XML.
If you really need to use regular expressions, then you should correct the one you are using. "|<CountryName>([^<]*)</CountryName>|i" would work better.

Categories