How to see errors about server sent events? - javascript

I coded a website using HTML5 Server Sent Events and it's working like charm on Godaddy shared hosting, however the same site with exactly the same code isn't working on 101domain shared hosting.
Rest all is working fine, except chat functionality using Server Sent Events.
How to find the errors in the script.
Here is the HTML page, with SSE javascript code.
<?php
$get_value_this_url = "globalchat";
?>
<div id="chat">
<div id="chats-div">
<p id="tip">(tip! kickstart a discussion by sharing this page)</p>
<ul id="chats-ul">
<?php
/*This session id will be used to fetch the latest chat via SSE*/
$_SESSION["id"] = 1;
if($stmt = $con->prepare("SELECT `icicinbbcts_id`, `icicinbbcts_user`, `icicinbbcts_chats` FROM `icicinbbcts_chats` WHERE `icicinbbcts_video_id` = ? ORDER BY `icicinbbcts_id` DESC LIMIT 25")){
$stmt->bind_param("s", $video_id);
$video_id = $get_value_this_url;
if ($stmt->execute()) {
$stmt->bind_result($id, $user, $chats);
$stmt->store_result();
if($stmt->num_rows() > 0){
$_SESSION["offset"] = $stmt->num_rows;
}
while ($stmt->fetch()) {
//print_r($user .": ". $chats."<br>");
echo '<li class="chats"><span id="nicknameChats">'.$user.'</span>: '.$chats.'</li>';
//echo '<span class="line-spacing"></span>';
$_SESSION["offset"] = $stmt->num_rows;
if($_SESSION["id"] < $id){
$_SESSION["id"] = $id;
}
}
}else
echo $stmt->error;
}else
echo $stmt->error;
$stmt->free_result();
$stmt->close();
?>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("auto_update.php?r=<?php echo $get_value_this_url; ?>");
source.onmessage = function(event) {
var obj = JSON.parse(event.data);
$("#chats-ul").append('<li class="chats"><span id="nicknameChats">'+obj.user+'</span>: '+obj.chats+'</li>');
$('#chats-ul').scrollTop($(window).height());
};
} else {
document.getElementById("chats-ul").innerHTML = "Your browser doesn't support a part of HTML5, so please use modern browsers like Chrome, Firefox, etc.";
}
</script>
</ul>
</div>
<input id="text-area" class="q" name="text-input" form="textForm" maxlength="140" placeholder="Type to comment" ></input>
</div>
And here's the server side PHP script.
<?php session_start(); ?>
<?php //error_reporting(E_ALL); ?>
<?php require "connection.php";?>
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if($stmt = $con->prepare("SELECT `icicinbbcts_id`, `icicinbbcts_user`, `icicinbbcts_chats` FROM `icicinbbcts_chats` WHERE `icicinbbcts_video_id` = ? AND `icicinbbcts_id` > ? ORDER BY `icicinbbcts_id` DESC")){
$stmt->bind_param("si", $video_id, $row_id);
$row_id = $_SESSION["id"];
$video_id = mysqli_real_escape_string($con, strip_tags($_GET["r"]));
if ($stmt->execute()) {
$stmt->bind_result($id, $user, $chats);
$stmt->store_result();
if($stmt->num_rows > 0){
while ($row = $stmt->fetch()) {
if($_SESSION["id"] < $id){
$send = array("user" => $user, "chats" => $chats);
echo "retry: 100\n";
echo "data: ".json_encode($send)."\n\n";
ob_end_flush();
flush();
$_SESSION["id"] = $id;
}
}
}
}else
echo $stmt->error;
}else
echo $stmt->error;
$stmt->close();
?>
The same above code works perfectly on Godaddy shared hosting, however the save code just isn't working on 101domain.
I tried putting charset UTF-8 in both PHP and HTML, but that din't help, I tried adding ob_flush in server side PHP script and it din't help too.
There's nothing wrong with connection.php because same file on other pages works fine.
On chat functionality the chat messages are getting inserted into the database, however it's not showing on the page, unless we refresh the page.
How to check for errors and how to debug Server Sent Events?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I did console.log and didn't find the log in chrome, when I placed console.log code at the point shown below in the code.
<script>
if(typeof(EventSource) !== "undefined") {
console.log("SSE is supported"); //placing console.log here, displays the message in chrome developer tool
var source = new EventSource("auto_update.php?r=<?php echo $get_value_this_url; ?>");
source.onmessage = function(event) {
console.log("message isn't received from server"); //placing console.log here doesn't display any log message in Chrome Developer Tool
var obj = JSON.parse(event.data);
$("#chats-ul").append('<li class="chats"><span id="nicknameChats">'+obj.user+'</span>: '+obj.chats+'</li>');
$('#chats-ul').scrollTop($(window).height());
};
} else {
document.getElementById("chats-ul").innerHTML = "Your browser doesn't support a part of HTML5, so please use modern browsers like Chrome, Firefox, etc.";
}
</script>
So from the console.log above, we see that the SSE script is not receiving messages from backend, and backend code is shown above, can you show what's wrong with the backend code?

