Sending information via ajax partially working/failing - mysql

I am trying to send information about the user browser to a mysql database via ajax and this method that used to work perfectly on another site is now working partially, meaning that the data about the screen and browser width/ height, the color and pixel depth don't appear in my database and the information collected via php are sent/ saved.
Here is what I have in my index.html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html lang="en">
<head>
<title>Welcome</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
function ajax_post() {
var hr = new XMLHttpRequest();
var url = "st.php";
var sw = screen.width;
var sh = screen.height;
var bw = document.documentElement.clientWidth;
var bh = document.documentElement.clientHeight;
var cd = screen.colorDepth;
var pd = screen.pixelDepth;
var vars = "sw="+sw+"&sh="+sh+"&bw="+bw+"&bh="+bh+"&cd="+cd+"&pd="+pd;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
}
}
hr.send(vars);
};
ajax_post();
</script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
My content here
</body>
</html>
and here is the content of the st.php file used to collect information via php and to send/ seve it to the database:
<?php
$dnt = date(DATE_COOKIE);
$ip = $_SERVER['REMOTE_ADDR'];
$rh = gethostbyaddr($ip);
$re = $_SERVER['HTTP_REFERER'];
$ua = $_SERVER['HTTP_USER_AGENT'];
$al = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$sw = $_POST['sw'];
$sh = $_POST['sh'];
$bw = $_POST['bw'];
$bh = $_POST['bh'];
$cd = $_POST['cd'];
$pd = $_POST['pd'];
$db_host = ********; // the host
$db_user = ********; // the user
$db_password = ***********; // the password
$connection = mysql_connect($db_host, $db_user, $db_password) or die(mysql_error());
mysql_select_db(*******) or die(mysql_error());
$query = "INSERT INTO *********(dnt, ip, rh, re, ua, al, sw, sh, bw, bh, cd, pd)
VALUES ('".mysql_real_escape($dnt)."','".mysql_real_escape($ip)."','".mysql_real_escape($rh)."','".mysql_real_escape($re)."','".mysql_real_escape($ua)."','".mysql_real_escape($al)."','".mysql_real_escape($sw)."','".mysql_real_escape($sh)."','".mysql_real_escape($bw)."','".mysql_real_escape($bh)."','".mysql_real_escape($cd)."','".mysql_real_escape($pd)."')";
mysql_query($query) or die(mysql_error());
?>
I checked that I wasn't blocking any script (deactivated noscript), I tried it on Firefox and Chrome and Epiphany without any success: no data about the screen and browser width/ height, the color and pixel depth.
I don't have any idea why this is not working as I used exactly the same code one week ago on a website on the same host and it worked perfectly.
Thank you for your help.
----- EDIT -----
Thanks to #PiTheNumber I checked the Firebug Console and tracked the origin of the problem
Problem solved
Waiting 6 more hours to be able to answer my own question since I have less than 100 points of reputation and therefore cannot answer it right now.

This is very nice for mysql injection!
Use mysql_real_escape() with your insert:
$query = "INSERT INTO *********(dnt, ip, rh, re, ua, al, sw, sh, bw, bh, cd, pd)
VALUES ('".mysql_real_escape($dnt)."'...)";

Thanks to #PiTheNumber I checked the Firebug Console and tracked the problem to the rewriting/ redirecting of .php files that were breaking part of the POSTing of the the screen and browser width/ height, the color and pixel depth.

Related

Is it possible to send a POST request only through HTML (without javascript)?

