title: How to encrypt/decrypt files with php (mcrypt)?
body: <p>I'm surprised that I didn't find any code snippet, advice or tutorial in the web that explains how to encrypt a file using just standard php components. </p>
  
  <p>So I'm asking your advice: how to encrypt/decrypt files using just mcrypt and php standard functions? I do not have the option to use gnupg. No, actually, my question is: how to do the above without messing up my files? Because I'm already encrypting/decrypting the hell out of these files (with mcrypt/AES), and it works well for jpegs, PDF, some .doc files and interestingly password-secured .docx files. It does not work for non-secured .docx files and numerous other filetypes.</p>
  
  <p>My current code is this. Basically, I really just open the file, whisk the data around with mcrypt/AES, and write it on server/let user download it.</p>
  
  <p>To encode after upload:</p>
  
  <pre><code>// using codeigniter's encryption library, which uses mcrypt and the AES cypher
  $this-&gt;load-&gt;library('encrypt');
  $pathandname = $config['upload_path'].$output['content'][$a]['file_name']; 
  $theFile = file_get_contents($pathandname);
  $fh = fopen($pathandname,'w');
  fwrite($fh,$this-&gt;encrypt-&gt;encode($theFile));
  fclose($fh); 
  </code></pre>
  
  <p>To decode &amp; download:</p>
  
  <pre><code>$this-&gt;load-&gt;library('encrypt');
  $pathandname = $filelocation.$results[0]['encryptedfile']; 
  $theFile = file_get_contents($pathandname);
  $decrypted = $this-&gt;encrypt-&gt;decode($theFile);
  force_download($filename, $decrypted); // a codeigniter function to force download via headers
  </code></pre>