7 September 2011

php open, write and download a file

I have spend today and yesterday trying to make html write into a file and then download that file. The first objective was to open a file.


Seems straight forward but i got an error

fopen(LinkTestText.txt) [function.fopen]: failed to open stream: Permission denied.

Okay okay calm down all I have to do is change permission of the file. <long time doing a google search> (many frustrating clicking and shouting at the computer (glad it doesn't have emotions)). On all <exaggeration> the forums no one mentioned a php function called "chmod"!!! Why this is what i'm looking for, okay so lets code it.

chmod($filename, 0777);

Error appears:

chmod(): Operation not permitted in /file/path/to/that/ruddy/file.php

Rubbish, lets look on php.net to see if they have an answer <Quick look> ooh they have an answer. What one person says is use File Transfer Protocol (ftp) to change the permission, Huzzah an answer finally.

$row['username']="Joe Bloggs";
$ftp_details['ftp_user_name'] = $row['username'];
$ftp_details['ftp_user_pass'] = $row['password'];
$ftp_details['ftp_root'] = '/file/path/to/that/ruddy/';
//website address
$ftp_details['ftp_server'] = '';
function chmod_11oo10($path, $mod, $ftp_details){
// extract ftp details (array keys as variable names)
extract ($ftp_details);
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to chmod $path directory
if (ftp_site($conn_id, 'CHMOD '.$mod.' '.$ftp_root.$path) !== false){
else {
// close the connection
return $success;
chmod_11oo10($filename, "0777", $ftp_details);
fwrite($file,"Writing a lovely string to a file");

Good so all we need to do now is activate ftp and then work out a way to force a download. Here is a link i found earlier

header('Content-Description: File Transfer');
header('Content-Type: application/download');
//it will be called
header('Content-Disposition: attachment; filename="Link test test.txt"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));

Done. One last thing the whole of it HAS to appear before "any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.". The only thing that is missing is why i put 0777 as the permission, to be honest i have no idea, just saw the number keep on popping up on a couple of forums.

No comments:

Post a Comment