Since the result it works with one provider but not another, it is probably a server configuration issue.
Here are some things you can try to narrow down the issue:
In the javascript script use console.log(event) to check if you are getting anything from the server
Check the network tab in the developer tools area of browsers (in Chrome choose other to view server sent events).
If there is no output then try narrowing the problem down on the server. Resolev SSE output early to see if SSE mechanism works. Bit by bit resolve the SSE later and later until it breaks. If there is a difference on a specific line between providers it may be due to the PHP version. To compare php versions run <?php phpinfo() ? in a php file.
If you find a difference contact your provider!

You want to report errors?
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>

Related

Header not working in php

I have a program that brings an image from the database and displays it inside an image div in my website. The below code was working successfully on my local wamp server but when I moved it to an online server it did not work anymore.
<?php
session_start();
include 'dbConnector.php';
$uID = $_SESSION['loggedUserID'];
$sql = "SELECT photo FROM hostmeuser WHERE userID = '$uID'";
$result = $conn->query($sql);
if(!$row = mysqli_fetch_assoc($result))
{
$imgData = "Assets/man.jpg";
}
else
{
$imgData = $row['photo'];
}
header("content-type: image/jpg");
echo $imgData;
?>
I have noticed that all (header) functions are not working on the new server and I have no control over this server so I replaced every:
header("Location: example.php")
with:
?>
<script type="text/javascript">
window.location.replace("example.php");
</script>
<?php
it is working fine now on most cases but not this one!
header("content-type: image/jpg");
Can you suggest any solution for this? or at least do you know how to represent this command in javascript?

ajax call download fails on chrome works on firefox

