HTML5 - Server side events - Using external text file as data input - html

I am attempting of using a plain text-file (text.txt) as part of html5 - server side events.
Currently I am not seeing any printout of text in browser. If just running this line, without using an external file for input data, it works:
echo "data: test\n\n";
Question: What do I need to adjust to make the external file data to be visible in the browser, assuming the setup of below files?
My html file
<h1>SSE</h1>
<div id="result"></div>
<script>
// Create an object
var source = new EventSource("updater.php");
// Detect message receipt
source.onmessage = function(event) {
// Write the received data to the page
document.getElementById("result").innerHTML += event.data + "<br>";
};
</script>
my php file
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Include files
echo include("text.txt");
flush();
?>
my text file:
"data: t1972\n\n";

The solution for the question, works if using [file_get_contents] as specified below.
$data = file_get_contents('text.txt');
echo "data: " . $data . "\n\n";
This also means that the file [text.txt] is left with only text, removing the [data: ] and [\n\n].

Related

PHP Phantomjs: How to handle Page Transition? (Web Scraping)

Everyone.
This question maybe duplicated with Using PhantomJs, how to get and handle the new page?.
But there was not exact answer.
My question is as follows.
The pages what I want to scrape 3 pages.
1st Page : input unique id , click next.
if valid id => go to 2nd page.
2nd Page : click link(contains id)
3rd Page : download Pdf File.
So my aim is to download pdf file from unique id automatically.
Then the main point is how to handle page transition in Phantom PHP?
My test Code is as:
// Use the composer autoloader.
require_once 'vendor/autoload.php';
// Setup mink drivers.
$goutteDriver = new \Behat\Mink\Driver\GoutteDriver();
$phantomjsDriver = new \Behat\Mink\Driver\Selenium2Driver('phantomJS');
// Setup mink sessions.
$goutteSession = new \Behat\Mink\Session($goutteDriver);
$phantomjsSession = new \Behat\Mink\Session($phantomjsDriver);
// Setup mink session manager.
$mink = new \Behat\Mink\Mink();
// Register sessions.
$mink->registerSession('goutte', $goutteSession);
$mink->registerSession('phantomjs', $phantomjsSession);
// Set Goutte as the default session.
$mink->setDefaultSessionName('phantomjs');
// Visit mink website with phantomjs driver.
$mink->getSession('phantomjs')->visit('https://testurl.com');
// Get the default goutte session.
$session = $mink->getSession('phantomjs');
// Get the page document.
$page = $session->getPage();
echo $session->getCurrentUrl(), PHP_EOL;
// $page->find('css', '#guides')->clickLink("Drivers");
// echo $session->getCurrentUrl(), PHP_EOL;
// Output the installation instructions from the page.
$input = $page->find('css', '#id');
$input->setValue("1234567890");
echo $input->getValue(), PHP_EOL;
$page->find('css', '#validar')->Click();
echo $page->find('css', '#validar')->getValue(), PHP_EOL;
$session->executeScript('document.getElementById("validar").click()');
//$session->reload();
sleep(5);
// $mink->getSession('phantomjs')->visit('https://testurl.com/next');
$page = $session->getPage();
echo $session->getCurrentUrl(), PHP_EOL;
sleep(5);
$mink->getSession('phantomjs')->visit('https://testurl.com/next2?id=1234567890');
$page = $session->getPage();
echo $session->getCurrentUrl(), PHP_EOL;
// Stop browser sessions.
$mink->stopSessions();
So
How to handle page transition?
How to download pdf file properly?

html5 - Server side events: Replace line instead of append

I am aiming at using HTML5 SSE (Server Side Events) to send updates of data from server to the client. Currently the time is appended as an extra line. I am using the [\n\n] in the php-file in order to stop the stream.
Question: How can I replace the complete line insted of having it appended? I want the replacement to be in the same place, thus be kept inside the div [result].
I have tried to remove the br-tag at line 17 of the html-file, but it did not remove the "newline".
My html5 file, with js included:
<h1>SSE test</h1>
<div id="result"></div>
<script>
// Create an object
var source = new EventSource("updater.php");
// Detect message receipt
source.onmessage = function(event) {
// Write the received data to the page
document.getElementById("result").innerHTML += event.data + "<br>";
};
</script>
my php file:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// The server time
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
In your source.onmessage callback, just change the line to this:
document.getElementById("result").innerHTML = event.data + "<br>";
The problem is caused by the += operator, which appends the new result to the previous one. Now, with = it overwrites the old result, thereby solving the problem.

How can I embed external content in a WordPress widget?

