Download the YouTube video file directly to user's computer through browser - php

<?php
$youtubeUrl = "https://www.youtube.com/watch?v=Ko2JcxecV2E";
$content = json_encode ($file = shell_exec("youtube-dl.exe $youtubeUrl "));
$input_string =$content;
$regex_pattern = "/Destination:(.*.mp4)/";
$boolean = preg_match($regex_pattern, $input_string, $matches_out);
$extracted_string=$matches_out[0];
$file =explode(': ',$extracted_string,2)[1];
// Quick check to verify that the file exists
if( !file_exists($file) ) die("File not found");
// Force the download
header("Content-Disposition: attachment; filename=\"$file\"" );
header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);
?>
When I run this file the respective YouTube video is first downloaded to the localhost server folder where this PHP file is, using youtube-dl.exe and then it is pushed from that folder to browser download (forced download).
How to directly start the download to user's browser?
Also the file is running fine on localhost but not on remote server.

First, you need to use a version of youtube-dl for a platform of your webserver. The youtube-dl.exe is a build for Windows, while most webhostings use Linux.
Then use the passthru PHP function to run the youtube-dl with the -o - command-line parameter. The parameters makes youtube-dl output the downloaded video to its standard output, while the passthru passes the standard output to a browser.
You also need to output the headers before the the passthru. Note that you cannot know the download size in this case.
header("Content-Disposition: attachment; filename=\"...\"" );
header("Content-Type: application/octet-stream");
passthru("youtube-dl -o - $youtubeUrl");
If you need a video metadata (like a filename), you can run the youtube-dl first with the -j command-line parameter to get the JSON data without downloading the video.
Also you need 1) Python interpreter on the web server 2) to be able to use the passthru function 3) connectivity to YouTube from the PHP scripts. All these are commonly restricted on webhostings.

The trouble is probably within: shell_exec("youtube-dl.exe $youtubeUrl ")
Firstly, some hosts disable shell_exec for security reasons.
Secondly, youtube-dl.exe looks like it is probably a windows script, where as your remote server is probably Linux based.

Related

