Track users with PHP and JavaScript - php

Have I missed any obvious things that you can log to keep track on your visitors (using PHP and JavaScript)?
Can I get computer name?
Can I get the country?
Can I get the city?
Postal code?
Any other information that can be collected from certain browsers?
PHP DOCUMENT :
<script>
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$hostaddress = gethostbyaddr($ip);?>
<?php echo "document.write('The IP-adress: ' + " . "'" . $ip . "'" . " + '<br>');";?>
<?php echo "document.write('The host address: ' + " . "'" . $hostaddress . "'" . " + '<br>');";?>
document.write('The date: ' + new Date() + '<br>');
document.write('Get the entire URL of the current page: ' + location.href + '<br>');
document.write('This document was last modified on:' + document.lastModified + '<br>'); // good to know wich version of the page they have
if (document.referrer != ''){
document.write('The referrer of this document is: ' + document.referrer + '<br>')
}
else{
document.write('The is no referrer.<br>')
}
document.write('Number of URLs in history list: ' + history.length + '<br>')
// I know it doesn't allways return the right browser info, but it gives a good clue.
document.write("Browser name: " + navigator.appName + '<br>');
document.write("Browser version info: " + navigator.appVersion + '<br>');
document.write("Platform: " + navigator.platform + '<br>');
document.write("User-agent header sent: " + navigator.userAgent + '<br>');
document.write("Language of user: " + navigator.userLanguage);
document.write("Total Height: " + screen.height + '<br>');
document.write("Total Width: " + screen.width + '<br>');
document.write("Cookie: " + document.cookie + '<br>');
</script>

There are a lot of geolocation databases available. If you wish to go free there are some free databases too with less frequent updates than their paid counterparts, e.g. MaxMind GeoLite.
For more Google for IP geolocation.

Related

AJAX call from inside a Widget in Yii2?

I would like to create a Widget for my Yii2 project that will based on a few parameters given in the View create an AJAX call that updates a portion of my View.
Basically I have a Postcode field that when updated will look up the corresponding town in a different PHP file. I created something that works, but I was wondering if this is the right (or only?) way to do what I'm looking for. I don't want to have to rewrite the AJAX call as I want to be able to reuse this functionality on several forms and thus fields in my project.
I call the Widget in my View like this:
<?= SearchWidget::Widget(['id' => 'customerform-postalcode',
'dataTarget' => 'cities',
'targetId' => 'customerform-city',
'targetType' => 'dropdown']);?>
and in the Widget I basically have only a run() function which echoes the AJAX call to the page.
public function run()
{
$jScript =
'<script>'
. '$("#' . $this->id . '").change(function(){'
.'$.ajax({'
. 'url: "../scripts/search.php",'
. 'data: {'
. 'needle: $("#' . $this->id . '").val(),'
. 'haystack: "' . $this->dataTarget . '"'
. '},'
. 'type: "POST"'
. '}).done(function(data){'
.'var targetType = "' . $this->targetType . '";'
.'if (targetType=="dropdown") {'
. '$("#' . $this->targetId . '").empty();'
. 'var obj = jQuery.parseJSON(data);'
. '$.each(obj, function(key, value) {'
. '$("#' . $this->targetId . '").append("<option>" + value + "</option>");'
. '});'
. '} else {'
. 'var obj = jQuery.parseJSON(data);'
. '$("#' . $this->targetId . '").val(obj);'
. '}'
. '});'
. '})'
.'</script>';
echo $jScript;
}
First off, I've only just started working with Yii and frameworks so I'm really unsure if this is the correct way to go about it. My first instinct says this is too messy and there should be a better way to do it. Any help is appreciated.
Personally I don't like to write JS code in my PHP files. So I would try to get the JS in a separate .js file.
I would change my SearchWidget to echo an input field with some additional attributes that will provide the JavaScript with the right variables. So my postcode input field would look something like:
<input type="text" name="postcode" id="postcode" class="search-field" data-target="cities" data-targetid="customerform-city" data-targettype="dropdown" />
Then you can rewrite your JS to something like below (untested).
$('.search-field').change(function() {
var id = $(this).attr('id');
var data_target = $(this).data('target');
var target_id = $(this).data('targetid');
var target_type = $(this).data('targettype');
$.ajax({
url: "../scripts/search.php",
data: {
needle: $("#" + id).val(),
haystack: data_target
},
type: "POST"
}).done(function(data) {
if (target_type == "dropdown") {
$("#" + target_id).empty();
var obj = $.parseJSON(data);
$.each(obj, function(key, value) {
$("#" + target_id).append("<option>" + value + "</option>");
});
} else {
var obj = $.parseJSON(data);
$("#" + target_id).val(obj);
}
});
});
Then put this JS file somewhere and register it in the init part of your widget.