I want to display a download link inside a WordPress widget. The file to be downloaded is located in the download subfolder of the site root, so that it can be uploaded via FTP. The name of the file and the text to be displayed for the download link shall be stored in a simple text file in the same folder.
Assuming WordPress is installed on www.mysite.com. The file name is setup_1_0.zip and the link display is Setup 1.0.
I am open to the file format how this information is stored as long as I can upload that file via FTP, too.
How can I embed this information inside a Custom HTML widget to get a valid download link with the text taken from that file?
How to automate the process of uploading latest software's build and download link creation in WordPress?
Based on your logic.
You are trying to automate the download process of your latest software version.
You don't want to update things manually and you just want to upload your latest build in the /download/ folder. (Only drop your latest version using FTP; that's all)
This is how I would do it:
Referencing those questions:
Get the latest file addition in a directory
How to force file download with PHP
I propose two solutions: First two separte codes, Second One inline code.
Just for educational purpose
First solution: Quick and short usage:
(You might need a way or a plugin to activate running PHP in Widget; this plugin helps PHP Code Widget)
<?php
$path = "download/";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
echo 'Download '. $latest_filename . '';
?>
Second solution:
(Again, you might need a way or a plugin to activate running PHP in Widget; this plugin helps PHP Code Widget)
A) Create download.php in http://www.example.com/download.php
Add the following code:
<?php
$path = "download";
$latest_ctime = 0; //ctime stands for creation time.
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
// echo $latest_filename; un-comment to debug
$file_url = 'http://www.example.com/download/'.$latest_filename;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url); // do the double-download-dance (dirty but worky)
?>
B) in your WordPress HTML Widget add the following code
<?php
$path = "download";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
echo 'Download '. $latest_filename . '';
?>
Further explanation:
A) is responsiple for downloading the latest software build automatically.
B) is responsiple for displaying Latest build name and Creating the link.
Now, You only need to upload one file to your /download/ folder which is your latest build (setup_1_0.zip, setup_1_1.zip, setup_1_2.zip ...etc. The proposed solution will check creation date regardless of file's name.)
Important note: You can see that the latest file checker function is repeated twice; once in download.php and once in WordPress Widget. Because if we combine in one file we will get header already sent error.
Dose this answer your question please? Kindly feedback.

AS3 ALIVEPDF saving via method.remote (PHP) no longer working

The SWF is located on a web server. I am calling the function using this code in AS3...
myPDF.save(Method.REMOTE, "http://www.example.com/generator/createpdf.php",
Download.ATTACHMENT, "line.pdf");
Here is my PHP script located on the server...
$method = $_GET['method'];
$name = $_GET['name'];
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
// get bytearray
$pdf = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($pdf));
header('Content-disposition:'.$method.'; filename="'.$name.'"');
echo $pdf;
} else echo 'An error occured.';
It used to work, but stopped a while back. Any help would be greatly appreciated.
1) This stopped working for me as well, until I added the following -
if(!$HTTP_RAW_POST_DATA){
$HTTP_RAW_POST_DATA = file_get_contents(‘php://input’);
}
2) I also patched /src/org/alivepdf/pdf/PDF.as::save() per this post enter link description here

PHP code within Javascript - how to transfer variable

in my webpage, I have the following code:
<?php
echo "<td class=\"action\">
?>
<script>
function deleteline(a) {
var r=window.confirm("Voulez-vous vraiment supprimer le viager " + a +"?");
if (r)
{
<?php
$test="<script> document.write(a);</script>";
mysql_connect("localhost", "xxxxxx", "xxxxxx") or die (mysql_error ());
mysql_select_db("xxxxxx") or die(mysql_error());
$strSQL =("update viagers set statut='deleted' where id=????");
$rs = mysql_query($strSQL);
mysql_close();
?>;
}
}
</script>
In a php table, i have an small delete icon in each row. I want the user to be able to click on it so it deletes the record in the sql db. I can't find a way to retrieve the 'a' variable in the php code of my script function (replace by ????).
Could you please help?
thanks and regards
Harold
You can't mix javascript and PHP like that. Make another PHP file for deletion, and send the a by javascript to the file through AJAX.
PHP code inside javascript is not a good approach. As lqbal Fauzi mentioned, send a variable - row id by javascript to the php file through AJAX - or as I do below, by using JQUERY. In php file, you can do your database stuff and if wanted, send some result back to your application.
In your HTML file you have to have scripts with JQUERY library source files.. Download these 2 files from here:
https://mega.co.nz/#!IUAFCYZb!Cu0mQoAVAkJHzqvac40-RYA-n3TnhYGtoazw5k_PMv4
https://mega.co.nz/#!hABhFDiS!Q_L8rERVq8330zrOxXXen0uxmLCes7zYG6J6SCncz6M
and save/copy those files into the folder containing your html file.
Your html file should look something like this:
<html>
<head>
<meta charset="utf-8" />
<title>Your page Title</title>
<script src="jquery.mobile-1.3.2.min.js"></script>
<script src="jquery-1.9.1.min.js"></script>
<script>
function yourJavascriptfunction(sender){
var r=window.confirm("Voulez-vous vraiment supprimer le viager " + sender.name +"?");
if (r)
{
$.post("YourPHPPageToAccessDatabaseAndSendResult.php", {
UserID:sender.name
})
.success(function(data){
//some code on data return if you want
alert(data); //should pop up with message saying "Hello, this is the result data"
})
.fail(function(error){
alert("Unable to retrieve data from the server");
});
}
}
</script>
</head>
<body>
<button type="button" name="YourRowID" onclick="yourJavascriptfunction(this)" > your button text</button>
</body>
</html>
and in the php file named YourPHPPageToAccessDatabaseAndSendResult.php which has to be in this case in the same directory as your html file following code:
<?php
$connection = mysql_connect("localhost","USER","YOURPASSWORD") or die(mysql_error());
mysql_select_db("DatabaseName",$connection);
$UserID= $_POST['UserID'];
$strSQL =("update viagers set statut='deleted' where id=$UserID");
$rs = mysql_query($strSQL);
mysql_close();
//by printing with echo you sent some data that you want return to your html file
echo "Hello, this is the result data";
?>
The above code is not tested for functionality, there might be some typos, but the logic in there should work and help you in the future
Don't forget to substitute the YourRowID in button name in html file to whatever you need, and set correct USER, YOURPASSWORD and DatabaseName in the php file.