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.
Related
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;
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);?>
<?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.
So, I am using a php program to read a file, make some changes and then write it to a new file. After that, I call gnuplot, using a system call:
system('cat sarx.conf | /usr/bin/gnuplot');
sarx.conf has the gnuplot commands to generate the plot. The problem is if run my php from the command line (its on a linux server) it generates the image and stores it on the disk. But when I do the same thing by running the php on my browser it generates the image and tries to spit it out on the browser without actually storing it on disk.
Things i tried:
I though i might have had issues with permission settings but it didn't help.
I also hard coded the path where I want the image to be in sarx.conf. That didn't help either.
I also tried looking for it in the tmp directory --- no luck!!
Does anyone have any ideas on how can I get this to work? I need to store this image on disk so that my website can grab it to show the plot later. Is there any php stuff which can grab the image and write it to disk?
There is a great LGPL-licensed PHP interface to gnuplot here: http://www.liuyi1.com/PHP-GNUPlot/
Here is how you could do something similar:
$my_file = tempnam();
$handle = popen('gnuplot', 'w');
fwrite($this->ph, "Run some gnuplot commands here\n");
fwrite($this->ph, "set term png\n");
fwrite($this->ph, "set output ".$my_file."\n");
fwrite($this->ph, "replot\n");
flush($handle);
pclose($handle);
header('Content-Length: '.filesize($my_file));
header('Content-Type: image/png');
print file_get_contents($my_file);
unlink($my_file);
i want to open a notepad from php file and the notepad should contain the text which i declare as string in php file. essentially a notepad should open with the text I pass from php file.
If the PHP file is executing on a web server you cannot cause a web browser to open a new process like that. I'm sure you can imagine what a security hole that would be!
If you're running a PHP file as a local script in CLI mode, you should be able to launch notepad like any other process, e.g. using backticks or exec etc.
However, if you really wanted to do this server side, the best you could do is have a PHP script which used a Content-Disposition header, e.g.
//tell client we're delivering text
header('Content-type: text/plain');
//hint that it's a downloadable file
header('Content-Disposition: attachment; filename="textfile.txt"');
//output our text
echo "The quick brown\nfox jumps over\nthe lazy dog.";
The user can then save this file and open in their editor of choice.
You can't get PHP to open a window on the user's machine, because PHP is run entirely on the server. By the time the output reaches the browser the script will generally have terminated - you can only do what you can ask the browser to do and what it will let you (using HTML / headers etc.). For security purposes the browser will not (or should not) let an arbitrary website do very much with your machine - e.g. it will not let you spawn new Windows processes.
The best I think you could do is something like this:
$string = 'a string';
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="file.txt"');
echo $string;
This will send the relevant headers so that the browser will treat the content as a download called file.txt of type plain text. The browser should prompt them to download a file which will be likely to open in notepad, unless they have changed the file association for .txt .
However you won't be able to get any changes back that the user makes to the document unless you ask them to upload it, so I'm not sure this is a good solution to what you are trying to acheive.
It is possible to execute a program from php but only server-side.
So imagine the server runs Windows, it would start notepad server-side.
PHP gets executed on the server, and has nothing todo what's running client-side.
Technically, to do this you'd have to create a file and then execute a system with that file as a parameter. Something like this:
//String to show in notepad
$myStringToDisplay = "some text to show in notepad";
//Write this string to a file
$myFile = "somefile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $myStringToDisplay);
fclose($fh);
//Execute notepad with this file as a parameter
system("notepad.exe ".$myFile);
However, this is going to execute Notepad on the server running the PHP file (if system calls are even enabled on your server), which is probably not what you want to do. PHP cannot execute any code on the client machine, and certainly cannot make a system call to execute any program it wants on the client (thank god). It would be a huge, huge security breach.
If this does not accomplish the desired functionality, please tell us what you're trying to do and why. This does not sound like a very sensible request.
It is not possible to open a program from your php application. But you ca load the text file using a PHP text editor. You will also be able to load the values which you are talking about.
http://www.fckeditor.net/ is one such editor.
First you can "create" the file and fill it with text.
Execute shell command: echo $text >> $filename
then execute: notepad $filenameToOpen
Thats it.
To open a notepad from php script we will use command line inter phase.
Firstly we will create one php file in that we will write:
var_dump(popen('notepad','r'));
Then we will save that with some name like notepad.php
then open command prompat there we will give the path of our file to run our file
like:
d:/>wamp>www>php notepad.php
It will run our php file and it will oopen notpad.