Bug in alternating subtitles with jquery - javascript

I wrote a jquery script to play short videoclips with random audio fragments + subtitles attached. See here for a 'working' example. Most of the code is triggered when the video ends, and that part works well. However I have an occasional problem with the on document.ready function. It works about 7 out of 8 times, but sometimes a 404 is given for the .vtt subtitle file and the first video plays without subtitle (I checked the link and the .vtt file is actually created). (you can recreate the bug by refreshing the page a few times) I was wondering if someone has a suggestion on how to fix or debug this... Thank you!
$(document).ready(function() {
createsubtitle(); //creates random subtitle string
timestamp0 = $.now();// two timestamps to make unique files (to be deleted afterwards)
timestamp1 = $.now();
window.timestamp0 = timestamp0
window.timestamp1 = timestamp1
$.ajax({type: "POST",url:"save1.php",data: {text:subtitle, time:timestamp1},success: function() {console.log("message sent!")}}); // first .vtt file is made using php (see code below)
createsubtitle(); // new random subtitle
$.ajax({type: "POST",url:"save0.php",data: {text:subtitle, time:timestamp0},success: function() {console.log("message sent!")}}); // second php (the script alternates between two .vtt files)
$("#subtitles").attr("src", "subtitle/sub1" + timestamp1 + ".vtt"); // one .vtt file is added as src to track element #subtitles
$('#rearrangements').get(0).play(); // video is played
});
php code:
#!/usr/bin/php
<?php
$subtitle = $_POST['text'];
$timestamp = $_POST['time'];
$filename = 'subtitle/sub1'.$timestamp.'.vtt';
$myfile = fopen($filename, "w") or die("Unable to open file!");
$txt = $subtitle;
fwrite($myfile, $txt);
fclose($myfile);
?>

Related

PHP is not writing to file

I'm trying to pass a variable ( n ) from a JS script to PHP thru the URL and get it to write said variable to a file. Unfortunately I can see the PHP script being called over the network, with the appropriate URL and with 200 status, but it doesn't seem to be executing. The file it should be writing to never changes. The disk is not full, the file is not in use by another process and the file it is writing to has completely open permissions as a testing measure. Hopefully this is a simple fix, thanks in advance.
<?php
$my_file='count.txt';
$count= $_GET['n'];
$handle = fopen($my_file, 'w');
fwrite($handle, $count);
fclose($handle);
?>
Examples of requests being sent
Your code is working fine and its writing whatever value for n is passed. however it keeps on overwriting previous value for every new request.
$handle = fopen($my_file, 'w');
In 'w' mode it create new file for read and write while placing pointer at the beginning.
Use 'w+' mode this places the pointer at the end of file.
$handle = fopen($my_file, 'w+');
For more details on files you can check below url for different modes and other functions
http://php.net/manual/en/function.fopen.php

Showing off a HUGE Text file on a website

