Providing php generated xml file to javascript parser - javascript

I am developing a smart tv app that plays live streams. App itself works fine, when i provide a valid xml playlist to it.
But when i use php to generate xml file (wich also generates fine), it doesnt work.
I get an error:
TypeError: 'null' is not an object (evaluating 'this.XHRObj.responseXML.documentElement')
Here is my php file that generates videoList.xml, it works 100%.
In short words, this script checks if MAC address in database, and if it is, then it writes videoList.xml with walid live streaming links.
SamsungAPI.php
<?php
$MAC = $_GET['MAC'];
require_once('../config.php');
//Remove brackets form array
$_INFO = preg_replace('/[{}]/', '', $_INFO);
$mysqli = new mysqli($_INFO['host'], $_INFO['db_user'], $_INFO['db_pass'], $_INFO['db_name']);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="SELECT * FROM users WHERE admin_notes = '$MAC' ";
$rs=$mysqli->query($sql);
$rows=mysqli_num_rows($rs);
if ($rows == 1) {
//MAC FOUND
$row = mysqli_fetch_array($rs);
$username = $row['username'];
$password = $row['password'];
$file = "videoList.xml";
$txt_file = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . '/get.php?type=starlivev3&username=' . $username . '&password=' . $password . '&output=hls');
$rows = explode("\n", $txt_file);
if(empty($rows[count($rows)-1])) {
unset($rows[count($rows)-1]);
$rows=array_map('trim',$rows);
}
$handle = fopen($file, "w+") or die('Could not open file');
fwrite($handle, "<?xml version=\"1.0\"?>"."\n");
fwrite($handle, "<rss version=\"2.0\">"."\n");
fwrite($handle, "<channel>"."\n");
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(',', $data);
//replace _ with spaces
$row_data[0] = str_replace('_', ' ', $row_data[0]);
//generate playlist content
fwrite($handle, "<item>"."\n");
fwrite($handle, "<title>{$row_data[0]}</title>"."\n");
fwrite($handle, "<link>{$row_data[1]}</link>"."\n");
fwrite($handle, "<description> Reserved for EPG </description>"."\n");
fwrite($handle, "</item>"."\n");
}
fwrite($handle, "</channel>"."\n");
fwrite($handle, "</rss>");
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
//MAC NOT FOUND
echo "MAC NOT FOUND";
}
mysqli_close($mysqli); // Closing Connection
?>
Then in samsung smart tv videoplayer app, i have xml parser like this:
Server.js
var Server =
{
/* Callback function to be set by client */
dataReceivedCallback : null,
XHRObj : null,
url : "http://myvalidhost.com/samsungAPI.php?MAC=02000027000b"
}
Server.init = function()
{
var success = true;
if (this.XHRObj)
{
this.XHRObj.destroy(); // Save memory
this.XHRObj = null;
}
return success;
}
Server.fetchVideoList = function()
{
if (this.XHRObj == null)
{
this.XHRObj = new XMLHttpRequest();
}
if (this.XHRObj)
{
this.XHRObj.onreadystatechange = function()
{
if (Server.XHRObj.readyState == 4)
{
Server.createVideoList();
}
}
this.XHRObj.open("GET", this.url, true);
this.XHRObj.send(null);
}
else
{
alert("Failed to create XHR");
}
}
Server.createVideoList = function()
{
if (this.XHRObj.status != 200)
{
Display.status("XML Server Error " + this.XHRObj.status);
}
else
{
var xmlElement = this.XHRObj.responseXML.documentElement;
if (!xmlElement)
{
alert("Failed to get valid XML");
}
else
{
// Parse RSS
// Get all "item" elements
var items = xmlElement.getElementsByTagName("item");
var videoNames = [ ];
var videoURLs = [ ];
var videoDescriptions = [ ];
for (var index = 0; index < items.length; index++)
{
var titleElement = items[index].getElementsByTagName("title")[0];
var descriptionElement = items[index].getElementsByTagName("description")[0];
var linkElement = items[index].getElementsByTagName("link")[0];
if (titleElement && descriptionElement && linkElement)
{
videoNames[index] = titleElement.firstChild.data;
if(linkElement.firstChild.data.substring(0,4) !="http"){
alert("asdasdasd "+linkElement.firstChild.data.substring(0,4));
var rootPath = window.location.href.substring(0, location.href.lastIndexOf("/")+1);
var Abs_path = unescape(rootPath).split("file://")[1]+linkElement.firstChild.data;
videoURLs[index] = Abs_path;
}
else{
videoURLs[index] = linkElement.firstChild.data;
}
videoDescriptions[index] = descriptionElement.firstChild.data;
}
}
Data.setVideoNames(videoNames);
Data.setVideoURLs(videoURLs);
Data.setVideoDescriptions(videoDescriptions);
if (this.dataReceivedCallback)
{
this.dataReceivedCallback(); /* Notify all data is received and stored */
}
}
}
}
Does anyone have any idea why doesnt it accept my generated xml file?
Regards
M

