I'm building a sort of analytics platform for fun this weekend and here is my desired effect.
Client: abc.com
Server: test.com
User visits http://abc.com/#12345
Client sends Server via javascript id: 12345, and browser information. Server responds with a new id (ex: #23456), which is then pushed onto the current url (pushstate) http://abc.com/#23456
I was thinking of some kind of script that the Client includes from the Server that communicates with the servers backend, but is that not techincally XSS and unsecure? How do analytics people (Google, GetClicky, etc) do it?!
How can I achieve this like analytics sites do so the internet gods don't get mad at me for XSS, while still maintaing security, and ease of implementation. One included source.
I'd love anything you can do to point me in the right direction.
With jsonp. The idea is that the source of a script tag is the code you want to execute:
<script type="text/javascript" src="http://yoursite.com?id=12345&this=that" />
edit: Yes, you create the script dynamically similar to an ajax response:
function getResponse(id){
var scrpt = document.createElement("script");
scrpt.type="text/javascript";
scrpt.src = "http://yoursite.com?id="+id;
document.body.appendChild(scrpt);
}
Inside your php page:
<?PHP
if(!isset($_GET['id']))die();
$id = $_GET['id'];
echo "alert('$id');";
?>
Something of the sort, anyway.
edit: completely forgot, but the point of jsonp is that you pass in a callback function. See here for some php documentation: http://php.net/manual/en/function.json-encode.php
Related
I have a webpage that needs to check to see if an app exists using a deep link, but it doesn't seem to work like it should. I have tried the following things.
Using a redirect in PHP (Doesn't work)
header('Location: exampleapp://param=test');
Using a redirect using JavaScript (Doesn't work)
var appurl = 'exampleapp://param=test';
var appstore = 'https://itunes.apple.com/us/app/...';
var timeout;
function preventPopup() {
clearTimeout(timeout);
timeout = null;
window.removeEventListener('pagehide', preventPopup);
}
function startApp() {
window.location = appurl;
timeout = setTimeout(function(){
if(confirm('You do not seem to have the App installed, do you want to go download it now?')){
document.location = appstore;
}
}, 100);
window.addEventListener('pagehide', preventPopup);
}
// app start is then called in the onload
Same as above but replace the the line window.location = appurl; with document.getElementById('deeplink').click(); and adding a link in the html's webpage. (Works) <a id="deeplink" href="exampleapp://param=test">Deep Link</a>
Is there a reason why you can't redirect using a header in PHP?
The PHP version doesn't work, because of the way HTTP works. The HTTP protocol doesn't specify that it should work to redirect to a different protocol from within the "Location:" header. There is nothing specific to PHP here, it's a HTTP issue.
The Javascript version doesn't work because you wanted to set the windows location. And the window cannot show the contents of "exampleapp://..." . You want the link to open like when the user clicks on it. Instead of using window.location you may use document.location.href. That should work.
Another problem:
in your code you write exampleapp:// in 1) and 2). And in 3) you write testapp:// - make sure you use the same URL in all three cases, so that you can be sure that the URL can work eventually..
The answer is to use Apples implementation called 'Smart Banners'
<meta name="apple-itunes-app" content="app-id=myAppStoreID, affiliate-data=myAffiliateData, app-argument=myURL">
You can include three comma-separated parameters in the content
attribute:
app-id: (Required.) Your app's unique identifier. To find your app ID
from the iTunes Link Maker, type the name of your app in the Search
field, and select the appropriate country and media type. In the
results, find your app and select iPhone App Link in the column on the
right. Your app ID is the nine-digit number in between id and ?mt.
affiliate-data: (Optional.) Your iTunes affiliate string, if you are
an iTunes affiliate. If you are not, find out more about becoming an
iTunes affiliate at http://www.apple.com/itunes/affiliates/.
app-argument: (Optional.) A URL that provides context to your native
app. If you include this, and the user has your app installed, she can
jump from your website to the corresponding position in your iOS app.
Typically, it is beneficial to retain navigational context because: If
the user is deep within the navigational hierarchy of your website,
you can pass the document’s entire URL, and then parse it in your app
to reroute her to the correct location in your app. If the user
performs a search on your website, you can pass the query string so
that she can seamlessly continue the search in your app without having
to retype her query. If the user is in the midst of creating content,
you can pass the session ID to download the web session state in your
app so she can nondestructively resume her work. You can generate the
app-argument of each page dynamically with a server-side script. You
can format it however you'd like, as long as it is a valid URL.
https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/PromotingAppswithAppBanners/PromotingAppswithAppBanners.html
This is for an online examination: I should trap the user to use the back and forward button from browser and also by refreshing the page when the user is already taking the exam.
Thanks in advance for your answers and responses.
I don't think the solution should rely on a client-side code because it can be modified by the client. I think it could be okay for some kind of controlled environment where you can prevent the client from entering in developer mode.
In case the environment can be controlled, restricting keyboard shortcut, right click and providing a browser in full-screen mode should be enough to ensure the client complete the task properly.
Otherwise, a system relying on key/value token between the client a server should do the job. Some secure online service rely on such system and it works well if you accept to broke the "back" and "forward" functionality as well as the refresh page. You surely could emulate a callback when the client call such broken functionality.
There is some circumstance in which it's useful to only on JavaScript to ensure page display. Such as generating random identifier and random so the page never the same, etc.
In any case (IMO), exclusively relying on JavaScript for security purpose is not (and never) a good idea.
Edit:
Here is a Proof-Of-Concept:
The server generate a uniqid and the client store that value using html5 local storage functionality. Using the local storage as a key/value registry we can store the page stage and compare each reload with the stored key compared with the server new generated key.
It's pretty straight-forward and what used as the server generated token can be randomize a lot, preventing anyone from guessing it.
A long enough server generated token could even provide a good single-use encryption key for the client local storage registry.
Code:
<?php
$stamp = uniqid();
?>
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://raw.github.com/andris9/jStorage/master/jstorage.js"></script>
<style>
body{background-color:blue;}
p{margin-left:auto;margin-right:auto;width:800px;background-color:gray;font-weight:bolder;padding:1em;}
</style>
<script>
// display nice messages
var err_reloaded_page = "page reloaded";
var keeper = '<?php echo $stamp; ?>';
var current = $.jStorage.get('state');
// first initialization, Exception
if(current == null){
$.jStorage.set('state',keeper);
current = $.jStorage.get('state');
}
if(current != keeper){
alert(err_reloaded_page);
}
</script>
</head>
<body>
<p>
Proof of concept<br/>
Can detect page reload by comparing a stamp created server-side, stored on the local storage and compared on each page reload.
</p>
</body>
</html>
I want to create a simple tracking script to give to my clients. Something similar with GA but very basic.
The requirements are
give the clients a single and simple js script like google Analytics does
make most of the logic inside the js file loaded by 3th party sites from the main site
collect in PHP the information and store it
What I can't figure yet is what are the ways to do this?
Google from what I see is loading a gif file, stores the information and parses the logs.
If I do something similar sending the data to a php file Ajax cross site policy will stop me, from what I remember.
So what is a clean way to do this ? ( I don't need code just the logic behind it )
Method a - web bug:
Give the user this:
<img src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid" width="1" height="1" />
have the php return header("content-type:image/gif"); and serve them a gif file for their effort.
Method b - script
Create a php file that can parse parameters and have it return content-type:text/javascript
Have them load it like this:
<script type="text/javascript" src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid"></script>
If you want to you can do additional stuff like
<script type="text/javascript">
var associateId = "12345";
var trackingPage="homepage";
</script>
<script type="text/javascript" src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid"></script>
then in the php have code like this (watch the nested quotes)
$str = 'var url = "http://www.yourserver.com/moretracking.php?associateid="+associateId+';
$str .= '"&page="+trackingPage+"&ref="+escape(document.referrer);\n';
$str .= 'document.write(\'<img src="\'+url+\'"/>\');';
echo $str;
You may read this (found googling) about cross domain ajax and its possible solutions... http://snook.ca/archives/javascript/cross_domain_aj/
Well, i use some php code that is included in my script that logs Ip Addresses and as much information i can get from a server-side perspective. It saves it in a MySql Database. I also use a Ajax script to post data to a php script, the data in this case is Screen Heigth and thing you only can get client-side.
I want to connect to public facebook page or group and list all entries from the wall on a personal website. I will use PHP on my server so that would be the best solution for me. Or javascript.
Could anyone explain or perhaps give a working code on how to do this? Or just all steps nessesary for making this?
If its possible to handle information about person, date, description ... for each post, that would be great! So my layout could be customized.
Thanks for helping me out here!
You need to run FQL on stream table and provide id of a page or group you are interested in as source_id (fb docs have some explanation and examples). Once you get stream data you can dig deeper and get user who left this post or any other data you need again through FQL.
There are many ways of running FQL - it could be done in JS API, PHP API, or through old REST API.
use the facebook graph api urls that they provide
python code using simplejson parser
keyword="old spice"
searchurl='http://graph.facebook.com/search?q='+keyword
resp=urllib2.urlopen(searchurl)
pageData=resp.read()
json = simplejson.loads(pageData)
posts=json['data']
for p in posts:
postid=p['id']
username=p['from']['name']
posterimg=p['icon']
comment=p['message']
In JavaScript (jQuery).
You can use my spare access_token for viewing public groups or pages ;)
To get your own access token the facebook graph explorer can generate one for you (as well as test queries).
In Javascript we make a request to facebook graph, which returns a JSON object. The response looks like this.
The code below iterates though each entry and prints out the message, if you look at the link above it gives you the naming convention for the other data fields.
for example:
data.data[0].created_time;
data.data[0].from.name;
etc..
Hope that Helps!
<!DOCTYPE html>
<head>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
</head>
<body>
<ul id = 'list'>
<script>
var graphQuery = 'https://graph.facebook.com/2228101777/feed';
var authToken = '145634995501895|477bb3c939123a5845afe90d.1-100002565213903|F1VA26jsYL7yBeq2iU6SZX_XXrs'
var url = graphQuery +'?access_token='+ authToken +'&callback=?';
$.getJSON(url,function(data){
for( i=0; i < data.data.length; i++){
$("#list").append('<li>'+ data.data[i].message +'</li>');
// add some more here if needed
}
});
</script>
</ul>
</body>
</html>
What you are talking about, as far as I can tell, is Web Scraping. What you would do is get the URL of the group, use the file_get_contents($url) command in PHP to get the file, and then analyze it in PHP.
I'd suggest brushing up on your regular expressions for this, as it'll be important to review the HTML that Facebook uses for the wall posts. You'll be able to get the information that you're looking for from the HTML.
I would post some example code, but that's on another computer, far far away. Still, should be a good start.
Edit: Adding in some example code:
$URL = "http://facebook.com/group=5343242" (or whatever the URL structure is for the facebook group)
$groupPage = file_get_contents($URL)
Here's the link to the PHP pages on Regular Expressions:
http://www.php.net/manual/en/book.pcre.php
I need to fire a php class from a javascript function.
code:
<input type="button" name="Submit" value="Submit" class="opinionbox"
onclick="verifyControl('<?=$control_no?>')"/>
function verifyControl(rNo) {
Cont_no=document.getElementById("ContNo").value;
if(rNo==Cont_no) {
frames['frame1'].print();
showPage('payment');
}
else if(rNo!=Cont_no) {
alert("invalid control no");
}
}
i need to run the code
$data = $obj_com -> getSelectedData('tbl',
'control_no', $contno);
$control_no = $contno;
$obj_com -> recordPay('tbl',$contno);
inside the verifyControl() how can I do this?
You cannot "call" a PHP class from Javascript because Javascript is run on the client side (ie, the browser) while PHP is run on the server. What you can do, however, is call a PHP script asynchronously, get its output, and do fun stuff with javascript. This is known as AJAX. If you're going to go down this road, you are highly advised to use a library like jQuery and learn from there. Here are a few questions to get you started (check out the answers):
How to dynamically call a php function in javascript
Javascript and PHP functions
To call PHP code from Javascript, given that PHP is executing on the server and Javascript is executing on the client, you will need to set up some sort of interface at the server that can be accessed remotely.
You may also want to be aware of the security implications of doing so. In particular, if you want to ensure that only your users will be calling your server in this way - that is, if a malicious user calling this code could do damage, you will need some sort of authentication.
You will also need to decide on a protocol for communicating between the client and server.
Protocols such as SOAP and XML-RPC define everything you need to remotely call procedures on the server. Or you can roll your own, just by calling a certain URL and receiving a certain result, in a certain format (JSON can help) from the server.
you can use Brent Ashley jsrsClient.js or $.ajax of jQuery Javascript lib.