Lauching program via command in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php How do I start an external program running - Having trouble with system and exec
how to open exe with php?
I had this idea and make hard to success it for several years,but failed at last. any one tell me a success method to do the job ?
<?php
if(isset($_POST['file_path'])){
/* -------
using "notepad++.exe" to open "test.php" file.
or run a bat file which calling "notepad++.exe" to open "test.php" file.
how to seting php.ini or firefox or any setting to do this job.
it is only for conveniently developing web page in my PC ,not for web servers
------- */
}
?>
<form action="test.php" method="post">
<input type="text" name="file_path" value="test.php"/>
<button type="submit">open with notepad++</button>
</form>
This would create something like:
To launch a program on the computer which runs the webserver:
<?php
exec('"C:\Program Files (x86)\Notepad++\notepad++.exe" "C:\foo.php"');
The above will work on vista/win7 IF the webserver does not run as a windows service. For example, if you run apache and it automatically starts when your computer boots, you probably installed it as a service. You can check to see if apache shows up in the windows services tab/thingy.
If the webserver runs as a service, you'll need to look into enabling the "allow desktop interaction" option for the service. But otherwise:
An easy test using php's new built in webserver(php 5.4+). The key thing here is you manually start the server from a shell, so it runs as your user instead of as a service.
<?php
// C:\my\htdocs\script.php
exec('"C:\Program Files (x86)\Notepad++\notepad++.exe" "C:\foo.php"');
start a webserver via a command window
C:\path\to\php.exe -S localhost:8000 -t C:\my\htdocs
Then in your browser
http://localhost:8000/script.php
I assume you are wanting the client device to open Notepad++ not the remote server. If this is the case, the best you can do is to serve up the file with the proper file type header and hope the client has Notepad ++ set up as the default application to open such a file.
Something like this should do it:
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="' . $file_name . '"'); // forces file download
header('Content-length: ' . filesize($file_path));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); // make sure file is re-validated each time it is requested
$fh = fopen($file_path, 'r');
while(!feof($fh)) {
$buffer = fread($fh, 2048);
echo $buffer;
}
fclose($fh);
Where $file_name is the name of the file (not the full path) and $file_path is the full path to the file
the finally successful way I tested.
thank Charles ,refer to php How do I start an external program running - Having trouble with system and exec
Start->Run, type "services.msc" to bring up Services control (other ways to get there, this is easiest IMO)
Locate your Apache service (mine was called "wampapache" using WampServer 2.0)
Open the service properties (double-click or right click->properties)
Flip to the Log On account and ensure the checkbox titled "Allow service to interact with Desktop" is checked
Flip back to the General tab, stop the service, start the service
then: in php
pclose(popen("start /B \"d:\\green soft\\notepad++5.8.4\\notepad++.exe\" \"d:\\PHPnow-1.5.6\\htdocs\\laji\\a.php\"", "r"));
Thank all your good guys, what a great help . I had finally made my idea to be true. Happy new year !
never had a reason to do so, but have you tried passthru() ?
http://php.net/manual/en/function.passthru.php
EDIT:
sorry the OP was really unclear at first glance..
what I would do is parse the file into a string or whatnot, then force the browser to treat that as a download.. php is server sided so you can`t only ask the browser to do some stuff..
$someText = 'some text here';
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="text.txt"');
echo $someText;

YouTube-dl server direct file download

I have succesfully installed youtube-dl on my server and from command line everything is working like a charm.
Now I want to be able to call a link on my site from my web browser which directly initiates a download of the file. So in that order:
Open site in browser (for example http://example.com/download.php?v=as43asx3
YouTube-dl processes the input
Web-browser downloads file
Temporary files will be deleted from server
I am not very experienced with this, but nevertheless need to solve this issue.
There might be a better way of doing this and I would appreciate seeing it, however, here is how I solved it:
<?php
ignore_user_abort(true);
//getting ID from URL
$youtubeID = $_GET['videoID'] ;
//getting audio file from youtube video via youtube-dl
exec('~/bin/youtube-dl --verbose --extract-audio -o "~/html/YouTubeDownloader/%(id)s.%(ext)s" '.$youtubeID);
//downloading file to client/browser
$filename = $youtubeID.".m4a";
header("Content-disposition: attachment;filename=$filename");
header("Content-type: audio/m4a");
readfile($filename);
//deleting file again
unlink($filename);?>

Uploading a PHP generated CSV file to SFTP server via terminal

I have a PHP file which generates a CSV file using the code below:
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
I've not included the code which creates the content as it does it's job fine. What I need to do is use terminal to run this file and upload the results to an sftp server. I can connect to the server fine in terminal.
I have been using the php command in terminal to produce the resulting CSV. This however doesn't produce the CSV like it does when run in the browser. What it does do is produce the CSV as a string.
Is there a way to either produce the CSV as a file like the browser so I can grab it in terminal and upload it to the SFTP server? Alternatively is it possible to echo out the string produced from the PHP file and create the CSV myself using this kind of command:
echo "boo,to,you">file.csv
Just redirect the php output to a temporary file and upload the file.
php yourscript.php > /tmp/file.csv
echo "put /tmp/file.csv" | sftp user#example.com
If you want to do it without the temporary file, you cannot do with just the (OpenSSH) sftp as it cannot read contents to upload from the stdin. Neither the (OpenSSH) scp can.
You can of course produce the file from PHP code itself, if that suits your task better.
Just use the file_put_contents():
file_put_contents("/tmp/file.csv", $csv_output);
See How to write into a file in PHP?
The suggestion by #MarcB should work, if the remote server is *nix (understands the cat) and allows a shell access.
php yourscript.php | ssh user#example.com 'cat > file.csv'
Though obviously that's not "SFTP upload" anymore.
When producing a file, do not use the the header(). Headers make sense in webserver environment only, not when you use the PHP as a scripting language in a shell.

How can I start a Windows GUI program using PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php How do I start an external program running - Having trouble with system and exec
how to open exe with php?
I had this idea and make hard to success it for several years,but failed at last. any one tell me a success method to do the job ?
<?php
if(isset($_POST['file_path'])){
/* -------
using "notepad++.exe" to open "test.php" file.
or run a bat file which calling "notepad++.exe" to open "test.php" file.
how to seting php.ini or firefox or any setting to do this job.
it is only for conveniently developing web page in my PC ,not for web servers
------- */
}
?>
<form action="test.php" method="post">
<input type="text" name="file_path" value="test.php"/>
<button type="submit">open with notepad++</button>
</form>
This would create something like:
To launch a program on the computer which runs the webserver:
<?php
exec('"C:\Program Files (x86)\Notepad++\notepad++.exe" "C:\foo.php"');
The above will work on vista/win7 IF the webserver does not run as a windows service. For example, if you run apache and it automatically starts when your computer boots, you probably installed it as a service. You can check to see if apache shows up in the windows services tab/thingy.
If the webserver runs as a service, you'll need to look into enabling the "allow desktop interaction" option for the service. But otherwise:
An easy test using php's new built in webserver(php 5.4+). The key thing here is you manually start the server from a shell, so it runs as your user instead of as a service.
<?php
// C:\my\htdocs\script.php
exec('"C:\Program Files (x86)\Notepad++\notepad++.exe" "C:\foo.php"');
start a webserver via a command window
C:\path\to\php.exe -S localhost:8000 -t C:\my\htdocs
Then in your browser
http://localhost:8000/script.php
I assume you are wanting the client device to open Notepad++ not the remote server. If this is the case, the best you can do is to serve up the file with the proper file type header and hope the client has Notepad ++ set up as the default application to open such a file.
Something like this should do it:
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="' . $file_name . '"'); // forces file download
header('Content-length: ' . filesize($file_path));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); // make sure file is re-validated each time it is requested
$fh = fopen($file_path, 'r');
while(!feof($fh)) {
$buffer = fread($fh, 2048);
echo $buffer;
}
fclose($fh);
Where $file_name is the name of the file (not the full path) and $file_path is the full path to the file
the finally successful way I tested.
thank Charles ,refer to php How do I start an external program running - Having trouble with system and exec
Start->Run, type "services.msc" to bring up Services control (other ways to get there, this is easiest IMO)
Locate your Apache service (mine was called "wampapache" using WampServer 2.0)
Open the service properties (double-click or right click->properties)
Flip to the Log On account and ensure the checkbox titled "Allow service to interact with Desktop" is checked
Flip back to the General tab, stop the service, start the service
then: in php
pclose(popen("start /B \"d:\\green soft\\notepad++5.8.4\\notepad++.exe\" \"d:\\PHPnow-1.5.6\\htdocs\\laji\\a.php\"", "r"));
Thank all your good guys, what a great help . I had finally made my idea to be true. Happy new year !
never had a reason to do so, but have you tried passthru() ?
http://php.net/manual/en/function.passthru.php
EDIT:
sorry the OP was really unclear at first glance..
what I would do is parse the file into a string or whatnot, then force the browser to treat that as a download.. php is server sided so you can`t only ask the browser to do some stuff..
$someText = 'some text here';
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="text.txt"');
echo $someText;

