Calling PHP wrapper on client side - javascript

I´m currently working on a school project, where we are using Apache cordova (HTML, CSS and JS side) and currently our school has a server, where our .php file is located.
In our project, (one of the HTML files) we use API key and an domain address, that we want to get rid off from source code (so other students cant see it). What would be easiest way to execute this?
We´ve been thinking following;
We use the php-file as a wrapper with the following code;
IE.
<?php
function getJson($data){
$decoded = json_decode($data);
if (isset($decoded)){
// Toteutusten haku
$url = "URL THAT WE DONT WANT TO BE SEEN";
$apiKey = "API KEY GOES HERE";
// curl
$ch = curl_init($url);
// curl_exec returnsanswer (not boolean)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Asets api key, ":"
curl_setopt($ch, CURLOPT_USERPWD, $apiKey.":");
// Setting message - JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Sets false if necessary
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Sends request
$responseJson = curl_exec($ch);
return $responseJson;
curl_close($ch); //close session
**}
}
?>
And in HTML file we have code snippets that looks like following;
// B building rooms
if (buildingcode.startsWith("B", 5)) {
var requestB = new XMLHttpRequest();
requestB.onreadystatechange = function () {
if (requestB.readyState === 4) {
if (requestB.status === 200) {
try {
var jsonB = JSON.parse(requestB.responseText);
for (var fb = 0; fb < jsonB.resources.length; fb++) {
var resB = jsonB.resources[fb];
if (resB.type === "room") {
if (bTilat.indexOf("code")) {
bTilat.push(resB.code + resB.name.slice(resB.name.indexOf(' ('), 50));
}
}
}
} catch (e) {
console.log(e.message);
return;
}
}
}
//console.log(bTilat);
};
requestB.open("GET", 'THIS PART HAS THE DOMAIN WE WANT TO HIDE', true, "THIS PART HAS THE API WE WANT TO HIDE", "");
requestB.send(null);
}
So my question is following; I guess we need to get rid off
requestB.open("GET", 'THIS PART HAS THE DOMAIN WE WANT TO HIDE', true, "THIS PART HAS THE API WE WANT TO HIDE", "");
requestB.send(null);
From html, but how do we request the code from wrapper?
Thank you in advance.

Related

load OTHER LINK if not available

$mp3Linkger = wp_get_attachment_url($mp3_file_id);
$mp3Link = wp_get_attachment_url($mp3_file_id);
$mp3Link = str_replace( 'example.COM', 'static.example.COM', $mp3Link );
$playerTag = '[audio mp3="'.$mp3Linkger.'"][/audio]';
In the above code
$playerTag loads the link
$mp3Linkger Is broadcast
I want to load $mp3Link if $mp3Linkger was not available
Not available like Down Server or 404 error and ...
Update :
Ways that friends tell / Site loading speed slows down :
function check_url($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $mp3Linkger);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
return $headers['http_code'];
}
$check_url_status = check_url($mp3Linkger);
if ($check_url_status == '200') {
$playerTag = '[audio mp3="'.$mp3Linkger.'"][/audio]';
} else {
$playerTag = '[audio mp3="'.$mp3Link.'"][/audio]'; }
I want this process to happen when the user clicks on the link ($playerTag)
That is, if link a is not available, link b will be loaded
.
You should take a look at #fopen();.
fopen — Opens file or URL
Mode
Description
'r'
Open for reading only; place the file pointer at the beginning of the file.
Source # https://www.php.net/manual/en/function.fopen.php
<?php
/**
* Check if CDN's url is valid, if not return fallback
*/
$test = #fopen( '_Your_CDN_URL_goes_here_', 'r' );
if ( $test !== false ) {
// CDN's url is valid
$url = _Your_CDN_URL_goes_here_;
} else {
// CDN's url isn't valid
$fallback = _Your_fallback_URL_goes_here_;
}; ?>

PHP. saving many pages as png from the command line

I access a page via GET (some of its contents are loaded using jquery), on document.ready this page gets saved as a png.
I want to call this page from a command line using inside the command a for loop to save multiple pngs.
How can I do it?
If I run this on the browser it works fine but the idea is not to make it manually, one by one for each gln code.
curl did not work or am I using it wrong?
<script>
#isset($saveCode)
$("#btnPng").click();
#endisset
$("#btnPng").click(function () {
var selected_date = $('#selectReportDate').find(':selected').val() ;
var selected_gln = $('#selectAccount').find(':selected').val() ;
html2canvas($("#printable"), {
onrendered: function (canvas) {
var url = canvas.toDataURL();
$("<a>", {
href: url,
download: selected_date + selected_gln
})
.on("click", function() {$(this).remove()})
.appendTo("body")[0].click()
}
})
});
</script>
command handle code
public function handle()
{
$date = WeeklyTopSheetsData::max('report_date');
$accounts = REF_GA_GLN::Select('gln')->orderBy('account_name')->get();
foreach ($accounts as $account) {
$auxURL = 'http://localhost:8000/topsheet/' . $account['gln'] . '/' . $date . '/1';
$ch = curl_init();
echo $auxURL;
//set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $auxURL);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
}
echo ' FIN';
}
}