Hello I am using spout to run some excel reports. I have a user interface where they input date, model, and other information then I do a GET to send it to a php script where I run a query and then put all the results into an excel file like this:
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
require_once 'spout-2.7.2/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$reportDate=date("Ymd_hhmmss");
$filename="combined_report".$reportDate.".xlsx";
include ("../log/connectionToDb.php");
$conn = connectionSQL();
//provide error if connection fails
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//connected successfully to db. Do not echo anything otherwise it will not show up on dropdown.
else {
//echo "connected";
}
//From date and to date static in case not provided by user
$fromDate = $_GET['convertedFrom'];
$toDate = $_GET['convertedTo'];
$line= $_GET['selectedLine'];
$model_num=$_GET['modelNumber'];
$writer = WriterFactory::create(Type::XLSX);
ob_start();
$writer->openToBrowser($filename);
$sheet = $writer->getCurrentSheet();
$sheet->setName('Production Data');
$rowCount = 2;
$flag=false;
$production = "query";
//echo memory_get_usage() ;
$result1 = sqlsrv_query($conn, $production);
if($result1 === FALSE){
die(print_r(sqlsrv_errors(), TRUE));
}
do{
if(!$flag) {
$headerRow = ['line', 'Work order','Model number', 'Revision','Serial number','Lpn','Date created','Date completed'];
$writer->addRow($headerRow);
$flag = true;
}
else{
$reportRow = [$row['line'], $row['work_order'], $row['model_num'], $row['revision'],$row['serial_num'],$row['LPN'],$row['date_created'],$row['date_completed']];
$writer->addRow($reportRow);
$rowCount++;
}
}
while ($row = sqlsrv_fetch_array($result1));
$writer->close();
$xlsData = ob_get_contents();
ob_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
);
}
die(json_encode($response));
Then on the AJAX call I have the following:
$.ajax({
url: 'modelData/excel-export.php',
method: "GET",
data: {'modelNumber':modelNumber,'convertedFrom':converted_from_UTC,'convertedTo':converted_to_UTC,'selectedLine':selectedLine},
dataType:'json',
success: function(fileCreated){
}
}).done(function(data){
console.log(local);
var $a = $("<a>");
$a.attr("href",data.file);
$("body").append($a);
$a.attr("download","combined_report_"+local+".xlsx");
$a[0].click();
$a.remove();
});
now if I run this in Firefox everything works I am able to download up to 4 months of data which is >60,000 records this has no problem. If I run this in google chrome I cannot download more than 1 week about 20,000 records and U get a "download failed -network error" I was using PHPExcel but then found out it didn't support too many records so I switched to spout but I find the same issue only in google chrome but I don't understand where this limitation is coming from. I have read multiple posts and I have tried setting headers, lengths etc but nothing has worked also I chatted with a spout forum and they said none of the headers were necessary but they were still unable to help me.
I think this question Download failed - network error in google chrome but working in firefox may be going close to the same direction as my issue.
Also I have tried running incognito mode chrome I have tried disabling all extensions
As a side note...The firefox download appears to work fine but we don't "support" firefox so it would be hard for customers to go to multiple browsers specially when they're not tech savy
Any help will be greatly appreciated! :)
I was able to solve this issue by doing the following:
JS
window.open("modelData/excel-export.php?modelNumber="+modelNumber+"&convertedFrom="+converted_from_UTC+"&convertedTo="+converted_to_UTC+"&selectedLine="+selectedLine,
'_blank'// <- This is what makes it open in a new window.
);
then on the PHP side:
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
require_once 'spout-2.7.2/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$reportDate=date("Ymd_hhmmss");
$filename="combined_report".$reportDate.".xlsx";
include ("../log/connectionToDb.php");
$conn = connectionSQL();
//provide error if connection fails
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//connected successfully to db. Do not echo anything otherwise it will not show up on dropdown.
else {
//echo "connected";
}
//From date and to date static in case not provided by user
$fromDate = $_GET['convertedFrom'];
$toDate = $_GET['convertedTo'];
$line= $_GET['selectedLine'];
$model_num=$_GET['modelNumber'];
$writer = WriterFactory::create(Type::XLSX);
$writer->openToBrowser($filename);
$sheet = $writer->getCurrentSheet();
$sheet->setName('Production Data');
$rowCount = 2;
$flag=false;
$production = "query";
//echo memory_get_usage() ;
$result1 = sqlsrv_query($conn, $production);
if($result1 === FALSE){
die(print_r(sqlsrv_errors(), TRUE));
}
do{
if(!$flag) {
$headerRow = ['line', 'Work order','Model number', 'Revision','Serial number','Lpn','Date created','Date completed'];
$writer->addRow($headerRow);
$flag = true;
}
else{
$reportRow = [$row['line'], $row['work_order'], $row['model_num'], $row['revision'],$row['serial_num'],$row['LPN'],$row['date_created'],$row['date_completed']];
$writer->addRow($reportRow);
$rowCount++;
}
}
while ($row = sqlsrv_fetch_array($result1));
$writer->close();
The library I am using just doesn't work very well with AJAX so this approach solved my issue. Thanks for all the help :)
I used Blob Javascript for the same problem.
this link maybe help someone :
Blob