wkhtmltopdf: download a PDF to the user's HD

how to download automaticaly (to the user's HD) a pdf generated using wkhtmltopdf or snappy? You know.. a user click a link ("Download this page as PDF") and download the pdf to his/her HD.
Regards
Javi
PHP: there are better ways of getting wkhtmltopdf working with PHP, however, I like to be able to print out what my command line is so that I can debug the resulting page that bit more easily. It is not just about code, but about having margins and other page details correct. Here the wkhtmltopdf is a binary in the web root, margins are set to zero, the background is turned off:
$do_it=$_SERVER["DOCUMENT_ROOT"]."/wkhtmltopdf --dpi 600 -B 0 -L 0 -R 0 -T 0 --no-background http://".$_SERVER['SERVER_NAME']."/".$filename." ".$_SERVER["DOCUMENT_ROOT"]."/".$pdf_url;
//var_dump($do_it); // uncomment to see your wkhtmltopdf parameters...
$whatever=passthru($do_it);
header('Content-disposition: attachment; filename='.$pdf_url);
header('Content-type: application/pdf');
readfile($pdf_url);
I don't think much comes back when running passthru when it comes to error messages, however, it does run whatever you send it.
As for header, it is important to set the content type to PDF or else the browser will not know what to do with it.
The Snappy website actually also has a ready made example just for this.
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput('http://www.github.com');
Here's how I do it in RoR
filename = "MyNew.pdf"
fullpath = "#{RAILS_ROOT}/tmp/charts/#{filename}"
# system issues a shell command
system "/usr/local/bin/wkhtmltopdf \"http://localhost/page/to/pdf?download=t\" #{fullpath}"
send_data(File.read(fullpath), :type => 'application/pdf', :filename => filename, :disposition => "attachment;filename=\"#{filename}\"")

Categories