We have the following code in Javascript:
var speakMe = function (text) {
var key, lang, url, audio;
key = "key=1234567890";
lang = "sv_se";
url = "http://api.ttsengine.com/api/read?" + key + "&lang=en_us&voice=male1&speed=100&audioformat=ogg&oggbitrate=100&text=" + text;
audio = new Audio(url);
audio.play();
};
It functions well. However, I would like to mask the key. For this I have been advised to use a PHP proxy script.
I found this proxy but I don't know how to implement it. How do I get the data I normally get, but through this proxy?
Per the documentation of your proxy script. you can call your script and pass a url argument which then it will return the content back. you must also set mode=native as another url parameter.
// > ba-simple-proxy.php?url=http://example.com/&mode=native
//
// Response:
//
// > <html>...</html>
//
// Topic: Notes
//
// * Assumes magic_quotes_gpc = Off in php.ini
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP? => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..
This php code decodes the secret key before hashing with SHA 512
$API_SECRET_KEY="W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
$BDAPI_SECRET_KEY=base64_decode($API_SECRET_KEY);
$HMAC_SIGN = base64_encode(hash_hmac('sha512',$MESSAGE,$BDAPI_SECRET_KEY,true));
echo $HMAC_SIGN;
BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==
I want to replicate this in google app script
var Secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg="
var BDSecret= Utilities.base64Decode(Secret)
var hmac = Utilities.base64Encode(Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, BDSecret ));
Logger.log(hmac)
ew5KhLWSJixn8zw4s6VkpYIwvGBjrmjY3LhNWZr9CVEw6W22LOGg+lVzA3uQgOVyICSCffw2bzTepnBdoYtldw==
If I do not decode the API before hashing they return the same result. But for this particular purpose, the key needs to be decoded. The message variable is just my first name "Parit" in case someone wants to replicate.
I thought that Utilities.computeHmacSignature() might not be able to use []byte for the value. So as a workaround, how about using jsSHA? I think that in your case, you can use https://github.com/Caligatio/jsSHA/blob/master/src/sha512.js.
The flow for using jsSHA is as follows.
Flow :
Download sha512.js.
On script editor, create new script as for example, the filename of sha512.js.
Copy and paste the script of sha512.js to the created script.
Copy and paste the sample script to Code.gs of the script editor.
Run myFunction() of the sample script.
Sample script :
function myFunction() {
var message = "Parit";
var secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
var obj = new jsSHA("SHA-512", "TEXT");
obj.setHMACKey(secret, "B64");
obj.update(message);
Logger.log(obj.getHMAC("B64"))
}
Note :
When I tested Parit for message, I got BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==.
It this was not useful for you, I'm sorry.
Update :
By the Google's update at June 19, 2018, Utilities.computeHmacSignature() got to be able to use the byte arrays. By this, using only native Google Apps Scvript, the result can be retrieved without using jsSHA. So I would like to update my answer.
Modified script :
function myFunction() {
var message = "Parit";
var secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
var value = Utilities.base64Decode(Utilities.base64Encode(message));
var key = Utilities.base64Decode(secret);
var out = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, value, key);
var res = Utilities.base64Encode(out)
Logger.log(res)
}
Result :
BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==
Is there a way to obtain the server time without having to first set it? For example, I can simply do:
curl -X PUT -d '{".sv": "timestamp"}' https://SampleChat.firebaseIO-demo.com/servertime.json
which will return the server time, but this sets the value servertime within my firebase instance. I should note that I'm using the REST API.
You can retrieve the server time without writing it by using .info/serverTimeOffset:
var fbRef = new Firebase(URL);
var getServerTime = (function(ref) {
var offset = 0;
ref.child('.info/serverTimeOffset').on('value', function(snap) {
offset = snap.val();
});
return function() {
return Date.now() + offset;
}
})(fbRef);
var now = getServerTime();
I was wondering if they is a way to change the url so it doesn't show the product id at the end. Because this way someone can change the pid and it might direct them to a different page if that pid is in the database.
View
http://WWW.testexample.x10.mx/item/item.php?pid=2
You can do any of this:
1) do post on href click and then access pid from $_POST on server side
2) do base64 or custom encryption for pid value (can be coupled with 1))
3) handle manual pid change on the business side
so it is not a problem for you, just let them do it if they want.
I would go for option 2) but here an example of option 1)
<html><body id="body"><script> function postData(val) {
var frm = document.createElement("form")
frm.action="/data.php";
frm.method="post";
var input=document.createElement("input")
input.name="pid";
input.value = val;
input.type = "hidden";
frm.appendChild(input);
var body= document.getElementById("body");
body.appendChild(frm);
frm.submit();
} </script>View</body></html>
this is example for option 2 using base64 encoding:
View
and then in item.php:
$pid=base64_decode($_GET['pid']);
Is it possible to use SSE to send POST data to PHP like in Ajax?
I've been using AJAX now for quite a while with bad results in long-polling technicues. I have also been thinking about WebSockets, but it seems a bit redundant.
No, SSE cannot send any data to the server.
You can still use SSE to read data in real time and use AJAX to upload any data (you might need a shared database to pass information between AJAX-receiving processes and SSE-sending one).
You can send data via GET.
e.g.
name=john&name=lea
This is a simple script that sends to server number of iteration and the server return progress using SSE.
This Project consists of two files (index.php and ssedemo.php).
index.php contain a text box and a button. the textbox suppose to contain the number of iteration of the loop in ssedemo.php
<h2>Server Sent Event Test</h2>
<form>
<label>Process Duration</label>
<input type="text" id="progVal">
<input type="button" value="Get Messages" onclick="updateProgress()"/>
</form>
<div id="container">
</div>
updateProgress
function updateProgress() {
var input = $('#progVal').val();
var evtSource = new EventSource("ssedemo.php?duration=" + encodeURIComponent(input));
evtSource.addEventListener("progress", function (e) {
var obj = JSON.parse(e.data);
$('#container').html(obj.progress);
if( parseInt(obj.progress) == 100){
evtSource.close();
}
}, false);
}
this function get the content of the textbox using jQuery and then create an eventSource. The EventSource() constructor takes one or two arguments. The first specifies the URL to which to connect. The second specifies the settings, if any, in the form of an EventSourceInit dictionary.
You can pass what you want by adding it to URL as you do with GET.
"ssedemo.php?duration=" + encodeURIComponent(input)
In the server side, you have to set header type and disable cache according to W3C recommendation
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
then you get the data using $_GET as usual.
$TotalNo = $_GET['duration'];
for ($i = 1; $i <= $TotalNo; $i++) {
updateProgress($i, $TotalNo);
sleep(1);
}
function updateProgress($currentVal, $totalNo) {
$completionPrecentage = $currentVal / $totalNo * 100;
echo "event: progress\n";
echo 'data: {"progress": "' . $completionPrecentage . '"}';
echo "\n\n";
ob_flush();
flush();
}
if you want to send array you can refer to this
The EventSource API does not support POST method, however that does not mean that you cannot use SSE with POST. You just cannot use the EventSource API.
There are alternative implementations however. One example is sse.js which allows you to specify a payload, and also headers if you need. sse.js should be a drop-in replacement for EventSource, eg:
var source = new SSE("get_message.php");
source.onmessage=function(event)
{
document.getElementById("message-window").innerHTML+=event.data + "<br>";
};
In order to use a POST method, you just need to specify a payload, eg:
var source = new SSE("get_message.php", {payload: 'Hello World'});
And, since it is a fully compatible polyfill, you can probably do this:
EventSource = SSE;
var source = new EventSource("get_message.php", {payload: 'Hello World'});
source.onmessage=function(event)
{
document.getElementById("message-window").innerHTML+=event.data + "<br>";
};