Ok, so I have a huge text file (around 2 gigabytes) and it has about 2 billion lines.
All I've tried so far is
$myfile = fopen("C:\Users\server\Desktop\primes.txt", "r") or die("Unable to
open file!");
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
but has a problem with not finishing all of the lines and hangs up somewhere in the first quarter - and it also takes a long time to load.
Second thing I've tried was this
$path="C:/Users/server/Desktop/Server files/application.windows64/";
$file="primes.txt";
//read file contents
$content="
<code>
<pre>".file_get_contents("$path/$file")."</pre>
</code>";
//display
echo $content;
But it wasn't even loading lines.
Also, I can't directly open this file and it has to be on my Desktop. Please don't suggest me to copy or move it into another directory.
Could I get any suggestions to help me get along or at least an explanation why it's not working?
Sorry, my English isn't as good as it should be.
$attachment_location = $_SERVER["DOCUMENT_ROOT"] . $file;
if (file_exists($attachment_location)) {
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public");
header("Content-Type: text/plain");
header("Content-Length:" . filesize($attachment_location));
header("Content-Disposition: attachment; filename=file.txt");
readfile($attachment_location);
die();
} else {
die("Error: File not found.");
}
It's not working because it's a 2 gig file and you're trying to output it to the screen as opposed to allowing the user to download it or open it on their personal machine. That should be the only way this file is delivered. 2 gigs output to a browser window would probably crash either or both of the client and server.
http://php.net/manual/en/function.readfile.php
If you really want to actually display the file, it would technically be possible to display a certain % of the file with a pager that when clicked will switch between different portions of the file.
http://php.net/manual/en/function.fseek.php

Issue saving file with PHP script

I'm making a PHP script for a JavaScipt site I've made.
The goal is to save the contents of a string as an HTML file when I click a button.
I'm using jQuery to make a Post request.
I'm using an Ubuntu OS with an Apache 2 server. The folder I'm writing to has permissions 777 (for testing only, will repeal this).
A requirement is the PHP must live in another file.
The issue is whenever I make the request, the file saves blank.
A requirement is each filename must be a timestamp. The file has the correct file name, but not contents.
So far, here is my code:
<?php
$fileName = $_GET['fileNameData'];
$htmlImport = $_GET['htmlToSaveData'];
$htmlToSave = (string)$htmlImport;
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
?>
I've tried the frwite function that I've commented out, same effect.
I have tested this in terminal by passing in arguments ($argv[1] and $argv[2]). That works fine.
The JS I've made to run my site looks like:
var newURL = 'saveHTML.php/?fileNameData=' + fileName + '&htmlToSaveData=' + htmlToSave
$.post(newURL)
.done(function(){
alert('Your file saved as ...' + htmlToSave)
})
I've also tried this code, with the same result:
$.post('saveHTML.php/', {
fileNameData : fileName,
htmlToSaveData : htmlToSave
})
Both the fileName and htmlToSave are strings, although htmlToSave is rather long and is actually html text that I've converted to a string.
Does anyone have ideas about what's going on here? I'm not a PHP developer at all.
I'm using a callback so I can be sure I've collected all my html before I pass the string to PHP.
I've read and tested the recommendations on this question here and this has been fruitless.
EDIT Don't be alarmed about the code, I realise it's a security issue but this is a learning project and this will not be in production.
I can see right off the bat that you have
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
file_put_contents takes a file name, not a handle. So you would only need
file_put_contents($fileName, $htmlToSave);
Edit: I also feel like I should point out that you should not allow your users to name your files. They could potentially do some nasty stuff to your machine.

Downloading files using Header with a JS input

I have a page that has a JavaScript function that uses Post to send a variable to a php file. The problem is, that I am using "header" to download the file and my JS does not open the PHP script in a new page.
When I open the php file in a new page, it does not receive the needed variable from the JS.
I know it sounds confusing, but I hope my code can shed some light on my problem.
The short version is, I am trying to download a file that is selected by a radiobutton. I use JS to check which radiobutton is checked and then send that to my php file. Which then needs to download the file.
Thank you all in advance.
PHP:
<?php
if (isset($_POST['routenumber'])) {
if(!isset($_SESSION)){session_start();}
$routenumber = (isset($_POST['routenumber']) ? $_POST['routenumber'] : null);
$directory = ("Users/".$_SESSION['id']."/SavedRoutes/");
$routes = scandir($directory);
sort($routes);
$route = $routes[$routenumber];
$file =("Users/".$_SESSION['id']."/SavedRoutes/".$route);
header("Content-type: application/gpx+xml");
// header("Content-Disposition: attachment;Filename=".json_encode($route).".gpx");
header("Content-Disposition: attachment;Filename=route.gpx");
readfile($file);
}
?>
JS:
function fuAccountDownloadRoute(){
var i=2;
var SelectedRadio
while (i < routecounter){
var str1='radio';
var str2=JSON.stringify(i);
var result = str1.concat(str2);
if (document.getElementById(result).checked){
SelectedRadio = result.slice(5);
}
i=i+1;
}
$.post('accountPage.php',{routenumber:SelectedRadio});
}
When you open the url: http://localhost/accountPage.php in your browser it makes a GET request. You should change all the $_POST to $_GET in your code if you want to make it possible, and then you can open it like this: http://localhost/accountPage.php?routenumber=3, though it's probably not what you really want.

Function to look through folder and use a wildcard

been a lurker on Stack Overflow for a while, love the site.
Now its my turn. From the code below, i am making the background image random each time the page loads.
Would anyone be so kind as to help me make this more efficient so that i don't have to manually enter my filenames ? Im looking for some kind of wildcard function that can look through my given folder and load footer*.png or even *.png as this folder will only contain footer patterns.
var images = ['footer.png', 'footer2.png', 'footer3.png'];
$('#footer').css({'background-image': 'url(images/footers/' + images[Math.floor(Math.random() * images.length)] + ')'});
With PHP, you can do it:
<?php
$directory = "./images/";
$images = glob($directory . "*.png");
foreach($images as $image)
{
echo $image . "\n";
}
?>
Just don't make $directory an arbitrary argument, as the Russian hackers will jack your webapp.
To use it, make an AJAX request to the PHP file and parse the output, separating each file by the \n character.
So with jQuery,
var images = [];
jQuery.load('images.php', function(data)
{
images = data.split('\n');
});

Categories