i'm trying to find a way to print pdf's which are downloaded from our php-based website.
currently we have to point every printer ourselves ( small labelprinter-large labelprinter-laserjet) , but we would like a workflow like this:
on the website you click the small label icon.
a pdf is generated with the label and gets a filename with .pdf stored on the fileserver in the users folder.
based the prefix and suffix of the file a monitoring program monitoring the folders sends a command to print to the printer specified in the file.
Basically i'm aiming for a kiosk printing mode, with a functionality for every user to specify which printer is nearby and should be used .
Is this a functionality which is easily acheived?
Doing this in PHP is quite hard, It would be easier to use Python
For windows
You have to make a python script which scans every 10 seconds (or less) a folder where you put all files to print.
while True:
files_in_dir = os.listdir(os.path.join('path to the scanned folder'))
time.sleep(10) # sleep 10 seconds before the new scan
Then, you can use gsprint to send the file to the printer
p = subprocess.Popen(
['path_to_gsprint.exe', '-printer', 'printer_name', 'fullpath_file'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
if out:
print Tools.format_txt(out)
if err:
print Tools.format_txt(err, level="error")
Once the file is printed, delete it or move it to an other folder so it will not be scanned again.
os.rename(filename, 'path to printed folder' + filename) # move file
os.remove(filename) # delete file
For linux
On linux, the script is quite similar, using Python, you scan a folder and you sent the found files to the printer using lp command
lp -d PRINTER_NAME *.pdf
Again, once the files are printed, delete or move them.
With this technique, you will not get instant print, you will have to wait for the script to scan the folder but if you set a short time between scans, this won't be a problem
Related
I am working on a project for school. I am wondering if there is a way in PHP to listen for print jobs and store them once received? I currently have a webserver that is accepting webhooks from other applications, parsing out the JSON and storing in a MsSQL. Is this the wrong path to take? thanks
Ok – I don’t know if this is a solution but here is my attempt at trying to help :)
Disclaimer: I am not affiliated to any of the links posted here and (or) make no recommendations.
General assumptions:
PHP is the server side language used in all instances (the theory should work with others as well – using PHP as the question was tagged as such)
Sender and receiver servers are different (it is more easier if both are on the same box – but not a show stopper)
Access to both sender and receiver webservers
Windows set up (WAMP or alternative)
You are securing your set up / directory accesses as you go along
Option 1 (Custom sender / receiver)
On the box that is sending the print request:
Create a PHP script to output the files to a temp directory
Create file with required extension (please see documentation if required)
Put contents
Close connection / file - https://www.php.net/manual/en/function.file-put-contents.php
Use powershell or alternative to put the files in the temp directory into a remote directory on the
https://blogs.msdn.microsoft.com/luisdem/2016/08/31/powershell-how-to-copy-a-local-file-to-remote-machines/
Run this at an interval of your choice
On the box that is receiving the file:
Create a PHP script to read files on remote
Show files to print in a list which can be downloaded to local terminal / device and printed
Option 2 (Leverage an existing print server)
In this option you would only need to amend the sender webserver config:
[inspired by: https://www.hashbangcode.com/article/printing-directly-php]
Download php_printer.dll for your version (https://windows.php.net/downloads/pecl/snaps/printer/0.1.0-dev/)
Enable in php.ini via: printer.default_printer=PHP_INI_ALL extension=php_printer.dll
Set the printer as your print server address and send your output to print directly from the Webserver as follows from your application:
`
$data= "Hello";
printer_set_option($ph, PRINTER_MODE, "RAW");
printer_write($ph, $data);
printer_close($ph);
}
else "Couldn't connect...";
?>'
Option 3 (Use a plugin):
https://www.neodynamic.com/products/printing/raw-data/php/
I'm attempting to find a way to sanitize/filter file names in a Bash script the exact same way as the sanitize_file_name function from WordPress works. It has to take a filename string and spit out a clean version that is identical to that function.
You can see the function here.
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Ubuntu 14.04.5 LTS (GNU/Linux 3.13.0-57-generic x86_64)
This is perl 5, version 18, subversion 2 (v5.18.2) built for x86_64-linux-gnu-thread-multi
Example input file names
These can be and often are practically anything you can make a filename on any operating system, especially Mac and Windows.
This File + Name.mov
Some, Other - File & Name.mov
ANOTHER FILE 2 NAME vs2_.m4v
some & file-name Alpha.m4v
Some Strange & File ++ Name__.mp4
This is a - Weird -# Filename!.mp4
Example output file names
These are how the WordPress sanitize_file_name function makes the examples above.
This-File-Name.mov
Some-Other-File-Name.mov
ANOTHER-FILE-2-NAME-vs2_.m4v
some-file-name-Alpha.m4v
Some-Strange-File-Name__.mp4
This-is-a-Weird-#-Filename.mp4
It doesn't just have to solve these cases, it has perform the same functions that the sanitize_file_name function does or it will produce duplicate files and they won't be updated on the site.
Some thoughts I've had are maybe I can somehow use that function itself but this video encoding server doesn't have PHP on it since it's quite a tiny server and normally just encodes videos and uploads them. It doesn't have much memory, CPU power or disk space, it's a DigitalOcean 512MB RAM server. Maybe I can somehow create a remote PHP script on the web server to handle it through HTTP but again I'm not entirely sure how to do that either through Bash.
It's too complicated for my limited Bash skills so I'm wondering if anyone can help or knows where a script is that does this already. I couldn't find one. All I could find are scripts that change spaces or special characters into underscores or dashes. But this isn't all the sanitize_file_name function does.
In case you are curious, the filenames have to be compatible with this WordPress function because of the way this website is setup to handle videos. It allows people to upload videos through WordPress that are then sent to a separate video server for encoding and then sent to Amazon S3 and CloudFront for serving on the site. However it also allows adding videos through Dropbox using the External Media plugin (which actually is duplicating the video upload with the Dropbox sync now but that's another minor issue). This video server is also syncing to a Dropbox account and whitelisting the folders in it and has this Bash script watching a VideoServer Dropbox folder using inotifywait which copies videos from it to another folder temporarily where the video encoder encodes them. This way when they update the videos in their Dropbox it will automatically re-encode and update the video shown on the site. They could just upload the files through WordPress but they don't seem to want to or don't know how to do that for some reason.
If you have Perl installed, try with:
#!/bin/bash
function sanitize_file_name {
echo -n $1 | perl -pe 's/[\?\[\]\/\\=<>:;,''"&\$#*()|~`!{}%+]//g;' -pe 's/[\r\n\t -]+/-/g;'
}
filename="Wh00t? it's a -- re#lly-weird {file&name} (with + Plus and__1% #of# [\$qRots\$!]).mov"
cleaned=$(sanitize_file_name "$filename")
echo original : "$filename"
echo sanitised: "$cleaned"
Result is:
original : Wh00t? it's a -- re#lly-weird {file&name} (with + Plus and__1% #of# [$qRots$!]).mov
sanitised: Wh00t-it's-a-re#lly-weird-filename-with-Plus-and__1-of-qRots.mov
Looking at WP function, this emulates it quite well.
Inspired by the answer.
EscapeFilename()
{
printf '%s' "$#" | perl -pe 's/[:;,\?\[\]\/\\=<>''"&\$#*()|~`!{}%+]//g; s/[\s-]+/-/g;';
}
I have a Chromecast and a URL of an mp4 file online. I also have a 2Mbps download connection, which is pathetic and renders direct buffering to the Chromecast too slow. That's what I tried so far:
Through the developer console, I simply set location.href to the online URL of the mp4. The Chromecast would buffer for 20 seconds, play 10 seconds' worth of video, and then buffer again. So, through the console, I paused the video and let it buffer for 5 minutes. When I let it play again, it played for about 15 seconds, and then lost all progress and had to be returned to the home screen.
As I don't want to wait for the whole download of the mp4 to complete, I am currently attempting this: I buffer the mp4 to a local file which is in my htdocs directory, and I then direct the Chromecast to that file's location. However, when opening the mp4 file thorugh Chrome (the browser), instead of playing, it shows a download prompt, and the Chromecast returns to the home screen.
I have implemented the buffering in PHP, and it looks as thus:
$bufferSource = 'http://example.com/path/to/file.mp4';
$bufferedReader = fopen($bufferSource, 'r');
while(!($finished = feof($bufferedReader))){
if($finished !== false){ break; }
//get onle line
$buffer = fgets($bufferedReader);
file_put_contents('buffer.mp4', $buffer, FILE_APPEND);
}
fclose($bufferedReader);
I know that PHP does its work, as I can watch the file size grow on my computer, and I can open the file with VLC. Is there maybe another PHP script I could make to access the locally buffered mp4 file which simulates 'bufferability', so Chrome does not show the download dialog but buffers the file, as should do the Chromecast?
EDIT: One more thing. I am not directing the Chromecast to the PHP script. I am actually directing it directly to the buffer.mp4 file.
You're missing a Content-Type header in your PHP script.
Figure out what the original content type header is from your server (probably video/mp4) and send it with your proxying script like this:
header('Content-Type: video/mp4');
This will allow the browser to detect the content type and play it directly (if supported), without downloading.
Also, I would consider using a real proxy server, such as Nginx, rather than reinventing the wheel. This will be much easier and more reliable.
You can use a receiver with a Media Element tag and then point its source to your mp4 file on your server. If you don't want to write your own receiver, you can use either the default or Styled Media Receiver . You would need a very simple sender to send the url, check out the github repo for examples
Im playing with MongoDB and Im trying to import .csv files to DB and Im getting strange error. In process of uploading script just ends for no reason and when I try to run it again nothing happens only solution is to restart apache. I have already set unlimited timeout in php.ini Here is the script.
$dir = "tokens/";
$fileNames = array_diff( scandir("data/"), array(".", "..") );
foreach($fileNames as $filename)
if(file_exists($dir.$filename))
exec("d:\mongodb\bin\mongoimport.exe -d import -c ".$filename." -f Date,Open,Next,Amount,Type --type csv --file ".$dir.$filename."");
I got around 7000 .csv files and it manage to insert only about 200 before script ends.
Can anyone help? I would appreciate any help
You are missing back end infrastructure. It is just insane to try to load 7000 files into a database as part of a web request that is supposed to be short lived and is expected, by some of the software components as well as the end user, to only last a few seconds or maybe a minute.
Instead, create a backend service and command and control for this procedure. In the web app, write each file name to be processed to a database table or even a plain text file on the server and then tell the end user that their request has been queued and will be processed within the next NN minutes. Then have a cron job that runs every 5 minutes (or even 1 minute) that looks in the right place for stuff to do and can create reports of success or failure and/or send emails to tell the original requestor that it is done.
If this is intended as an import script and you are set on using PHP, it would be preferable to at least use the PHP CLI environment instead of performing this task through a web server. As it stands, it appears the CSV files are located on the server itself, so I see no reason to get HTTP involved. This would avoid an issue where the web request terminates and abruptly aborts the import process.
For processing the CSV, I'd start by looking at fgetcsv or str_getcsv. The mongoimport command really does very little in the way of validation and sanitization. Parsing the CSV yourself will allow you to skip records that are missing fields, provide default values where necessary, or take other appropriate action. As you iterate through records, you can collect documents to insert in an array and then pass the results on to MongoCollection::batchInsert() in batches. The driver will take care of splitting up large batches into chunks to actually send over the wire in 16MB messages (MongoDB's document size limit, which also applies to wire protocol communication).
I'm trying to install ClamAV on Windows but I can't find how to.
What I want actually is to scan for malwares uploaded files and return a value like "safe" or "Infected by: X"
Do you think it's possible on Windows using a free library?
Do you know if there is a paid software that can do this (even using command-line)?
I managed to do it by installing ClamWin on the Windows 2008 Server. (clamwin-0.97.6). I created the eicar.txt file in order to test detection:
X5O!P%#AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*
Created test.php file:
<?php
$file = 'C:/Users/Localadmin/Desktop/testfile/eicar.txt'; // infected test file
$db = '"C:/Documents and Settings/All Users/.clamwin/db/"'; // path to database of virus definition
$scan_result = shell_exec("D:/programs/clamwin/bin/clamscan --database=$db $file");
echo $scan_result;
?>
It gives me this result:
Eicar-Test-Signature FOUND
----------- SCAN SUMMARY -----------
Known viruses: 1568163
Engine version: 0.97.6
Scanned directories: 0
Scanned files: 1
Infected files: 1
Data scanned: 0.00 MB
Data read: 0.00 MB (ratio 0.00:1)
Time: 7.363 sec (0 m 7 s)
Than you can process the string $scan_result to figure out what number has been returned after 'Infected files: '.
I will be using it to scan files uploaded via form and since the scanning takes time (7 seconds) I will use some ajax script which can nicely return feedback to the user such "Uploading file..." and "Scanning for viruses..."
You can install clamav for windows (clamwin), and use php's passthru function to scan a file via commandline and get the output back. Parse it then display your message. You will have to adjust your php timeout value, or configure your application to upload, get the user to constantly refresh for the status while a background script scans and inserts the result into a database or something. Try looking at virustotal.com they do this, and scan it with over 20 av scanners.