Create line break in WhatsApp message

I have been working on WhatsApp sharing message using:
whatsapp-button.js
$_u.="Product Name:".$_productName."\n";
$_u.="Sku:".$_productSku."\n";
Share
How to add a line break:
I have tried \n, \r\n, PHP_EOL, and %0D%0A, but it just displays as text.
If you want to send an only text containing newline
use this %0a
link =`whatsapp://send?text=%0a‎Hello%0aWorld`;
If you want to send some url link with text containing newline
var encodedURL = encodeURIComponent(some_url);
link =`whatsapp://send?text=${encodedURL}%0a‎Hello%0aWorld`;
Now embedded this link in anchor tag
<a href=link> Click here! </a>
To create a line break in WhatsApp you can use this command. It's working fine and I am using it:
use `%0a`
For example:
smsContain = "*Greetings from " + cname + " ,%0a %0aM/s. " + txtName.Text + " %0a %0aYour Bill for Advertisement is generated ; %0a %0aBill Date :- " + DateTime.ParseExact(dateTimePicker1.Text, "dd/MM/yyyy", null).ToString("dd/MM/yyyy") + " %0a %0aBill no :- " + lblBillNo.Text + " %0a %0aBilling Amount of Rs. " + lblNet_Amt.Text + " %0a %0aAdvertisement Published in " + news + " in " + Edi + " edition,%0a %0aReleased Date : " + DateTime.ParseExact(DateTime.Parse(dt).ToShortDateString(), "dd/MM/yyyy", null).ToString("dd/MM/yyyy") + ".%0a %0aPlease find the Bill attached below, and request you to please release the payment ASAP. %0a %0a %0aAny descripancy in regards to this Bill to reported to us immediately.%0a %0a %0aAlways at your Service....* ";
smsContain = smsContain.Replace("&", "+%26+");
https://wa.me/+99123456789?text=Line%0aBreak
The %0a represents the line break
I got one working solution:
HTML:
$_u.="Product Name:".$_productName."\n";
$_u.="Sku:".$_productSku."\n";
<a data-text="<?php echo $_u; ?>" data-link="" class="whatsapp">Share</a>
JS:
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
$(document).on("click", '.whatsapp', function() {
if( isMobile.any() ) {
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
var whatsapp_url = "whatsapp://send?text=" + message;
window.location.href = whatsapp_url;
} else {
alert("Please share this in mobile device");
}
});
There is a solution in here which basically is using:
whatsappMessage = window.encodeURIComponent(whatsappMessage)
Try to use 
. It is a special HTML code.
For example:
Hello!
How are you today?
will get a result like this:
Hello!
How are you today?

open link on new window with top bar from my site