PHP & cURL -- Wierd output

I'm mainly playing with PHP and cURL (the code includes some AJAX and HTML as well).
Architecture:
Front <--> Middle <--> Back <-->MySQL
Description:
In my front section I'm creating an AJAX object and doing a POST request with some data (JSON format) obtain from a Form in the HTML.
Data is sent to my middle server (PHP file). This file receives it and json_decodes it. Determines witch switch case to use and sends it to the back server using cURL.
Back server (PHP file) gets data from POST request and it json_decodes the data. It then proceeds to create MySQL connection checks if passwords match. If the passwords match it echos back a string saying "GRATNED".
Data is passed back to middle server and then to front section where AJAX receives it and displays the string.
So...
All of this works perfect. However, for some reason my data contains a 1 at the end. which messes up my Regular Expression in my JS file.
Can you guys please let me know what option do cURL (if that is the case) do I have to modify or what is it that I'm doing that I get that one(1) and how to remove it.
Thank you guys.
Attached is my code & and images of output...
Front
function whenSubmitt()
{
//Get the data that I want to pass
//JS Object
var parameters = {"case":"login",
"username":document.getElementById("username").value,
"password":document.getElementById("password").value
};
//Make into JSON object
parameters = JSON.stringify(parameters);
//Create AJAX object
var xobj = new XMLHttpRequest();
var method = "POST";
var url = "./front.php";
//Open Connection
xobj.open(method,url,true);
xobj.setRequestHeader("content-type", "application/x-www-form-urlencoded");
//When Submit button is pressed
xobj.onreadystatechange = function()
{
if (xobj.readyState == 4 && xobj.status == 200)
{
var respuestas = xobj.responseText;
document.getElementById("msrv_answer").innerHTML = respuestas;
//window.location.replace(respuestas[0]); //REDIRECTS TO NEW PAGE
}
};
xobj.send(parameters);
}
Front PHP
<?php
function contact_middle_man($parameters)
{
$url = "https://myurl/middle/middle.php";
$obj = curl_init();
curl_setopt($obj, CURLOPT_URL, $url);
curl_setopt($obj, CURLOPT_POST, strlen($parameters));
curl_setopt($obj, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($obj, CURLOPT_RETURNTRANSFER, true); //ALLOWS TO GET ANSWER BACK IN STRING FORMAT, AND DOES NOT OUTPUT ANSWER DIRECTLY.
$ans = curl_exec($obj);
curl_close($obj);
return $ans;
}
/*RECEIVE DATA FROM WEB INTERFACE, USER*/
$indata = file_get_contents("php://input");
/*CONTACT MIDDLE MAN, USE CURL*/
$middle_answ = contact_middle_man($indata);
echo $middle_answ;
?>
Middle PHP
<?php
function http_post_back_server($url, $data)
{
$obj = curl_init();
curl_setopt($obj, CURLOPT_URL, $url);
curl_setopt($obj, CURLOPT_POST, strlen($data));
curl_setopt($obj, CURLOPT_POSTFIELDS, $data);
$ans = curl_exec($obj);
curl_close($obj);
return $ans;
}
/*URL TO BACK SERVER*/
$url_myserver = "https://myurl/loginquery_v2_.php";
/*GLOBAL VARS*/
$back_ans ="";
/*RECEIVE DATA FROM POST REQUEST*/
$indata = file_get_contents("php://input");
$data = json_decode($indata, true);
/*MAKE REQUEST TO SERVERS*/
switch($data["case"]){
case "login":
$back_ans = http_post_back_server($url_myserver,$indata);
break;
default:
$back_ans="NADA";
break;
}
/*ANSWER BACK TO FRON END*/
echo $back_ans;
?>
Back PHP
<?php
/*RECEIVING DATA FROM POST REQUEST */
$indata = file_get_contents("php://input");
/*DATA TO JSON OBJ*/
$indata = json_decode($indata, true);
/*CONNECTION TO DATABASE */
$conn=mysqli_connect(myusername, mypassword);
/*CHECKING DATABASE CONNECTIVITY */
if(mysqli_connect_error())
{ echo "Connection Error: ".mysqli_connect_error; }
/*GOOD CONNECTION ... CONTINUE */
$uname = $indata["username"];
$query="SELECT * FROM alpha WHERE username ='".$indata["username"]."'";
$db_output = mysqli_query($conn,$query);
/* CHECK QUERY RESULT */
if($db_output)
{
/* FETCH RESULTS */
while($result = mysqli_fetch_assoc($db_output))
{
/* COMPARE STORE PWD VS RECEIVED PWD */
if($result["password"] == $indata["password"])
{
/*JSON OBJECT*/
echo "ACCESS GRANTED";
}
/* PASSWORDS DOES NOT MATCH */
else
{
/*JSON OBJECT*/
echo "ACCESS DENY";
}
}
}
/*CLOSE DATABASE CONNECITON */
mysqli_close($conn);
?>
PAGE WITH OUTPUT
Thank you guys.
This is occurring because in your Middle PHP, you are missing the CURLOPT_RETURNTRANSFER option in your curl call. As a result, $ans is assigned the value true (because the curl call is successful) and the output from the curl call (ACCESS GRANTED) is echo'ed into the output from Middle PHP, followed by $back_ans, which being true, when it is echo'ed produces a 1 in the output. Thus the string returned to Front PHP is ACCESS GRANTED1. You can fix this by adding this to Middle PHP:
curl_setopt($obj, CURLOPT_RETURNTRANSFER, true);
Then $ans will be assigned the value ACCESS GRANTED instead of true and your output will be as expected.

want to use JavaScript and Ajax to send to a php script using curl to connect to a remote server

Please i want to use JavaScript and Ajax to send to a php script that sends to a remote server using Curl. But the first time i will send to this php script, i will get a result, after the first time i will no longer get a result, except i refresh the page. I want to do this without refreshing the page. that is, i want to send to the remote server so many times and get a result.
function go() {
var xmlhttp = new XMLHttpRequest();
var url = "url.php";
var text = document.getElementById("text").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var variables = "text="+text+"&name="+name+"&email="+email;
xmlhttp.open("POST", url, true);variables in the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = xmlhttp.responseText;
document.getElementById("flash-message").innerHTML = data;
}
}
xmlhttp.send(variables);
}
my php script
<?php
if(!empty($_POST['text']) && !empty($_POST['name']) && !empty($_POST['email']) {
$url = "http://url.com/api";
$xmlString = "
<profile>
<names>
<firstname>john</firstname>
<lastname>doe</lastname>
</names>
</profile>";
$fields = "XML=" . urlencode($xmlString);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo $response = curl_exec($ch);
curl_close($ch);
}else {
echo "Please fill in those fields";
}
?>
As long as you are able to send requests you could get response from the php script.
Check you are sending requests from the browser net panel using firebug
In js code see calling go() function by logging some help text to console panel using console.log('calling go function')

watch local directory for new files in javascript/html5

as title says, is it possible to monitor a local dir in the real filesystem (not html5 sandbox)? I'd like to write an automatic photo uploader that looks for new photos and uploads them.
Potential repeat of Local file access with Javascript.
My understanding is that you can't access the local filesystem directly through a web browser, you have to use an intermediary like the form input tag or drag and drop.
You may be able to get away with accessing the filesystem if you were to use the operating system's javascript interpreter or something like V8. There may also be experimental javascript api's in Chrome that you could look for on the Chrome flags page if thats your browser of choice. That all depends on whether or not you were doing a personal project or something for the web.
Otherwise another scripting language such as PHP, Ruby, or Python would better suit your needs.
You can set a Javascript Timing event. ie: use the setInterval() method.
On the other hand, you can make a button to trigger an onClick event, or any other event, to execute the following code.
NOTE:
If you set an interval, make sure the request was received before sending it again.
For achieving this, you need to check that the readyState of your XML HTTP Request equals 4, as follows:
xmlhttp.readyState == 4
NOTE:
This is for sending the request, parsing the response and putting it in a Javascript array:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "check_dirs.php", true);
xmlhttp.send();
fileArray = new Array();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
xmlDoc = xmlhttp.responseXML;
fileList = xmlDoc.getElementsByTagName("filesChanged");
while (fileArray.length > 0)
// clean the whole array.
// we want to store the newly generated file list
{
fileArray.pop();
}
for (i = 0; i < fileList.length; i++)
{
fileArray[fileArray.length] = fileList[i].childNodes[0].nodeValue;
}
}
}
Moreover, you will need to write a little PHP script to check your custom directory for files newer than a given date, that could be sent in the request by the way, and send an XML response back, like this:
<?php
(...) // check dir. output $files contain the xml nodes for the files to send
// mockup below
// Get our XML. You can declare it here or even load a file.
$xml_builder = '<?xml version="1.0" encoding="utf-8"?>';
$xml_builder .= $files;
// We send XML via CURL using POST with a http header of text/xml.
$ch = curl_init('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.hello..co.uk');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ch_result = curl_exec($ch);
curl_close($ch);
/*
echo $ch_result;
*/
?>
Here are some mockup functions to check the directory and build the XML response:
<?php
function analizeDir($dir)
{
if (is_dir($dir))
{
$dir_resource = opendir($dir);
while (false !== ($res = readdir($dir_resource)))
{
if ($res != "." && $res != ".." && $res != "old")
{
if (is_dir($dir . "\\" . $res)) // this is a subforder
{
analizeDir($dir . "\\" . $res);
} else { // this is a file
checkFile($dir . "\\" . $res);
}
}
}
}
}
function checkFile($file)
{
$today = date("Y-m-d H:i:s");
// if the difference in days between today
// and the date of the file is more than 10 days,
// print it in the response
if (date_diff(datemtime($file), $today) > 10)
{
$files .= "<filesChanged>" . $file . "</filesChanged>";
}
}
?>

Categories