I have a php script that receives parsed data from a javascript application via xmlhttp.
I'm finding that the php script will sometimes stop while it's processing a chunk of data and restart with the same POST data that was sent to it. I thought that maybe the javascript's xmlhttp might be double firing somehow, but I've ruled that out with an inProgress flag as shown below.
function SendPHP(str, callback){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
xmlhttp.open("POST","sendmail.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
inProgress=false;
if(xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if (inProgress==false){
inProgress=true;
xmlhttp.send(str);
}
else{
writeDisplayConsole("ERROR: xmlhttp fired twice!");
}
}
If the xmlhttp tries to send twice then that error is shown and no further packets will be sent. But that's never the case so the php script must be restarting on it's own.
Bear in mind that it happens at random intervals, not at the same time every time with the same data. What could be causing this to happen?
The php script frequently writes to big text file logs, could that be something to do with it?
Here's the php (but since the error happens at random intervals with the same data, I'm not sure how it could be a problem with the php code):
<?php
writelog("\n*** Sendmail script started ***");
$q = $_POST['q'];
//Split auth code and verify
$pieces = explode("(<!asplit!>)", $q);
$authc=$pieces[0];
$q=$pieces[1];
if ($authc<>"****"){
echo "!Authentification denied.";
writelog ("Authentification denied");
die;
}
writelog ("Authentification accepted");
//Split off packet details
$pieces=explode("(<!psplit!>)", $q);
$tpack=$pieces[0];
$q=$pieces[1];
$pieces=explode("-", $tpack);
$tpacket=$pieces[0];
$ofpacket=$pieces[1];
$totalcontacts=$pieces[2];
//Split contact data from email message
$pieces = explode("(<!dsplit!>)", $q);
$split=$pieces[0];
$q=$pieces[1];
//Assign contacts to array
$contacts = explode ("<!", $split);
$tcount=count($contacts);
$tcount=$tcount-1;
echo "(PACKET ";
echo $tpacket;
echo " OF ";
echo $ofpacket;
echo ")- ";
writelog("(PACKET " . $tpacket . " of " . $ofpacket . ")");
//Killswitch check incase double run
checkKillSwitch("!Startup aborted as Power set to off.",0);
checkKillSwitch("!Aborted, Killswitch set to Kill",1);
file_put_contents('log/killswitch.txt', "on");
echo $tcount;
echo " contacts processing...";
foreach ($contacts as &$value) {
//check killswitch
checkKillSwitch("Killswitch aborted during runtime",1);
$split=explode ("^!", $value);
//Get the contact's details
$firstname= $split[0];
$lastname= $split[1];
$temail = $split[2];
if ($firstname<>""){
$mainmessage=str_replace("[firstname]",$firstname,$q);
$mainmessage=str_replace("[lastname]",$lastname,$mainmessage);
//Split off subject
$pieces = explode("(/subject)", $mainmessage);
$tsubject=$pieces[0];
$mainmessage=$pieces[1];
testLogMail($temail, $tsubject, $mainmessage);
//log progress
$adder=$adder+1;
//For the log, show progress of total (based on 10 per packet change if different)
$tadder = (($tpacket-1)*10)+$adder;
echo ($tadder . ".");
writelog($tadder . " of " . $totalcontacts . " processed >> " . $temail);
sleep(rand(2,20));
}
}
function testLogMail($xaddress, $xsubject, $xmessage){
$tdate=date('d/m/Y H:i:s');
$file = 'log/testmaillog.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Enter email
$towrite="To: ".$xaddress."\n";
$towrite.="Subject: ".$xsubject."\n";
$towrite.="Date: ".$tdate."\n";
$towrite.="...\n";
$towrite.=$xmessage."\n";
$towrite.="___________________________________\n\n";
$current .= $towrite;
// Write the contents back to the file
file_put_contents($file, $current);
}
function writelog($towrite)
{
$tdate=date('d/m/Y H:i:s');
$file = 'log/testlog.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $towrite." --- ".$tdate."\n";
// Write the contents back to the file
file_put_contents($file, $current);
}
function checkKillSwitch($towrite, $killtype){
if ($killtype==0){
$killswitch = file_get_contents('log/killswitch.txt');
if ($killswitch=="on") {
echo $towrite;
writelog($towrite);
die;
}
}
if ($killtype==1){
$killswitch = file_get_contents('log/killswitch.txt');
if ($killswitch=="kill") {
echo $towrite;
writelog($towrite);
die;
}
}
}
writelog("*** Sendmail script ended ***");
?>
Related
I have an HTML/PHP form that uses JAVA SCRIPT function to send (POST) an input content to a PHP code which performs a query and gets back to the JAVA SCRIPT function with data to Auto fill additional inputs in the form.
It all works great when the input content i send is plain text, even if there is a single quote in the content it works.
BUT, as soon as double quotes are included in the input content it fails to return the Auto fill results.
Appreciate your help with indicating where do i fail with passing the quotes.
Thanks
Just to make it clearer, the code works if customer name is "Intel" or "Int'el" , but it fails when customer name is "Int"el"
Here is the JAVA SCRIPT function that sends and receive the data from the PHP:
!--Script Auto fill ltd by customer -->
<script type="text/javascript">
function updatefrm() {
setTimeout(function(){
var customer = $('#customer').val();
if ($.trim(customer) !='') {
$.post('customerfill.php', {customer: customer}, function(data) {
$('#customerupdate').val(data['customer']);
$('#ltdupdate').val(data['ltd']);
});
}
}, 10);
}
</script>
Here is the PHP code that gets the POST data , performs the query, and sends back the array for the JAVA SCRIPT auto fill:
<?php
if (!empty($_POST['customer'])) {
$DB_Server = "localhost"; // MySQL Server
$DB_Username = "XXXX"; // MySQL Username
$DB_Password = "XXXX"; // MySQL Password
$DB_DBName = "XXXXXXXX"; // MySQL Database Name
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Failed to connect to MySQL:<br />" . mysql_error() . "<br />" . mysql_errno());
// Select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Failed to select database:<br />" . mysql_error(). "<br />" . mysql_errno());
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$safe_name = mysql_real_escape_string(trim($_POST['customer']));
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
json($row);
} else {
json(null);
}
}
function json ($array) {
header("Content-Type: application/json");
echo json_encode($array);
}
i think your js code is fine and i think error in your php code and in that line
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
so you should use PDO Prepared Statements for security and not face problem with double quote
$dsn = "mysql:host=localhost;dbname=your_database;charset=utf8mb4";
try {
$pdo = new PDO($dsn, "database_username", "database_password");
} catch (Exception $e) {
echo "no connection";
exit();
}
$stmt = $pdo->prepare("SELECT * FROM customers WHERE customer = :customer LIMIT 1");
$stmt->execute(array(":customer"=>$safe_name));
$row = $stmt->fetch();
I'm working on a script that forms a web page based on what is in my database. For his I call a java script function when the page loads and whenever the page needs to update.
Firstly I made a script that gets the information from the database, passes it to java script by echo "var region_list = ". $js_region_list . ";\n"; and then proceeded to generate the page itself which worked.
After that I tried to get this to work based on an AJAX request but this failed horribly. As it stands I get correct information from the database but it does not change the value of echo "var region_list = ". $js_region_list . ";\n"; which prevents the page from updating.
The PHP part of my script:
if(isset($_POST["campaign_id"])){
// Get variables and sanetize
$campaign_id = preg_replace('#[^0-9]#i', '', $campaign_id);
// Create planet list
$planet_list = array();
$sql = "SELECT planet_nr, size, moon FROM planets WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($planet_list, array($row["planet_nr"],$row["size"],$row["moon"]));
}
/* free result set */
mysqli_free_result($result);
}
// Create region list
$region_list = array();
$sql = "SELECT planet_id, region_id, region_type, owner FROM regions WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($region_list, array($row["planet_id"],$row["region_id"],$row["region_type"],$row["owner"]));
}
/* free result set */
mysqli_free_result($result);
}
// Convert array's for use in java
$js_planet_list = json_encode($planet_list);
$js_region_list = json_encode($region_list);
$list = array($planet_list, $region_list);
$list = json_encode($list);
echo $list;
exit();
The javascript part:
<?php
echo "var planet_list = ". $js_planet_list . ";\n";
echo "var region_list = ". $js_region_list . ";\n";
?>
var ajax = ajaxObj("POST", "campaign.php?c="+campaign_id);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "Fail"){
alert(ajax.responseText);
}
}
}
ajax.send("campaign_id="+campaign_id);
NOTE: These are just snippets of the whole script. The whole script is in the same PHP file with the PHP up above between it's tags and the java down between the script tags.
In your ajax success part, you need to just update the values of the the variables planet_list and region_list as shown below
planet_list = JSON.parse(ajax.responseText[0]);
region_list = JSON.parse(ajax.responseText[1]);
I have a "contact us" form and everything is working but my error callback in the ajax runs instead of the success. I ajax is called, the PHP file runs, and I get an email to my localhost (using Mercury).
So why is my success callback not running? I have no idea how to find out what is causing the error especially since everything works.
The only thing I suspect is the file folders. The current structure is this. My html file and php file are in the root directory. The JS file is in a folder.
Here is a screenshot of the network tab in chrome debugger after I press submit
http://i.imgur.com/HfRYjj0.png
My Ajax:
$(document).ready(function(e) {
$("#main-contact-form").on('submit', (function(e) {
e.preventDefault();
$('#sendingemail').fadeIn();
$.ajax({
url : "../sendemail.php",
type : "POST",
data : new FormData(this),
contentType : false,
cache : false,
processData : false,
success : function(data) {
$('#sendingemail').fadeOut();
$('#emailsent').fadeIn();
},
error : function() {
alert("Error");
}
});
}));
});
My PHP:
<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL);
header('Content-type: application/json');
// WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
// WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:
/*$status = array(
'type'=>'Error',
'message'=>'Couldn\'t send the Email at this Time. Something went wrong',
'attachement'=>'Couldn\'t attach the uploaded File to the Email.'
);*/
//Added to deal with Files
require_once ('PHPMailer/class.phpmailer.php');
if (isset($_FILES['uploaded_file'])) {
//require_once('/PHPMailer/class.smtp.php');
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"] / 1024;
//size in KBs
//Settings
$max_allowed_file_size = 10240;
// size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "png");
//Validations
if ($size_of_uploaded_file > $max_allowed_file_size) {
$errors .= "\n Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
}
//------ Validate the file extension -----
$allowed_ext = false;
for ($i = 0; $i < sizeof($allowed_extensions); $i++) {
if (strcasecmp($allowed_extensions[$i], $type_of_uploaded_file) == 0) {
$allowed_ext = true;
}
}
if (!$allowed_ext) {
$errors .= "\n The uploaded file is not supported file type. " . " Only the following file types are supported: " . implode(',', $allowed_extensions);
}
//copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
$upload_folder = "temp/";
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if (is_uploaded_file($tmp_path)) {
if (!copy($tmp_path, $path_of_uploaded_file)) {
$errors .= '\n error while copying the uploaded file';
}
}
}
//--end
$name = #trim(stripslashes($_POST['name']));
$clientemail = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$email = new PHPMailer();
$email -> From = $clientemail;
$email -> FromName = $name;
$email -> Subject = $subject;
$email -> Body = $body;
$email -> AddAddress('root#localhost.com');
//Send to this email
// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION
$email -> isMail();
// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...
if (isset($_FILES['uploaded_file'])) {
if ($email -> AddAttachment($path_of_uploaded_file, $name_of_uploaded_file)) {
//$status[] = 'The Uploaded File was successfully attached to the Email.';
}
}
// NOW, TRY TO SEND THE EMAIL ANYWAY:
try {
$success = $email -> send();
//$status['type'] = 'success';
$status[] = 'Thank you for contacting us. We will reply as soon as possible.';
} catch(Exception $e) {
//$status['type'] ='Error';
$status[] = 'Couldn\'t send the Email at this Time. Something went wrong';
}
// SIMPLY, RETURN THE JSON DATA...
die(json_encode($status));
I've been trying lately to use this sample of AJAX to compare form data to an SQL database from one http://www.example.com domain. My issue is that the readyState is always 1 and my Status is always 0. It is expecting 4 and 200 respectively. It also always returns responseText="" I've looked all over StackOverflow but have unsuccessfully found anything helpful.
I've boggled my mind over what could be the issue, but I just can't seem to get it to work.
*I've also tried to set file permissions on both the JS and PHP, but it functions the same.
*I'm using a dedicated web server to host all this, and I have no problem running most scripts.
//HTML GenerateRep.html
Excuse the lack of < and > tags missing, the code won't appear without them.
form id="formgen" onsubmit="GenRep(this)"
....form stuff....
button id="submit" type="submit">Submit</button
//JAVASCRIPT GenerateRep.js
function GenRep(formgen) {
var email = formgen['repemail'];
var hash = formgen['reppass'];
var first = formgen['firstname'];
var last = formgen['lastname'];
var territory = formgen['territory'];
hash.value = CryptoJS.SHA256(hash.value);
var login = email + ";" + hash.value + ";" + first + ";" + last + ";" + territory;
Login(login);
}
function Login(login) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText == "VALID") {
window.location.href = "success.html";
} else if (xhttp.responseText == "INVALID") {
$("#login_error").text("Failed! Plese check your info.");
} else {
window.location.href = "error.php";
}
}
};
xhttp.open("GET", "Validate.php?q=" + login, true);
xhttp.send();
}
//PHP Validate.php
<?php
header('Access-Control-Allow-Origin: *');
include ("ConnectDB.php");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//THIS IS A TEST TO SEE IF reponseText FUNCTIONS. IT DOES NOT.
//echo "testecho";
$whole = $_REQUEST['q'];
$userPass = explode (";", $whole);
$sql1 = "SELECT UName FROM Reps WHERE UName = '$userPass[0]'";
$result = $conn->query($sql1);
if ($result->num_rows > 0) {
$conn->close();
echo "INVALID";
} else {
$sql = "INSERT INTO Reps (UName, Pass, FName, LName, Territory) VALUES ('$userPass[0]', '$userPass[1]', '$userPass[2]', '$userPass[3]', $userPass[4])";
if ($conn->query($sql) === FALSE) {
$conn->close();
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "VALID";
}
?>
I previously "commented" instead of creating an "Answer" because I wasn't suggesting a fix, just a debug step to make sure what you thought was happening, was actually happening.
Since my suggestion helped you figure out the problem, I created this "Answer" in case you want to give me "credit". :-)
I am using HTML5 Server-Sent Events.
Actually I need to show notification (new record enter and which are unread) that's when any new record is insert in database (php/mysql).
So for testing purpose I just tried with count of total row. But I am getting this error message in my local-host:
Firefox can't establish a connection to the server at http://localhost/project/folder/servevent/demo_sse.php.
The line is:
var source = new EventSource("demo_sse.php");
I have tried this:
index.php
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<div id="result"></div>
demo_sse.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$db = mysql_connect("localhost", "root", ""); // your host, user, password
if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("testdatase"); // database name
if(!$select_db) { echo mysql_error(); }
$time = " SELECT count( id ) AS ct FROM `product` ";
$result = mysql_query($time);
$resa = mysql_fetch_assoc($result);
echo $resa['ct'];
flush();
?>
Please let me know what going wrong.
I know for notification we can use Ajax with some interval time, but I don't want such thing. As I have N number of records and which may slow my resources.
According to this,
There are several 'rules' that need to be met, and yours is lacking at this point:
Output the data to send (Always start with "data: ")
It is somehow like:
echo "data: {$resa['ct']}\n\n";
Setting a header to text/event-stream worked for me:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Rest of PHP code
Please modify the following code snippet according to your requirements
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// infinite loop
while (1) {
// output the current timestamp; REPLACE WITH YOUR FUNCTIONALITY
$time = date('r');
echo "data: Server time: {$time}\n\n"; // 2 new line characters
ob_end_flush();
flush();
sleep(2); // wait for 2 seconds
}
?>
I tested this code snippet myself; it's working for me. If you have any query, let me know.