This is my url
http://localhost:8888/App.php#?ID=1S
I needed the 1S as a variable for using it with a query.
If you want to parse URL as string:
$str = 'http://localhost:8888/App.php#?ID=1S';
$temp = explode( "?", $str );
$result = explode( "=", $temp['1'] );
echo $result['1'];
Demo
If you want to get it on server side:
Hash value is not sent to server side. So it impossible to get it on server side but you can use javascript to do some trick.
Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?
Using JavaScript/jQuery: (tags are not added though)
<script>
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
hash = hashes[0].split('=');
alert( hash['1'] );
// you can use jQuery.ajax() here to send this value to server side.
</script>
Get hash value & pass from javascript to php
echo parse_url('http://localhost:8888/App.php#?ID=1S', PHP_URL_FRAGMENT);
OR
echo parse_url($_SERVER['QUERY_STRING'], PHP_URL_FRAGMENT);
If you need to parse it further:
$x = parse_url($_SERVER['QUERY_STRING'], PHP_URL_FRAGMENT);
parse_str($x, $arr);
echo $arr['ID']
$url = "http://localhost:8888/App.php#?ID=1S&another=3";
$a = parse_url($url);
parse_str($a["fragment"],$arr);
print_r($arr);
outputs:
Array (
[?ID] => 1S
[another] => 3
);
if you can live accessing the first parameter with "?ID"
I guess that the only way to do this is by an AJAX request, here is a simplified example:
the index page
<!doctype html>
<html>
<head>
<title>Website</title>
<script type="text/javascript">
var url = document.location;
url = url.toString();
var getVal = url.split("#");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'App.php'+getVal[1], true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
the App.php page
<?php
if (isset($_GET['url'])) echo 'url : ' . $_GET['url'];
?>
Related
I have set up a basic api and I know its working because requests that come with postman pass normally ,what I am having trouble with is passing the JSON object through AJAX to the php file.
The AJAX part
function add_book(){
if(validate()){
var jsonData = {};
jsonData.Price = document.getElementsByName("Price")[0].value;
jsonData.Title = document.getElementsByName("Title")[0].value;
jsonData.Author = document.getElementsByName("Author")[0].value;
jsonData.Genre = document.getElementsByName("select_dropdown")[0].value;
alert(JSON.stringify(jsonData));
var request = new XMLHttpRequest();
var url = "/books.php";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
}
}
request.send(jsonData);
}
}
For example this is the alert I get from stringifying the object
{"Price":"23","Title":"asdas","Author":"dasda","Genre":"Science fiction"}I can basically copy/paste this string to postman and it works as intended.
Now to the php part
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if(!empty($json_obj->Price) && !empty($json_obj->Genre) && !empty($json_obj->Author) && !empty($json_obj->Title)){
The if always returns false ,while it should not ,again postman requests pass for true.
========================================================================
EDIT :
I managed to find the source of the problem . I made a function to check if the json is valid , turns out its not , there is no problem in the php part as it turns out . Here is the function in case someone needs it / wonders :
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
=========================================================================Edit 2:
The problem was on the request.send(jsonData); part . Fixed it with request.send(JSON.stringify(jsonData));
Thanks for your time !
This is the problem
$json str = file_get_contents('php://input');
The post parameters should be accessed by $_POST.
Instead try this
$json_str = $_REQUEST['jsonData']`;
and also do a var_dump for $json_str
Does this help?
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if(!empty($json_obj['Price']) && !empty($json_obj['Genre']) && !empty($json_obj['Author']) && !empty($json_obj['Title'])){
I think the problem is the file_get_contents(). Maybe you try to echo it.
And for the if you could write:
if (!(empty($json_obj->Price) && empty($json_obj->Genre) && empty($json_obj->Author) && empty($json_obj->Title)))
everyone!
I have some PHP code to sign some text and it works fine. I need to have equivalent of this code on actionscript 3. I need your help.
$privateKeyPath = "private.key";
$message = "hello";
$privateKey = file_get_contents($privateKeyPath);
openssl_sign($message, $signature, $privateKey);
echo base64_encode($signature);
In AS3 I using as3crypto library to make sign:
private function readPrivateKey():String {
var f:File = new File("/Users/ivan/Desktop/private.key");
var fs:FileStream = new FileStream();
fs.open(f,FileMode.READ);
var key:String = fs.readUTFBytes(fs.bytesAvailable);
fs.close();
return key;
}
private function getSign():void {
var message:String = "hello";
var privateKey:String = readPrivateKey();
var srcBA:ByteArray = new ByteArray();
var resultBA:ByteArray = new ByteArray();
var rsaKey:RSAKey;
var base64encoder:Base64Encoder = new Base64Encoder();
srcBA.writeUTFBytes(message);
rsaKey = PEM.readRSAPrivateKey(privateKey);
rsaKey.sign(srcBA, resultBA, srcBA.length);
b64encoder.encodeBytes(resultBA);
trace(b64encoder.toString());
}
I have same private key file. I expect that the output values are equals. But these values are different =(
What am I doing wrong?
UPDATE: I tried to verify my encoded base64 string using public key and verify method - everything is ok inside Actionscript.
Example:
var text:String = "hello";
var srcBA:ByteArray;
var desBA:ByteArray;
var rsaKey:RSAKey;
var encodedB64:String;
// ENCODING
srcBA = new ByteArray();
srcBA.writeUTFBytes(text);
desBA = new ByteArray();
rsaKey = PEM.readRSAPrivateKey( readPrivateKey() );
rsaKey.sign(srcBA, desBA, srcBA.length);
encodedB64 = Base64.encodeByteArray(desBA);
trace("Original: " + text);
trace("Encoded: " + encodedB64 );
// DECODING
var srcBA2:ByteArray = new ByteArray();
var desBA2:ByteArray = new ByteArray();
var rsaKey2:RSAKey = PEM.readRSAPublicKey( readPublicKey() );
srcBA2 = Base64.decodeToByteArray( encodedB64 );
rsaKey2.verify(srcBA2, desBA2, srcBA2.length);
trace("Decoded: " + desBA2.toString() );
My original text and decoded value are equals. So, I conclude that AS3 signing methods are different than PHP.
Is anyone have idea to make it equals?
Thanks.
Maybe it's late answer, but anyway...
AS3 works fine in your second code, PHP needs some tweaks, like this:
$privateKeyPath = "private.key";
$message = "hello";
$privateKey = openssl_pkey_get_private(file_get_contents($privateKeyPath));
openssl_private_encrypt($message, $signature, $privateKey);
echo base64_encode($signature);
I just checked with key genereted on this site:
http://www.selfsignedcertificate.com/ and everything works fine, I'm getting similar results in both PHP and AS3 versions.
Im having problem Posting a javascript variable to a php file. Please would someone tell me what's going on?
// Get Cookies
var getCookies = document.cookie;
cookiearray = getCookies.split(';');
SelectedIds = cookiearray[0];
//take key value pair
name = cookiearray[0].split('=')[0];
value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
var url = "page.php";
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("Comp").innerHTML = return_data;
}
}
hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";
PHP
$test = $_POST['value'];
print_r($test); // NULL
Thanks
Instead of
print_r($test);
use the echo
echo $test;
As $test is not an array is a string value. print_r is used to print the array. that's why is given the null value.
And your send function in ajax should be like this:
hr.send("value="+value);
In the send function, the parameter that passed must be a string like this:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
More tutorial is here.
I've been trying work out, for sometime, how to pass quite a long string I have formatted in javascript into php to save in a file and I think I now have the answer. At least it works for me.
The variable 'str' is passed into 'getGame' from another function after it has been formatted. I am using the 'POST' method as the string can get quite long.
The code is:-
function getGame(str){
//Sends data to the php process "save Game".
var test = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send("data="+ test);
}
This sends the "data" to "saveGame.php where it is saved to a file as in the following code and returns a messsage in the alert dropdown.
<?php
$outputString = $_POST["data"];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
fwrite($fp, $outputString);
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
This works for me and I hope it is useful to other newbies.
I am trying to fetch the RSS feed document from rss.news.yahoo.com/rss/topstories using Ajax, extract the values associated with the 'titles' tags and echo them to the screen. xmlget.htm implements Ajax via GET request.
xmlget.php uses the PHP function file_get_contents to load in the web page at the URL supplied to it in the GET variable $_GET['url'] and display the 'title' tags on the screen.
The error I get is this:
XML Parsing Error: junk after document element Location: moz-nullprincipal:{2f186a54-8730-4ead-9bf9-f82c8d56ad8f} Line Number 2, Column 1:
xmlget.htm
<html>
<head>
<title>Ajax Example</title>
</head>
<body>
<h1 style="text-align: center;">Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
nocache = "&nocache="+Math.random()*1000000
url = "rss.news.yahoo.com/rss/topstories"
request = new ajaxRequest()
request.open("GET","xmlget.php?url="+url+nocache,true)
out = "";
request.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(this.responseXML != ""){
titles = this.responseXML.getElementsByTagName('title')
for (j = 0 ; j < titles.length ; ++j)
out += titles[j].childNodes[0].nodeValue + '<br />'
document.getElementById('info').innerHTML = out
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(null)
function ajaxRequest(){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e1){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e2){
try{
request = new XMLHttpRequest()
} catch (e3){
request = false
}
}
}
return request
}
</script>
</body>
xmlget.php
<?php
if(isset($_GET['url'])){
function SanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripcslashes($var);
}
header('Content-Type: text/xml');
echo file_get_contents("http://www.".SanitizeString($_GET['url']));
}
?>
please add the following line in the head
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
Found the problem!
The file_get_contents function was unable to find the host because the url was invalid. rofl...
INCORRECT
echo file_get_contents("http://www.".SanitizeString($_GET['url']));
CORRECT
echo file_get_contents("http://".SanitizeString($_GET['url']));
Hi I'm wanting to post a variable from ajax js file to a php file. here is my attempt so far.
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
here is my php file
<?php
print_r($_POST);
$node = $_POST['deletenode'];
print "node to be deleted: $node";
?>
nothing comes up in my php file, what can be the issue. my ajax request is intact and working right too. thank you and here is my handle request.
function handleRequest(request) {
// we only care for now about when we get to readyState 4
// which means the request completed and we have the response back
if(request.readyState == 4){
//alert("response: " + request.responseText); // check to see what
// we got back just for testing
// now get response's TEXT and put into document (specify where)
// below we have an html element with the id as timeLoc
json= eval ("(" + request.responseText + ")");;
//alert ("json="+json); //tests what was recieved
//clicking the close button
closeButton.onclick = function() {
node.setData('alpha', 0, 'end');
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end');
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
});
}// end readystate=4
}//end handle request
Remember you have to send the data as key/value pairs - request.send("deletenode=" + encodeURIComponent(deletenode));
I'm not sure if this is a copy/paste error, but if that's your actual code you appear to be missing a few curly braces closes. And have a double;; at the end of your eval line. This is the code tidied up with the extra curly braces, does that work?
function handleRequest(request) {
if(request.readyState == 4){
json= eval ("(" + request.responseText + ")");
closeButton.onclick = function() {
node.setData('alpha', 0, 'end');
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end');
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
});
}
}
}