passing html geolocation data to php - php

I am new to html and php(2hours).
I want to save the visitor geolocation data and ip address in a log file.
here is my code, i cannot pass the location data into php.
how can I do it?
I have no idea of what am i doning now.
<!DOCTYPE html>
<html>
<body>
<p id="demo">Dont click it</p>
<button onclick="getLocation()">Try It Anyway</button>
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(showPosition);
{enableHighAccuracy:true}
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
localStorage.loc= "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
x.innerHTML=localStorage.getItem("loc");
locOfSluts=localStorage.getItem("loc");
}
</script>
<?php
$$locofsluts = $_POST["locOfSluts"];
$contfile = fopen("NumOfSluts.log", "r");
$cont = fread($contfile,filesize("NumOfSluts.log"));
fclose($contfile );
$cont = $cont+1;
$contfile = fopen("NumOfSluts.log", "w");
fwrite($contfile , $cont);
fclose($contfile );
$log = fopen("log.log", "a") or die("Unable to open file!");
$ipOfSluts = $_SERVER["REMOTE_ADDR"]."\n";
fwrite($log, date("Y-m-d-h:i:s")."\n");
fwrite($log, $ipOfSluts);
fwrite($log, $locofsluts);
fclose($log);
?>
</body>
</html>

Since PHP is executed on the server and JavaScript is executed on the client side in your browser you cannot simply pass information from JavaScript to PHP.
The only way to archive that is to create an extra PHP script that saves the information given by some parameters and use AJAX to open an new request to this PHP file.
The problem more in detail:
You declare $loc in JavaScript and use it in PHP. It's generally not possible to use variables across multiple programming languages!!!
In this case please make sure you know the differences between PHP and JavaScript:
If you make a request to a file at the web server the PHP script starts running and generates the HTML response (so everything between is evaluated) and the output of all this will be sent to the client. Usually the connection to the server is closed afterwards.
So the PHP part of your script already ran at the server and is NOT served to the client (who wouldn't be able to run your PHP anyway since it cannot write on files at the server for example). Now your browser starts parsing the HTML result and builds the webpage for you. When the document is ready the web engine of your browser executes JavaScript and it collects the GEO information.
So when having this in mind you will see that your code cannot work for many different reasons.
The solution in detail:
You need to make an asynchronous solution for this. So you should have a .php file on your server that has no specific output. The only thing it does is saving the information given via GET parameters to your log file.
Now on your website you need a JavaScript code that fetches the GEO location data and when it succeed it should open an new connection to your .php file and pass the information you want to save as parameters to the .php script. With jQuery this would look like this:
$.ajax({
url: 'save.php?lang='+lang+'&lat='+lat,
}).done(function() {
alert('Information saved');
})

Related

How to read a log file live that is constantly updating in server to web textbox

the log file will be in notepad format the values will be like this 11.23445646,56.3456578954
10.23445646,26.3456578954
16.23445646,-46.3456578954
I'm planning to get the data from server to website textbox, of first value which I marked as italic the values will change after few seconds the updated value will come first. I tried some PHP example but not getting it in the below text box the values I need to get.. for example: x=11.23445646, y=56.3456578954, pls guide me
Longtitude <input id="x" type="number" value = "" onkeyup="updateMarker('x')">
Latitude <input id="y" type="number"value = "" onkeyup="updateMarker('y')">
Updated Answer
You can do this now using Web Socketing. Here is a guide and hello-wrold example of a php websocket server:
http://socketo.me/docs/hello-world
And to see how to implement client side javascript of websocket, you can see the bottom of the link put above, which shows you this snippet:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
Old
PHP does not support live connections generally in the way you expect, you have to simulate it via repeated AJAX request. How? For instance on each second, or each two seconds.
You first have to write an ajax in your HTML with jQuery library:
Sending a request each second:
var url = "url_to_you_file";
var textarea_id = "#textarea";
setInterval(function(){
$.ajax({
url : "site.com/get-file-logs.php",
type : "POST",
success : function(data){
$(".textarea").html(data);
}
});
}, 1000);
Then in PHP file you would write this:
$file_path = "path_to_your_file";
$file_content = file_get_contents($file_path);
echo $file_content;
The above example gets the file content and sends it back to your browser. You may want to process it in a certain way; that then changes your approach a little bit. Because you must always stick to JSON format when you try to get data back from server to be manipulated by Javascript.
PHP doesn't really do "live" page updates since normally when a web browser (or other user agent) loads a web page once it's done downloading the page then PHP is already finished and can't touch what's already on the client.
Best way to do this would probably be to use a JavaScript AJAX call to periodically load the updated values from a PHP script and then update the values on the page.
Or if it's a really small page (in byte size) you could just make it automatically reload the whole page (with updated values) if that is not a problem for you.
In any case every time the PHP script is called it would just open the file in read mode and only read the latest values from the beginning of the file and return those. See fread(). Or maybe file_get_contents() or file() would be easier and just read the first line.
AJAX is a bit larger topic and I don't currently have the time to explain the whole process of updating the page using JavaScript. Google is your friend.

Post web image to a server

I've read many posts that due to security risks you cannot upload to your server with an image from your folder as javascript isnt allowed such access. However, I have a situation where i have an svg image on a web site that I convert to a png whilst on the website. But, I wish to send the converted image to my server.
Will I encounter the same problems as if I were uploading from my documents?
I tried to make an example of jsfiddle but it seems it doesnt accept document.write very well, so here's sort of a work-around:
DEMO: jsfiddle
Ideally we would have a button defined as so:
<button id="image" onClick="image()">Convert & Send</button>
Then have the code that does the conversion within a function along with the ajax
function image() {
//conversion code & ajax
}
So in conclusion I would just like to know if this is possible if not, i would be grateful if you could show an alternative way, whether it may include a combination of php.
thanks in advance
It seems as though the fiddle isnt loading heres the snippet: of the conversion
function image () {
var svg = document.getElementById("svg-container").innerHTML.trim();
var canvas = document.getElementById('svg-canvas');
canvg(canvas, svg, { renderCallback: function () {
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
}
});
I'm not sure about what your question is, but indeed, you can use a combination of Ajax + PHP to upload your image.
The client would POST an encoded image (e.g. encoded in Base64) using ajax (using jQuery.post, for example), while the PHP would receive the image and store it (after decoding it) in your server.
For an example of the process, check this question, where a specific case of a canvas is discussed. I think your SVG conversion could work in a similar way.
PS: For some reason, I couldn't load your Fiddle.
EDIT:
So both Ajax & PHP are written on the front end to send the image to
my server/database (ruby on rails). Is that correct?
No. Only Javascript (with Ajax) is used in the client. PHP would be the server part of the process, so in your case it would not be used as you are already using Ruby on Rails. In other words:
The client (browser) uses Javascript (maybe JQuery) to POST the image data (in your snippet, img) to the server (more info here).
The server (a PHP, ASPX or Ruby script [among others]) gets the POSTed data and saves the picture on disk (some info here).
If you can use PHP (in the server) for the specific process of saving the image, you can use the question I linked before as a guide.
Yes Of Course Their are ways:
I know 2:
1-(This One I know it works on chrome and Firefox but don't know IE):
First Get The Base 64 Data Of An Image In Canvas:
<canvas id="Canv" ....(Other Attributes)>
Your Browser does not support the canvas element :(
</canvas>
<button type="button" OnClick="Image()">Transform and Save</button>
<script type="text/javascript>
var can =document.getElementById('Can');
var ctx = can.getContext("2d");
//do something with ctx
function image(){
//You Should check the real format using img.src
var data = can.toDataURL("image/png");
var array = data.split(".");
var Base64Data = array[1];
//Now step 2 :Sent it to PHP
//Check for Browser compatibly
var ajx = new XmlHttpRequest()
ajx.onreadystatechange=function()
{
if (ajx.readyState==4 && ajx.status==200)
{
if(ajx.ResponseText == "Err"){//if the paged returned error
alert("An error Has Occurred");
return;
}//if not
alert("Saved Succesufuly");
}
}
ajx.open("GET","Save.php?q=" + Base64Data , true);
}
</script>
Step3: Interprete it With PHP
<?PHP
if(isset($_GET['q] And !Empty($_GET['q'])){
try {
$Data = $_GET['q'];
$hndl = fopen("Saved/Pic1.jpg" , "w");
fwrite($hndl , $Data);
fclose($hndl);
}catch(Exception $err){
echo "Err";
}
}else {
echo "Err";
}
?>
Yeap And That it.:D
You Could also loop throught each file in that directory and create a load button that get the Base64 Value And the first stuffs and out it into canvas using pucontent method of canvas element object

I seem to be unable to get AJAX/JS to reload a PHP script and update various page elements

So here is the situation. I'm building a page to host a radio stream hosted on an Icecast server. I got the player working great and cobbled together a PHP script to extract and parse out various data points from the server. Information such as current track, number of listeners, etc.
Here's the problem. It loads fine when the page is first opened, but I can't figure out a way to get these variables to be updated every 5-10 seconds or so and update the page with the new information WITHOUT reloading the page completely (it is a radio station after all, and having to re-buffer the station ever 10 seconds just isn't feasible.
Here's what I have so far, after various attempts have been removed from the code. Any ideas? I've seen it done for one or two variables, but I have almost a Dozen here...
<div id="current_song"></div>
<script language="javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script language="javascript">
{
$.ajax({
type: 'POST',
url: 'script.php',
data: 'getLatestInfo',
dataType: 'json',
cache: false,
success : function(dp){
$.getJSON('script.php', function(dp) {
//'data' will be the json that is returned from the php file
$.("#current_song").html("dp[9]");
});
getlatest();
};
});
}
</script>
and here is the PHP parser
<?php
Function getLatestInfo() {
$SERVER = 'http://chillstep.info:1984';
$STATS_FILE = '/status.xsl?mount=/test.mp3';
$LASTFM_API= '27c480add2ca34385099693a96586bd2';
//create a new curl resource
$ch = curl_init();
//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//$output = our stauts.xsl file
$output = curl_exec($ch);
//close curl resource to free up system resources
curl_close($ch);
//loop through $ouput and sort into our different arrays
$dp = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($dp,$to_push);
}
}
$x = explode(" - ",$dp[9]);
echo json_encode($dp);
}
?>
I know it doesn't look pretty yet, but that's what CSS is for right?
Any ideas? Essentially I need the PHP script to rerun, update the variables, and rebuild the text output without touching the audio tag.
Javascript is code that executes client-side (on the website visitors machine) and PHP executes serverside. The way to insert content into a page without reloading the entire page is to use Javascript to inject code into the HTML. Now, for example, say that you have a PHP file on your server, called getLatest.php with a function called getLatestVariables() that finds out the latest values for all your variables and returns an array containing them. What you can do is use javascript to call getLatestVariables() from getLatest.php, and when the function returns the array, it will return it to the javascript. Once the array of variables has been returned to the javascript you can then insert the variabes into HTML divs without having to refresh the entire page.
to call the php function I suggest using jquery to perform an ajax call
also to insert the data returned from the php, jquery is your best bet too.
You need client side JavaScript for this. Get your hands on basic ajax books.
You can request the script for updated data every 5 seconds and update it on the page, this is complicated and needs some knowledge of JavaScript.
The script will have to be new too, or this one edited to trace type of request and return data accordingly.
var url="http://script-address"
var req = new XMLHttpRequest(); // Begin a new request
req.open("GET", url); // An HTTP GET request for the url
req.send(null);
This is how you can check the response
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
//we got a complete valid HTTP response
var response = req.responseText;
//code to handle response
}
php is a serverside language, so re-running the php inside your page will always result in the entire page refreshing, however if you use a javascript ajax call (I suggest using jquery) to a different php file, that php file can be executed serverside without affecting your page. you can then return the newly found variables from this php file to the javascript, and insert them in the callback of the ajax call.
see the answer to this question
If you need any more detail let me know...
$.getJSON('phpFileThatReturnsJSON.php', function(data) {
//'data' will be the json that is returned from the php file
$.("#idOfDivToInsertData").html("an item from the json array ie data['song']");
});
look at JQuery docs for ajax calls, if you've got this far you should be able to nail it out pretty quickly.
Also dont forget to include the jquery library in your html header...
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>

How to activate PHP file in JavaScript function

I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");

[PHP/JavaScript]: Call PHP file through JavaScript code with argument

I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.

Categories