How my brothers cleared of any possible link to my site once pressed opens the page again and be the top bar of my site such as the following
http://www.example.com/index.html
[Edit]
How to render a bar at the top of a website that shows content from some other site in its body.
i have this ode to get rss from other site
gfeedfetcher.prototype._displayresult=function(feeds){
var rssoutput=(this.itemcontainer=="<li>")? "<ul>\n" : ""
gfeedfetcher._sortarray(feeds, this.sortstring)
for (var i=0; i<feeds.length; i++){
var itemtitle="" + feeds[i].title + ""
var itemlabel=/label/i.test(this.showoptions)? '<span class="labelfield">['+this.feeds[i].ddlabel+']</span>' : " "
var itemdate=gfeedfetcher._formatdate(feeds[i].publishedDate, this.showoptions)
var itemdescription=/description/i.test(this.showoptions)? "<br />"+feeds[i].content : /snippet/i.test(this.showoptions)? "<br />"+feeds[i].contentSnippet : ""
rssoutput+=this.itemcontainer + itemtitle + " " + itemlabel + " " + itemdate + "\n" + itemdescription + this.itemcontainer.replace("<", "</") + "\n\n"
}
rssoutput+=(this.itemcontainer=="<li>")? "</ul>" : ""
this.feedcontainer.innerHTML=rssoutput
}
i need when click link open in other windows with i frame
The site is just the top header with an
<iframe></iframe>
within
Check out more info at w3schools
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe

Stripping HTML from jQuery load() result

