How to call Javascript API to Get IP Address in PHP Function? - javascript

I have a problem while calling javasript function in php. I found this script in : How to get client's IP address using javascript only?
<html>
<body>
<h1> Demo retrieving Client IP using WebRTC </h1>
<script type="text/javascript">
function findIP(onNewIP) { // onNewIp - your listener function for new IPs
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
var pc = new myPeerConnection({iceServers: []}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
key;
function ipIterate(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
pc.createDataChannel(""); //create a bogus data channel
pc.createOffer(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(ipIterate);
});
pc.setLocalDescription(sdp, noop, noop);
}, noop); // create offer and set local description
pc.onicecandidate = function(ice) { //listen for candidate events
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
};
}
var ul = document.createElement('ul');
ul.textContent = 'Your IPs are: '
document.body.appendChild(ul);
function addIP(ip) {
console.log('got ip: ', ip);
var li = document.createElement('li');
li.textContent = ip;
ul.appendChild(li);
}
findIP(addIP);
</script>
<?php echo "<script>addIP(ip);</script>"; ?>
</body>
</html>
Why it's all suddenly gone while i add this script :
<?php echo "<script>addIP(ip);</script>"; ?>
Is there anything wrong with my code ? Please Help

It looks like you're calling the addIP() function with a variable called ip that does not exist. I'm assuming you want to substitute that with the user's IP. To do this you would pass the IP address from PHP to Javascript with the following:
<?php echo '<script>addIP("' . $_SERVER['REMOTE_ADDR'] . '")</script>'; ?>
If you're testing locally it might output something like:
<script>addIP("::1")</script>
<script>addIP("127.0.0.1")</script>
<script>addIP("192.168.0.1")</script>
REMOTE_ADDR is not always reliable as it's sometimes the address of a proxy server the user is behind.

change from server call <?php echo "<script>addIP(ip);</script>"; ?> to client call <script type="text/javascript"> addIP(ip); </script>

(Just in case: your html file needs to use .php as extension.)
Try changing to:
<script type="text/javascript"> addIP(<?php echo $ip; ?>); </script>
On a side note: Something like this method of php in html will work fine but using a template engine would remove php code from display logic. Something like phpTal or one of the many others would be good to use. If you are only doing it for one value then don't bother with templating. but if you are dynamically creating html by using html in you php or php in your html then a template langue is what I would recommended.

Related

How to read all text files in a folder and filter display based on the suffix or prefix