I figured it out, in php headers content type was wrong.
Changed
header('Content-Type: application/octet-stream');
to
header('Content-Type: application/xml');
Now it works perfect!

Related

Javascript PHP chunk video and save into Database

window.addEventListener("load", () => {
var uploader = new plupload.Uploader({
runtimes: "html5",
browse_button: "upload",
url: "../upload.php",
chunk_size: "10mb", // <<<<<<< Here is my problem
filters: {
max_file_size: "100gb",
.... THIS CODE HERE DOESN'T MATTER .....
});
This is my upload.php
function verbose ($ok=1, $info="") {
if ($ok==0) { http_response_code(400); }
exit(json_encode(["ok"=>$ok, "info"=>$info]));
}
if (empty($_FILES) || $_FILES["file"]["error"]) {
verbose(0, "Failed to move uploaded file.");
}
$filePath = __DIR__ . DIRECTORY_SEPARATOR . "videos";
if (!file_exists($filePath)) { if (!mkdir($filePath, 0777, true)) {
verbose(0, "Failed to create $filePath");
}}
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
$dateformat = date("Y-m-d-H:i:s");
$fileSize = $_FILES["file"]["size"]; // <<<<< HERE IS MY PROBLEM
$title = pathinfo($fileName,PATHINFO_FILENAME);
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$out = #fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
$in = #fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
}else{
echo "err";
}
#fclose($in);
#fclose($out);
#unlink($_FILES['file']['tmp_name']);
}else{
verbose(0, "Failed to open output stream");
}
if (!$chunks || $chunk == $chunks - 1) {
$rename = 'videos/'.generateKey($pdo); // simple function to generate random string ( 123asdjjn124 and so on)
$databaseName = str_replace('videos/','', $rename); // remove videos/ from the string
rename("{$filePath}.part", $rename);
$stmt = $pdo->prepare("INSERT INTO videos(title,size,date,link) VALUES(:title,:size,:date,:link)");
$stmt->bindParam(':title',$title,PDO::PARAM_STR);
$stmt->bindParam(':size',$fileSize,PDO::PARAM_STR); // <<<<< HERE IS MY PROBLEM
$stmt->bindParam(':date',$dateformat,PDO::PARAM_STR);
$stmt->bindParam(':link',$databaseName,PDO::PARAM_STR);
$stmt->execute();
}
verbose(1, "Upload OK");
Now when I upload a file, everything is entered beautifully but the size of the "chunk_size" is always entered instead of the correct size of the file. Does anyone have an idea why this is so? It also makes no difference if I change the file size, it always takes the "chunk_size".
Any advice is helpful
Here I have another screenshot to illustrate how I mean it. https://prnt.sc/QW-zXtrb6RuY

show amount of Instagram followers on website

It seems like Instagram has changed certain things, because I have tried several codes on my html website to show the amount of Instagram followers on a button, but nothing works.
I tried this:
<?php
$account='XXX';
$instagramsource=file_get_contents('https://instagram.com/' . $account);
preg_match_all('/"userInteractionCount":"(.*?)"/', $instagramsource, $count);
$followcount=$count[1][0];
echo "$account instagram account has $followcount followers";
?>
Also this
<?php
$otherPage = 'XXX';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
if ($data !== null) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo $follows . ' and ' . $followedBy;
}
}
?>
And this ...
<?php
$url = "https://www.instagram.com/XXX";
$json = file_get_contents($url);
$obj = json_decode($json, true);
$content = $obj['query']['results']['script']['content'];
$content = str_replace("window._sharedData =", "", $content);
$content = str_replace(";", "", $content);
$content = trim($content);
$json = json_decode($content);
$instagram_follower_count = $json->entry_data->ProfilePage{0}->user->followed_by->count;
?>
And finally this:
<?php
$username = 'XXX';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo 'XXX follows:' . $follows . ' and is followed by: ' . $followedBy;
}
}
?>
None works.
Can anyone indicate what would work in 2021, please?
Thanks.
It's because the url https://www.instagram.com/$username/?__a=1 is redirecting to login page & giving u a html response
You can check it by echo $response
These posts will help you link1,link2
Instagram blocked access via __a=1 parameter since 2018-04-12. __a=1 must be replaced by JS and Ajax bypass. I've looked for an alternative solution. You can use javascript code inside php. For example:
async function instagramFollowers () {
const followers = []
try {
const userInfoSource = await Axios.get('https://www.instagram.com/123/')
const jsonObject = userInfoSource.data.match(/<script type="text\/javascript">window\._sharedData = (.*)<\/script>/)[1].slice(0, -1)
const userInfo = JSON.parse(jsonObject)
const mediaArray = userInfo.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges.splice(0, 10)
for (let media of mediaArray) {
const node = media.node
followers.push(node.thumbnail_src)
}
} catch (e) {
console.error('Unable to retrieve Followers. Reason: ' + e.toString())
}
return followers
}
Other helpful links: how to write javascript code inside php
https://code.tutsplus.com/tutorials/how-to-use-ajax-in-php-and-jquery--cms-32494