I want to send a newsletter through email and I would like to see who opened my email.
I send HTML in the content of the email, so I can not add javascript in there. (see here )
Is there any way to send a post request (to my server) only through HTML, every time the HTML is opened and not by pressing a button?
No.
The only HTTP requests that can be triggered by simply opening an HTML document without any JS in it are GET requests.
Tracking of HTML emails is usually achieved using GET requests from images (and usually blocked by email clients because it is intrusive).
I think you are wanting to track emails which are opened? If you are using a PHP server you can create a simple "pixel" but would need to hook it up to your database.
Inside your email you can load the pixel as an image and replace the %pixel_id%
<img src="https://yoururl/pixel.php?tid=%pixel_id%" style="width:1px;height:1px;" title="pixel">
Pixel code:
<?php
//YOU NEED TO INCLUDE YOUR DATABASE CONNECTION FILE HERE
$conn_cms=get_dbc();
$stmt = $conn_cms->prepare("SELECT * FROM `pixel_tracker` WHERE `pixel_id` = ?");
$stmt->bind_param("s", $tid);
$tid = $_GET['tid'];
$stmt->execute();
$result = $stmt->get_result();
$assoc = $result->fetch_assoc();// get the mysqli result
$stmt = $conn_cms->prepare("UPDATE `pixel_tracker` SET `seen` = ?,`seen_count` = ?,
`seen_when`= ?, `header_track`= ? WHERE `pixel_id` = ?");
$stmt->bind_param("sssss", $seen, $seen_count, $seen_when, $header_track, $pixel_id);
$seen = 1;
$seen_count = $assoc['seen_count']+1;
$seen_when = date("Y-m-d H:i:s");
if(isset($_SERVER['HTTP_REFERER'])){
$header_track = $_SERVER['HTTP_REFERER'];
} else {
$header_track = "none";
}
$pixel_id = $tid;
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$pixel = imagecreate(1,1);
$color = imagecolorallocate($pixel,255,255,255);
imagesetpixel($pixel,1,1,$color);
header("content-type:image/jpg");
imagejpeg($pixel);
imagedestroy($pixel);
?>
EDIT: If you are sending emails automatically from your server you can dynamically insert the pixel reference in to your database, otherwise for now you can do this manually.

How Do I Set A Variable to Cell Value that has Line Breaks, and Return Variable in HTML Template?

I'm trying to pass a cell value that contains line breaks into an HTML template for an outbound e-mail I am able to grab the values, but the line break isn't populating correctly. In this example, I'm using var row as my active row, and the cell I want to grab is index 36.
var notesUpdateHTML = row[36].replace(/\n/g,"<br>")
Index 36 is being updated by this code, which is grabbing the new update text, and appending the old update text(s) below it.
// setting notes values
var newNotes = developerQueueSheet.getRange("E7").getValue();
var oldNotes = developerQueueSheet.getRange("I2").getValue();
var newNotesDateFormat = Utilities.formatDate(new Date(), spreadsheetTimeZone, "M.dd");
var newNotesFormat = newNotesDateFormat + ' - ' + sessionEmail + ' // ' + newNotes
var notesUpdate
if (newNotes == '') {
notesUpdate = oldNotes
} else if (newNotes != '') {
notesUpdate = newNotesFormat + "\r" + "\n" + oldNotes
}
eSheet.getRange(startRow + i, 37).setValue(notesUpdate);
Inside the HTML Template, I am able to grab the notes and separate them into the newest update and the older ones. However, they just return as one long text blob.
I did try referencing the only other post I could find on my question, but still can't get it to return correctly.
Any advice/direction you all could provide would be greatly appreciated.
Thanks!
Update
Here's the code that I'm using to send the e-mail:
var MyToAddress;
var MyCCAddress
var MySubject;
var MyTemplate;
var processOwner
if (row[15] == "Existing Automation/Database" & row[17] == "Error") {
MyTemplate = HtmlService.createTemplateFromFile('errorEmailBody.html')
MySubject = "TCS Automation - A User Has Identified a Potential Error!"
MyToAddress = currentDatabaseEmail
MyCCAddress = row[14]
MyTemplate.row = row;
var messageBody = MyTemplate.evaluate().getContent();
var emailAddress = MyToAddress;
var ccAddress = MyCCAddress;
var subject = MySubject;
MailApp.sendEmail({
to: emailAddress,
cc: ccAddress,
subject: subject,
htmlBody: messageBody,
replyTo: emailAddress,
noReply: true
})
Here's the inside of the HTML template file
<!DOCTYPE html>
<html>
<head>
<style>
h1 {color:#fff ;background: #8E8E8F}
h2 {color:#fff ;background: #012F60}
</style>
</head>
<body>
Your project has been has a new update from <?= row[49] ?>.<br>
<p><b>Status</b><br>
<i><?= row[54] ?></i></p>
<p><b>ETA Update (If Applicable)</b><br>
<i><?= row[60] ?></i></p>
<p><b>New Notes</b><br>
<i><?= row[58] ?></i></p>
<p><b>Historical Notes</b><br>
<i><?= row[59] ?></i></p>
</body>
</html>
When using printing scriptlets (ie <?= row[59] ?>), google scripts automatically adds escape characters to protect against XSS attacks. This is a known behavior and has been documented here
In cases exactly like yours, where you are trying to add HTML elements dynamically, you can use force-printing scriplets (i.e <?!= row[59] ?>.
As a general rule, use printing scriptlets rather than force-printing
scriptlets unless you know that you need to print HTML or JavaScript
unchanged.
So your final HTML code will look like this:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {color:#fff ;background: #8E8E8F}
h2 {color:#fff ;background: #012F60}
</style>
</head>
<body>
Your project has been has a new update from <?= row[49] ?>.<br>
<p><b>Status</b><br>
<i><?= row[54] ?></i></p>
<p><b>ETA Update (If Applicable)</b><br>
<i><?= row[60] ?></i></p>
<p><b>New Notes</b><br>
<i><?= row[58] ?></i></p>
<p><b>Historical Notes</b><br>
<i><?!= row[59] ?></i></p>
</body>
</html>

TYPO3 website multilanguage configuration

I want to configure a multi language TYPO3 website. I tried to put this code to Page TSConfig
config {
linkVars = L
sys_language_uid = 0
sys_language_overlay = 1
sys_language_mode = content_fallback
language = sq
locale_all = sq_AL.UTF-8
htmlTag_setParams = lang="sq" dir="ltr" class="no-js"
}
[globalVar = GP:L = 1]
config {
sys_language_uid = 1
language = en
locale_all = en_US.UTF-8
htmlTag_setParams = lang="en" dir="ltr" class="no-js"
}
[global]
[globalVar = GP:L = 2]
config {
sys_language_uid = 2
language = it
locale_all = it_IT.UTF-8
htmlTag_setParams = lang="it" dir="ltr" class="no-js"
}
[global]
but when attaching the L parameter with sys_language_uid to the page URL, nothing happens. My template is :
#about
ABOUT = CONTENT
ABOUT {
table = tt_content
select {
where = colPos=1
languageField = sys_language_uid
}
}
I Have translated the content in Page Module.
Am I using this right or not? How can I properly configure the languages?
The Code you have shown above goes to TypoScript Setup. Not in the Page TS Config in the page properties.
Use the "Template" module on the left as admin in your TYPO3 backend. When you edit the template, it has two parts for code: Constants and Setup. Use that code in setup and clear the cache.

Facebook login page and cache

I've got a Facebook login in my website
but I need to request permission to post in my user's wall.
I found many many examples on google that use the scope, but they're too different form mine, and I don't understand where to put it
This is the code:
<?php
session_start();
// added in v4.0.0
require_once 'autoload.php';
require 'functions.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// init app with app id and secret
FacebookSession::setDefaultApplication( 'APPID','APPSECURE' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('http://www.bestparty.altervista.org/APP/facebook/fbconfig.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email');
/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
checkuser($fbid,$fbfullname,$femail);
/* ---- header location after session ----*/
$cookie_name = 'FBID';
$cookie_value = $fbid;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/');
$cookie_name2 = 'FULLNAME';
$cookie_value2 = $fbfullname;
setcookie($cookie_name2, $cookie_value2, time() + (86400 * 30), '/');
header("Location: ../gestaccount.php");
} else {
$cookie_name = 'FBID';
$cookie_value = $fbid;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/');
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
Also:
May I save the access token in mysql to use it in future?
Why does the datas that I save in cache stays only until I close the browser?
1, You can store the access token however which way you like. As long as it's secure and you are able to update them in case of expired/updated/extended access tokens, it should be fine.
2, This is a bit unclear, are you setting and handling cookies correctly ?

Update MySQL Value Through Img Src Variable Including jQuery

Thank-you to all who have helped me over the last few days.. Unfortunately I was working so I couldn't get back to you. I have included some code into what I thought would work, but for some reason the below code will not update in my SQL Database. I will provide the code and it's output if someone could please copy the code and see why it's not working... It's really doing my head in! Haha!
(The connection to the MySQL db + table is working fine).
// admin.php
<a href="#" id="chngeHref" /><img src="<?php echo "image.php?url=" . $row[2]; ?>?tid=<?php echo $row[0]; ?>&opn=<?php echo $row[1]; ?>" id="chnge" /></a>
// image.php?url=image.jpg?tid=3&opn=1
I was advised to do it this way to make it easier for me to pass the variables (tid and opn) through the process.
// update.php
$tid = $_GET['tid'];
$opn = $_GET['opn'];
if ($opn == "0") { $opn = "1"; } elseif ($opn == "1") { $opn = "0"; }
mysql_query("UPDATE catalogue SET opn = $opn WHERE tid = $tid ; ");
mysql_close();
// it's just a simple script to change a variable from 1 to 0 or 0 to 1 where tid = a specific number...
I have my jQuery stuff all tucked away in a lovely little file, because there is alot of it...
// navigate.js
$.extend({
getUrlVars: function() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
return vars;
}
});
$("#chngeHref").click(function() {
var tid = $.getUrlVars()['tid'];
var opn = $.getUrlVars()['opn'];
$.ajax({
type: "POST",
url: "update.php",
data: "tid="+ tid +"& opn="+ opn,
success: function(){
$('#chnge').fadeTo('slow',0.4);
}
});
});
The .extend code i found on the net which finds the parameter and value of all those in the address line. I THINK this is where my issue might be, because the top code is never actually sending it to the address bar, it's being sent through jQuery to the update.php file.
I can only say thank-you soooo much in advance to anyone who can assist in this.
Phillip.
There are a few issues here bsides the SQL Injection vulnerability Nathan mentions, namely you're POSTing, so you need to use $_POST rather than $_GET to retrieve your variables. Also you have an extra space in the data block, this:
data: "tid="+ tid +"& opn="+ opn,
should be:
data: "tid="+ tid +"&opn="+ opn,
or a bit cleaner using object notation (so it also gets properly encoded):
data { tid: tid, opn: opn },
For the SQL Injection issue, instead of this:
mysql_query("UPDATE catalogue SET opn = $opn WHERE tid = $tid ; ");
At the very least escape the values, like this:
$tid = mysql_real_escape_string($_POST['tid']);
$opn = mysql_real_escape_string($_POST['opn']);
Or, go the parameterized query route, which is what I'd prefer.