I'm trying to use jQuery to read all text files in a folder and display their contents, but then, filter which should ones should be displayed based on the name of the folder.
Here's the JavaScript:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt": "",
"01600610/9874565214_789545623.txt": ""
};
$.each( obj, function(SavedText) {
$.get(SavedText, function(data){
$('#NewMessagesHolder').prepend('<div class="MessageClass">'+ '<span class="ChatName">' + CookieName + ' ('+ time + ')</span>' + ': '+ data +'</div>')
}, 'text');
});
On this:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt":"",
"01600610/9874565214_789545623.txt":""
};
Q1: How do I get all text files inside a folder instead of specifying the file I want?
Q2: How can I filter? For example, how can I only get files ending or starting with 789545.
When these files are on your local filesystem, you can use the HTML5 Filesystem API.
If the files are located on a server, there is no way listing them from plain (client-side) javascript (maybe except a brute-force method, which shouldn't be considered of course). Then you have to write a server script (in PHP/Node/Perl/Phython/...) which will respond to a ajax request with a file list.
If you are using a server script, you should do the filtering on the server (so the answer depends on the language).
Otherwise you should use Regular Expressions:
var search = new RegExp("789545");
for(var file in obj) {
if(search.test(file))
alert(file+": "+obj[file]);
}
This would search for files with a name containing the pattern 789545
Please create index.php file and add this content to it. Create there a folder called "files" and add your files there
<?php
function contains($haystack, $needle){
if (strpos($haystack,$needle) !== false) {
return true;
}
return false;
}
if(isset($_POST['get_files'])){
$folder = "";
$filter = "";
if(isset($_POST['folder'])){
$folder = $_POST['folder'];
}
if(isset($_POST['filter'])){
$filter = $_POST['filter'];
}
$files = array();
foreach(glob($folder.'/*.*') as $filename){
if($filter != ""){
if(contains($filename, $filter)){
$files[] = $filename;
}
}else{
$files[] = $filename;
}
}
print_r($files);
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getData(){
jQuery.post('index.php',{
get_files:true,
folder:"files",
filter:""
},function(data){
jQuery('#container').html(data);
});
}
</script>
</head>
<body>
<input type="button" value="Get data" onclick="getData();" />
<div id="container"></div>
</body>
</html>
You can specify different folder, and filename filter in jQuery post request call
U can use regular expressions to filter the filenames. And for getting all files in a folder, U want to run a server side script. I use perl or php, to do this kinda stuff. U can use ajax to post the request and make the server script to return the file contents.
http://perlmeme.org/faqs/file_io/directory_listing.html
This link is just an example to do what u need in perl. And u could possibly do the same with other languages too

Youtube API loadVideoByUrl() function

I've got this code, which add videos (and videos infos) of a YouTube channel ($_POST) on a div of the Html code, and I want to play a video in the Youtube player after click on an element:
var args= "url="+urlchaine;
xhr_object.open("POST", "traitement.php", true);
xhr_object.onreadystatechange = function() {
if(xhr_object.readyState == 4) {
eval(xhr_object.responseText);
}
return xhr_object.readyState;
}
xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr_object.send(args);
traitement.php :
<?php
if ( isset($_POST["url"]) && !empty($_POST["url"]) )
$urlchaine = $_POST["url"];
else
$urlchaine = null;
$stringresult = str_replace("http://www.youtube.com/user/", "",$urlchaine);
require_once "Zend/Loader.php";
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
$videoFeed = $yt->getVideoFeed('http://gdata.youtube.com/feeds/users/...');
if ( $stringresult != null){
echo "var mydiv = document.getElementById('vids');";
echo "var newcontent = document.createElement('div');";
foreach ($videoFeed as $v): $thumbs = $v->getVideoThumbnails();
echo "newcontent.innerHTML = '...'";
echo "mydiv.appendChild(newcontent.firstChild);";
endforeach;
echo "img_videos.addEventListener('click',function () {
$('#ytplayer_footer').fadeIn('normal');
var idvideo = this.getAttribute('idvideo');
var ytplayer = document.getElementById('ytplayer');
ytplayer.loadVideoByUrl('...'); // ****** Here the problem
ytplayer.playVideo();
},false);";
?>
And I have this error : Object # has no method 'loadVideoByUrl'
What's wrong in my code ?
You might have some quote escaping issues going on here. Take a look at this line:
var ytplayer = document.getElementById("ytplayer");
You're using double quotes, but your "echo" statement also uses double quotes. Switch that to single quotes and see what happens. I'm somewhat surprised this code runs at all.
(Looks like the question was changed)
The other thing to look out for is that you don't seem to be loading the YouTube JS anywhere. You're loading the PHP client library which runs server-side, but you also need to load the JavaScript libraries client side - otherwise you're just trying to call "loadVideoByUrl()" on a vanilla DOM object.

running a php function inside javascript code [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I hope to run a php code inside a javascript code too and I do like that :
<?php function categoryChecking(){
return false;
}?>
....
function openPlayer(songname, folder)
{
if(<?php echo categoryChecking() ?> == true)
{
if (folder != '')
{
folderURL = "/"+folder;
}else
{
folderURL = '';
}
var url = "/users/player/"+songname+folderURL;
window.open(url,'mywin','left=20,top=20,width=800,height=440');
}else{
alerte('you should click on a subcategory first');
}
}
....
<a href='javascript:void();' onClick="openPlayer('<?php echo $pendingSong['id']; ?>','')">
finally I get this error instead the alert message "you should click on a subcategory first"
ReferenceError: openPlayer is not defined
openPlayer('265','')
You're reduced your test case too far to see for sure what the problem is, but given the error message you are receiving, your immediate problem has nothing to do with PHP.
You haven't defined openPlayer in scope for the onclick attribute where you call it. Presumably, the earlier JS code is either not inside a script element at all or is wrapped inside a function which will scope it and prevent it from being a global.
Update: #h2ooooooo points out, in a comment, that your PHP is generating the JS:
if( == true)
Check your browser's error console. You need to deal with the first error messages first since they can have knock on effects. In this case the parse error in the script will cause the function to not be defined.
Once you resolve that, however, it looks like you will encounter problems with trying to write bi-directional code where some is client side and some is server side.
You cannot run PHP code from JavaScript, because PHP is a server-side language (which runs on the server) and JavaScript is a client-side language (which runs in your browser).
You need to use AJAX to send a HTTP request to the PHP page, and then your PHP page should give a response. The easiest way to send a HTTP request using AJAX, is using the jQuery ajax() method.
Create a PHP file ajax.php, and put this code in it:
<?php
$value = false; // perform category check
echo $value ? 'true' : 'false';
?>
Then, at your JavaScript code, you should first add a reference to jQuery:
<script type="text/javascript" src="jquery.js"></script>
Then, use this AJAX code to get the value of the bool:
<script type="text/javascript">
$.ajax('ajax.php')
.done(function(data) {
var boolValue = data == 'true'; // converts the string to a bool
})
.fail(function() {
// failed
});
</script>
So, your code should look like this:
function openPlayer(songname, folder) {
$.ajax('ajax.php')
.done(function (data) {
var boolValue = data == 'true'; // converts the string to a bool
if (boolValue) {
if (folder != '') {
folderURL = "/" + folder;
} else {
folderURL = '';
}
var url = "/users/player/" + songname + folderURL;
window.open(url, 'mywin', 'left=20,top=20,width=800,height=440');
} else {
alert('you should click on a subcategory first');
}
})
.fail(function () {
// failed
});
}

How to send json_encode data with HTML5 SSE

I have a script that fires an SSE event for fetching json encoded data from online.php.
On googling, I found ways to send JSON data with sse, by introducing line-breaks.
What I am looking for is how to send JSON over SSE when the JSON array is created using PHP's json_encode() function.
I have written the following lines of code, but could anybody help me with where to add the "data: \n\n" required for SSE?
<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("online.php");
source.onmessage=function(event)
{
var data=JSON.parse(event.data);
$("#new_message").html("Inbox"+data['total']);
};
}
else
{
$("#new_message").html("HTML5 not supported");
}
</script>
online.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$data["total"]="hello";
echo json_encode($data);
ob_flush();
flush();
?>
You need to send it in EventStream format, which in this case is just prepending it with data:
echo 'data: ' . json_encode($data) . "\n\n";
You can encode the $data array like Ryan said:
echo 'data: ' . json_encode($data) . "\n\n";
Then, client side, event.data will be viewed as a string, which you can then easily parse to json using query's jQuery.parseJSON(). so your client-side code will look something like this:
// Check if the browser supports SSE
if (typeof (EventSource) !== "undefined") {
var source = new EventSource("script.php");
// Handle evetns
source.onmessage = function(event) {
// parse the data that has an object as a string
var msg = $.parseJSON(event.data);
// Do awesome code with the values inside msg
};
} else {
alert("Sorry, your browser doesn't support this awesome feature!");
}
Source: http://api.jquery.com/jquery.parsejson/
Your script will only show output once as it needs to have some kind of a loop to keep running (conditionally of course or you'll have millions of instances running!!).
I've chopped up an implementation I wrote earlier today which demonstrates this and also added some additional javascript/jquery to help manage the streams better. The below will also work on a single threaded PHP installation like Xampp (for local development)
Notes on Xampp: As the PHP script is in a loop and doesn't terminate immediately it will stop a new php or agax script from running. If you're using ajax as well to call PHP call stream_close() in the beforesend and stream_open() in the success callbacks.
The below is untested but it's mainly grabbed from working code so it should be fine.
<?
//stream.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
stream();
function stream(){
$data = array();
//collect data from database or wherever to stream to browser
//example data
$data[0]["name"] = 'Bob';
$data[0]["total"] = rand(0,100);
$data[0]["name"] = 'Jane';
$data[0]["total"] = rand(0,100);
//maybe there is no new data so just send one new line
//this is required to check if the connection is still alive
if(!empty($data)){
echo "\n";
}else{ //Otherwise json encode the data for output
echo 'data: '.json_encode($data)."\n\n";
}
flush(); //Flush the result to the browser
sleep(1); //Wait a second (or what ever you like)
//If the browser is still connected
if(!connection_aborted() && connection_status()==0){
stream(); //recurse the function
}
}
?>
<script>
var webstream = false;
function stream_open(){
stream_close(); //Close the stream it (in case we got here weirdly)
if(!!window.EventSource){ //Test compatibility
webstream = new EventSource('./stream.php');
console.log("Stream Opened"); //Log event for testing
webstream.addEventListener('message', function(e){
var data = JSON.parse(e.data); //Parse the json into an object
process_stream(data);
},false);
//Cleanup after navigating away (optional)
$(window).bind('beforeunload', function(){
webstream.onclose = function(){}; //delete onclose (optional)
webstream.close(); //Close the stream
});
}
}
function stream_close(){
if(typeof(webstream)=="object"){
webstream.close();
webstream = false;
console.log("Stream Closed"); //Log event for testing
}
}
function process_stream(data){
//do something with the new data from the stream, e.g. log in console
console.log(data);
}
//Optional:
//Toggle stream on blur/focus
//Good if the user opens multiple windows or Xampp?
$(window).on("blur focus", function(e) {
//get the last blur/focus event type
var prevType = $(this).data("prevType") || null;
if (prevType != e.type){
console.log(e.type); //Log event for testing (focus/blur)
switch (e.type){
case "blur":
stream_close(); //Close stream on blur
break;
case "focus":
stream_open(); //Open stream on focus
break;
}
}
//Store the last event type to data
$(this).data("prevType", e.type);
});
// Optional:
// Using idletimer plugin to close the stream in times of inactivity
// https://github.com/thorst/jquery-idletimer/blob/master/src/idle-timer.js
$(document).on("idle.idleTimer", function (){
stream_close();
});
$(document).on("active.idleTimer", function (){
stream_open();
});
$(document).idleTimer({timeout:5000}); //5 second idle timer
</script>

defined path from php to javascript

I have a little problem with the syntax in Javascript. I want to work with a defined variable for a path in Javascript.
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "http://localhost:8888/.../file.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Now I want to set for
http://localhost:8888/.../file.php
a defined variable from php
define('Name','http://localhost:8888/.../file.php');
You'd either have to retrieve that constant via an AJAX call, or embed it into the Javascript at the time PHP is building the page.
e.g.
<?php
define('your_url', 'http://.....');
?>
<script type="text/javascript">
var url = <?php echo json_encode(your_url) ?>;
...
var ajax = ajaxOBJ('POST', url);
Note that if the sole purpose of this constant is to hold a url that's passed to javascript and is otherwise never used in PHP, you might as well just use a variable - Javascript could not alter the PHP/server-side value anyways, so it's effectively a constant.

Categories