AJAX not outputting correct thing

So I'm trying to call a php method from javascript so I can query a database and get the results into my js functionality. Currently, the 'console.log(output)' that is in my ajax is just outputting:
"array (size=1)
'action' => string 'getResults' (length=10)'"
Not really sure why it's doing this, it should be returning the query result which is just one entry from the database. Anyone have any idea? Any help is welcome! Thanks.
Part of my Javascript file:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
//alert(output);
}
//error, function(err){console.log(err)}
});
}
callPHP();
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
echo var_dump($_GET);
/*
$handle = fopen("php://input", "rb");
$param = '';
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
*/
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
//echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
Conn.php - this is all the connection info, * out for confidential reasons:*
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "***";
}
?>
MySQLDao.php - this file holds the querys:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
echo json_encode($result);
echo($result);
}
}
?>
I think you misunderstand how to ship data between javscript and php.
Your javascript should be posting with $.post() if you want to send an object or array of data.
Your php will recieve json from the javascript. You need to use php's json_decode function on it to make it useful to php.
If you want the output of your php script to be useful to javascript, you need to encode it with php's json_encode function before returning it to the calling script.
http://php.net/manual/en/function.json-decode.php
The output is for echo var_dump($_GET); I'm sure. I can tell because of the output format is a var_dump type. and the success part of your code does not have any output. I mean in this part else { //Decodes data, dont change ... the output has been commented out.
I noticed that you are using MySqli but some methods are MySql api like this part of the code
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
I assume this code is not complete and in debugging phase as I can see many incomplete methods and function calls.
Also try to use prepared statements with place holders for security.
It is a good practice to use ob_clean() before API output as any extra character will destroy the output data and format. However, you will not see errors. There are useful tools for API testing like Browsers Rest Client extensions. The best way for debugging is always debugging tools and frameworks like x-debug.
Do following changes to your code. Hope this helps!
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
// echo var_dump($_GET);
/*
$handle = fopen("php://input", "rb");
$param = '';
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
*/
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
ob_clean();
echo json_encode($returnValue);
exit();
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
//Clean up before output
ob_clean();
echo json_encode($returnValue);
exit();
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
//Close connection as fast as possible
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode($result);
exit();
}
}
?>
MySQLDao.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = ?";
$stsm = $this->mysqli->prepare($sql);
$stsm->bind_param('i',1);
$result = $stmt->execute();
if (mysqli_num_rows($result) == 1) {
$obj = mysqli_fetch_object($result, 'obResults');
return $obj;
}
return false;
}
}
?>

Call data back from AJAX