Facebook Api Friends List Not Working server

i trying get friends list from facebook using graph api and Graph secret. first i have tired Localhost its Working well.i got taotal friends of facebook. i have used Graph api and secret key.
My code Looks like
facebook.php
<?php
require '/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXX',
));
$app_id = 'xxxxxxxxxxxxxxxxxx';
$app_secret = 'xxxxxxxxxxxxxxxx';
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
$result = $facebook->api('/me/friends');
print "<pre>";
//print_r($result);
$json_output=($result['summary']['total_count']);
// echo "<h1>".'<p>Following</p>'. $json_output. "</h1>";
echo '<p>Friends</p>'. "<h1>".$json_output. "</h1>";
//echo '<div class="col-md-6 two">."<span>".$json_output."</span>""<p>FRIENDS COUNTR</p></div>';
print "</pre>";
} else {
$statusUrl = $facebook->getLoginUrl();
$loginUrl = $facebook->getLoginUrl(array('scope' => 'user_friends'));
}
?>
this code i called my index html code
my top of the page i have write Looks like
<?php
session_start();
?>
i have include facebook.php in my html page assign particular place its Looks like
<div class="col-md-6 two">
<!--
<span>36</span>
<p>Following</p>--->
<?php include("facebook.php"); ?>
</div>
this code working localhost xampp. When i move this code server side its showing that particular place blank page ?
There is probably some error on your page when running it on the server but you probably have error reporting turned off on the server. If you can turn on PHP error reporting on your server you'll probably be able to track down the problem pretty quickly.
A quick guess would be that you haven't uploaded the required file 'src/facebook.php'

Server Sent Events : Not working

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.

Javascript and PHP scan for nudity

I am trying to not allow the uploading of files that have nudity to my server. I found javascript online that will scan a photo for nudity. It comes with demo pics and an html file and js files. I am using PHP to upload the file and I am having trouble not allowing if the scan find that the pic has nudity.
Here is my code sample:
$q= "insert into $table values('', '$email', '$aim', '$icq', '$yahoo', '$homepage', '0', '0', '0', '0', '0', '0', '', now(),'$myip','$email2','$password','$title','$download','$approved','$allowdelete','$author','$facebook','$piclink','$domain','$option3','$secret')";
$result = mysql_query($q) or die("Failed: $sql - ".mysql_error());
$q = "select max(id) from $table";
$result = mysql_query($q);
$resrow = mysql_fetch_row($result);
$id = $resrow[0];
$file = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], "pics/".$id.".".$picext);
$picfile=$id.".".$picext;
echo '<script type="text/javascript" <src="nude.js">';
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
echo '</script>';
if ($nude === false) {
$q = "update $table set picfile = '".$id.".".$picext."' where id='$id'";
$result = mysql_query($q);
Header("Location: index.php?id=$id");
} else{
echo '<script type="text/javascript">';
echo 'alert("Nudity found. Please try again.")';
echo '</script>';
$q = "delete from $table where id='$id'";
$result = mysql_query($q);
unlink("pics/".$picfile);
Header("Location: new2.php");
}
The code uploads the file and then it's supposed to check the file for nudity and delete it and tell the user to try again if nudity is found. If nudity is not found the user is brought to the main page of the site.(This is the add new photo page). All of the PHP is working fine, but since the javascript doesn't seem to be running the file i uploaded and then since $nude isn't set it goes into the else of the if statement and again the js doesnt run(no alert box), and then the file is deleted. How can I make the javascript run to scan my uploaded pic for nudity? What am I doing wrong here?
Any help is greatly appreciated!
P.S.
For those that would like to see the js file that is doing the scanning: http://pastebin.com/MpG7HntQ
The problem is that this line:
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
Doesn't do what you think it does.
When you output JavaScript via echo(), that code runs on the browser or client side and doesn't run until after the PHP script has finished.
You'll either need to port the code to PHP or use an AJAX call to report the validity of the images.

Categories

Resources