This is a followup to the solution for this question.
I am using jQuery's load() function to pull a headline within a div tag from one page to another within my site. This works wonderfully.
The problem is, load() also pulls the div tag itself, which I do not want, as it then gets formatted via CSS like the source page.
Here is the PHP:
function get_team_articles($team_id, $feat=0) {
.
.
.
while ($row = mysql_fetch_assoc($r)) {
$page = explode('_', $row['page_id']);
(is_numeric($page[1]))
? $pre = 'wk_'
: $pre = '';
$arr[] = $page[0] . " | " . $pre . $page[1] . ": " . "
<a linked_div='news_header'
linked_path='../news/" . $page[0] . "/" . $pre . $page[1] . "/" . $page[1] . "_" . $page[2] . ".html'
href='index.php?view=news&yr=" . $page[0] . "&wk=" . $page[1] . "&pg=" . $page[2] . "'></a>";
}
$articles = implode('<br/>', $arr);
return $articles;
}
Notice the linked_div and linked_path attributes within the anchor tag, which are used in my jQuery:
function set_team_headlines(){
$('#section-articles > a').each(function() {
var a = $(this);
a.load(a.attr('linked_path') + ' #' + a.attr('linked_div'));
});
}
Obviously I cannot strip the HTML tags within the anchor tags in PHP, because the server doesn't have the text within the anchor tags upon loading; so I assume I need to strip the HTML in jQuery after the load() call...and that is what I cannot figure out how to do. :)
The result I want is:
My headline
The result I'm getting is:
<div id="news_header">My headline</div>
Hopefully this makes sense. I think I provided more detail than I needed to. Thanks!
Navigate down one more level in your .load selector
a.load(a.attr('linked_path') + ' #news_header');
If your news_header id isn't unique, it isn't valid to select by that id (ID's must be unique!)
To get around that issue, use this:
a.load(a.attr('linked_path') + ' #' + a.attr('linked_div') + ' div');
Edit:
.load actually includes the targeted element when appending html instead of appending the target element's children. I would move to using $.get().
$.get(a.attr('linked_path')).done(function(html) {
a.text($(html).filter("#news_header").text());
});

timing of JSON AJAX Response in Jquery

I think this is more down to timing than code, so really I am looking for best practice advice on how best to get a JSON response.
<script type="text/javascript">
$(window).load(function() {
$('#messages').append('<img src="images/loading.gif" alt="Currently Loading" id="loading" />');
var ideaid = <?php echo $_GET['ideaid']; ?>;
$.ajax({
url: 'sql/ajaxsql.php',
type: 'POST',
data: 'switch=commentList&ideaid=' + ideaid + '&filter=sortdate',
dataType: 'json',
success: function(result) {
var len = result.length;
var html;
console.log('length= ' + len);
$('#response').remove();
console.log(result);
for(var i = 0; i < len; i++) {
var pic = '<img src="https://graph.facebook.com/' + result[i].user_id + '/picture&type=small" align="middle" />';
var authname;
FB.api('/' + result[i].user_id + '?fields=name', function(AuthName) {
console.log(AuthName);
alert(AuthName.name);
authname = AuthName.name;
});
html = '<p>' + result[i].comment + '<br><hr>Date Added: ' + result[i].date + ' by ' + pic + ' ' + authname + '<br><hr><hr></p>';
$('#comms').append(html);
}
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
</script>
With this code, it fires off to get comments regarding a certain idea (idea_id). The comments only holds the Users ID (facebook). When all the data is back, the success then sorts the data ready to print to the screen in some order.
As part of the success, I have the date, time, FB image and name as part of the Author Info under each comment.
Date and Time, works. Image using the graph works, but the name is a bit late of the window loading, and so misses it's call, so comes back as undefined and then the Alert pops up with the name. I understand ajax is meant to do this.
Whats the best way to get round this.
Thank you in advance.
Andrew
EDIT
I have been unable to make this work, even with the suggestions below.
EDIT AGAIN Just seen bf new updated version as below. would also have worked. But I have spent a day on this one function and dare not to play.
As soon as the FB.api comes into play, I could not get the values from out side it. So I took a different approach.
Rather than ajax, I used the query from the PHP side that gets the data, including the uid and then json queried that, and bolted it onto the (mysql_fetch_array) array as follows:
$gc_result = mysql_query($gc_query);
while ($result = mysql_fetch_array($gc_result)) {
$jsonURL = "https://graph.facebook.com/" . $result['user_id'] . "/";
$json = json_decode(file_get_contents($jsonURL), true);
$result["name"] = $json['name'];
$data[] = $result;
}
echo json_encode($data);
Now I have that, I can then do the following and call it within the jQuery:
for(var i = 0; i < len; i++) {
var pic = '<img src="https://graph.facebook.com/' + result[i].user_id + '/picture?type=small" align="middle" />';
html = '<p>' + result[i].comment + '<br><hr>Date Added: ' + result[i].date + ' by ' + pic + ' ' + **result[i]['name']** + '<br><hr><hr></p>';
$('#comms').append(html);
}
This all works great, and I am a complete novice to programming jquery and using Facebook API and JSON, but even I sit back and am pretty impressed with this solution. Before I get carried away, are there any potential flaws in this, performance or security wise ???
Thanks again in Advance.
Andrew
The call to FB.api is probably asynchronous (another ajax request), so you have to move the code after it to inside the FB.api callback:
FB.api('/' + result[i].user_id + '?fields=name', function(AuthName) {
console.log(AuthName);
alert(AuthName.name);
authname = AuthName.name;
html = '<p>' + result[i].comment + '<br><hr>Date Added: ' + result[i].date + ' by ' + pic + ' ' + authname + '<br><hr><hr></p>';
$('#comms').append(html);
});
You also have a variable scope problem because of the for loop. One of the ways to fix this is to use a separate function to create the callback. Add this right after your $(window).load block, before </script>:
function createFbApiCallback(jsonResult) {
return function(AuthName) {
var authname = AuthName.name;
var pic = '<img src="https://graph.facebook.com/' + jsonResult.user_id + '/picture&type=small" align="middle" />';
var html = '<p>' + jsonResult.comment + '<br><hr>Date Added: ' + jsonResult.date + ' by ' + pic + ' ' + authname + '<br><hr><hr></p>';
$('#comms').append(html);
}
}
Then change your loop to this:
for(var i = 0; i < len; i++) {
FB.api('/' + result[i].user_id + '?fields=name', createFbApiCallback(result[i]));
}
If you have to execute code that relies on a callback function inside another callback function, execute your code inside the most inner callback function. In your case, move all that is out of the FB API callback to be inside it, so all your DOM manipulation is done only when both the AJAX response and the FB.api response has returned.

Categories