I have a script which saves canvas PNGs to a directory and I need the URL to save on the server.
When I submit, the image saves but the server remains empty. I am trying to return error messages but I am receiving nothing.
JAVASCRIPT:
function doodleSave() {
var drawing = document.getElementById("doodle-canvas");
var drawingString = drawing.toDataURL("image/png");
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST", 'http://www.website.com/php/doodleSave.php', true);
ajax.onreadystatechange= function() {
if (ajax.readyState === 4) //If it ran smoothly
{$("#doodle-submit-button").html("...");}
};
ajax.send(postData);
ajax.success(function(data) {
{$("#doodle-submit-button").html(""+data+"");}
});
}
PHP:
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$rawImage = $GLOBALS['HTTP_RAW_POST_DATA'];
$removeHeaders = substr($rawImage, strpos($rawImage, ",")+1);
$url = md5(uniqid(rand(), true));
$decode = base64_decode($removeHeaders);
$fopen = fopen('../images/external/doodles/'.$url.'.png', 'wb');
fwrite($fopen, $decode);
fclose($fopen);
//ADD POST TO DATABASE WITH USER'S ID
/* AUTOMATED VARIABLES */
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = 'images/external/doodles/'.$url;
try
{
$stmt = $pdo->prepare("INSERT INTO `(table name)` (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUES(:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$profile_unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "uploaded";
}
else
{
echo "Could not upload";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>

Using PHP to retrieve a PDF (with JSON)

I'm using JS and PHP to collect a rows of information from a MySQL DB. This is working fine until I'm adding code to get a PDF-blob in the same return.
var docs;
getMini = function() {
showMiniLoading();
var req = new XMLHttpRequest();
req.onload = function() {
console.log("GOT IT!");
var temp = JSON.parse(this.responseText);
docs = temp;
hideMiniLoading();
printAllMini();
};
req.open("get", "resources/php/newMini.php", true);
req.send();
console.log("SENT!");
}
showPDF = function(id) {
for (var i = 0; i < docs.length; i++) {
var object = docs[i];
if (object.id == id) {
console.log("Found it! :D " + i);
console.log("Content: " + object.pdf);
// MORE STUFF HERE
document.getElementById("pdf").innerHTML = '<object "data:application/pdf,' + object.pdf + '" type="application/pdf" width="100%" height="100%"> <p>Alternative text - include a link to the PDF!</p> </object>';
break;
}
}
}
<?php
session_start();
include_once 'maindb.php';
$mysqli = mysqli_connect($dbMain['host'], $dbMain['user'], $dbMain['pass'],
$dbMain['db'])
or die('Kunde inte ansluta till databasen:'.mysqli_error($Maincon));
if(!$result = $mysqli->query(
"SELECT tblDokument.ID, tblMail.inkommet,
tblDokument.datum, tblDokument.Moms, tblDokument.pris, tblDokument.Org,
tblVerifikat.verifikatNo, tblLevMallar.OrgNr, tblLevMallar.name,
tblDokumentSvg.svg, tblDokumentPdf.pdf
FROM tblDokument
LEFT OUTER JOIN tblVerifikat ON tblDokument.ID = tblVerifikat.ID
LEFT OUTER JOIN tblMail ON tblDokument.tblMail_ID = tblMail.ID
LEFT OUTER JOIN tblLevMallar ON tblDokument.orgnr = tblLevMallar.OrgNr
LEFT OUTER JOIN tblDokumentSvg ON tblDokument.ID = tblDokumentSvg.dokumentid
LEFT OUTER JOIN tblDokumentPdf ON tblDokument.ID = tblDokumentPdf.id
WHERE tblVerifikat.verifikatNo <> 'Makulerad'
ORDER BY tblDokument.ID"))
{
echo "VERYTHING IS BAD";
}
else {
$i = 0;
while ($row = $result->fetch_assoc()) {
$tempPDF = $row["pdf"];
$size = filesize($tempPDF);
header('Content-type: application/pdf');
header("Content-length: $size");
header('Content-Disposition: attachment; filename="new.pdf")');
$tempArray[$i] = array(
"id" => $row["ID"],
"arrived" => substr($row["inkommet"], 0, 10),
"booked" => $row["datum"],
"verification" => $row["verifikatNo"],
"org" => $row["name"],
"price" => $row["pris"],
"stax" => $row["Moms"],
"pic" => base64_encode($row["svg"]),
"pdf" => $tempPDF);
$i++;
}
// HEADER STUFF
$done = json_encode($tempArray);
$size = strlen($done);
header('Content-type: application/json');
header("Content-length: $size");
header('Connection: close');
echo $done;
}
$result->close();
$mysqli->close();
?>
I encode the result with JSON at the end, but whatever I do I end up with a column full of null-values, instead of the desired PDF-blob. I've also tried to encode the entire pdf with base64_encode(), but then I get an error that says:
Uncaught SyntaxError: Unexpected token <
.. in the console of my browser.
Actual question:
How do i send a PDF-blob together with some other information and encoded in JSON?
I've tried a lot of other threads but haven't seen a solution that works in this case :/
NOTE:
I am very now to PHP and any additional feedback about the efficiency of the code above is highly appreciated.

Categories

Resources