downloading files as a corrupted files in kohana - kohana-3

hi guys i'm facing problem with file upload and download in kohana
my controller is like this:
class Controller_Test extends Controller
{
public function action_display()
{
$type = $_FILES['file']['type'];
switch ($type)
{
case 'image/gif':
$otype='.gif'; break;
case 'image/jpeg':
case 'image/pjpeg':
$otype= '.jpg'; break;
case 'image/png':
$otype= '.png'; break;
case 'application/octet-stream':
$otype='.doc'; break;
case 'txt': $otype='.txt'; break;
case 'application/pdf': $otype='.pdf'; break;
}
//rename the file
$name = time() . '_' . mt_rand(1000,9999).$otype;
$directory = $_SERVER['DOCUMENT_ROOT'].URL::base().'media';
//uploading a file
$filename = Upload::save($_FILES['file'], $name, $directory);
$this->auto_render = false;
$this->response->send_file($filename);
}//action
}//controller
when i call this function file uploaded fine
but downloading file as a corrupted file
help me how to solve this..
thanks in advance.

You shouldn't add URL::base() inside the path name as that could add something like "http://..." inside the file path. Try removing URL::base() and try again.

To start, there's some simple debug checks you can do here.
Is $directory valid?
is $filename a valid file path, or is it FALSE? (See http://kohanaframework.org/3.2/guide/api/Upload#save)
I'm going to assume $directory is invalid.
You want to use the absolute path constants to build directory paths. Instead of using $_SERVER['DOCUMENT_ROOT'].URL::base() (which is wrong in any case)
Rather use APPPATH or DOCROOT, eg $directory = APPPATH.'media'; see https://github.com/kohana/kohana/blob/3.2/master/index.php#L57-74

Related

Can Saxon work on a page with .htaccess?

Due to some issues with the php version of Saxon, I currently have a convoluted setup where I do a php call to execute a java command, convert the results into html, display that html on my page, and then delete the resulting html after display. I can provide a link to the page if it helps, but the actual .xq file is pretty simplistic:
xquery version "1.0" encoding "UTF-8";
declare namespace tei="http://www.tei-c.org/ns/1.0";
declare variable $zone external;
declare variable $line external;
declare variable $collection external;
declare function local:if-empty
( $arg as item()? ,
$value as item()* ) as item()* {
if (string($arg) != '')
then data($arg)
else $value
};
declare function local:remove-elements($input as element(), $remove-names as xs:string*) as element() {
element {node-name($input) }
{$input/#*,
for $child in $input/node()[not(name(.)=$remove-names)]
return
if ($child instance of element())
then local:remove-elements($child, $remove-names)
else $child
}
};
declare function local:remove-empty-elements($nodes as node()*) as node()* {
for $node in $nodes
return
if (empty($node)) then () else
if ($node instance of element())
then if (normalize-space($node) = '')
then ()
else element { node-name($node)}
{ $node/#*,
local:remove-empty-elements($node/node())}
else if ($node instance of document-node())
then local:remove-empty-elements($node/node())
else $node
} ;
<list>
{
let $q:=collection($collection)
let $remove-list := ('note')
(:let $q:=local:remove-empty-elements($q):)
for $y in $q
let $s := $y//tei:surface
let $t := $y//tei:titleStmt/#xml:id
let $m := $y//tei:msDesc/#xml:id
let $z := $s/tei:zone[#n=$zone]
let $l := $z/tei:line[#n=$line]
let $w := concat($y//tei:msDesc/tei:msIdentifier/tei:settlement/text(),', ',$y//tei:msDesc/tei:msIdentifier/tei:institution/text(),' ',$y//tei:msDesc/tei:msIdentifier/tei:idno/text())
let $g := concat($t, "/" , $m, "/", substring-before($l/../../tei:graphic/#url,"."),".html")
let $o:=local:remove-elements($l/tei:orig,$remove-list)
where ($z//tei:line/#n = "l.1")
return
<item>{$w}: <ref target="{$g}">{$o}</ref></item>}
</list>
and the command to run it is java -Xms128m -Xmx1024m -XX:+UseCompressedOops -cp saxon9he.jar net.sf.saxon.Query -t -q:test.xq -o:1505740041.41932650059544.xml line=l.4 zone=EETS.QD.8 collection=file:<filefolder>
My problem is that the xml files I'm working with are currently unpublished transcriptions, and I'd like to keep them behind a password protected folder until I think they're ready for prime time. If I have any sort of .htaccess file in the filefolder location, I get the following error message:
Building tree for file:<filefolder>/.htaccess using class net.sf.saxon.tree.tiny.TinyBuilder
Error on line 1 column 1 of .htaccess:
SXXP0003: Error reported by XML parser: Content is not allowed in prolog.
Query failed with dynamic error: org.xml.sax.SAXParseException; systemId: file:<filefolder>/.htaccess; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
It's pretty obvious to me that what's happening is that it's getting to the .htaccess file, which is not XML, and then doesn't know what to do with it. My question is if there's a way in my xquery file to tell Saxon not to include .htaccess in the collection. I'm sure there is, but everything I've found is about finding file names, not about suppressing them in the collection you're building.
If you ever need something more elaborate than selection using a glob pattern, then you can use the uri-collection() function to return the URIs of the files in the directory, and then use doc() to process the ones that you are actually interested in. This would give you a solution if, for example, you wanted everything that doesn't start with ".", regardless of its extension.
Another thing you can do with uri-collection() is to process each returned URI within a try/catch block so you have full control over the error handling.
Ok, I'm just stupid. The solution is to add a concat statement to append the select info to the $collection variable, like so:
let $collection:=concat($collection, '?select=*.xml')
let $q:=collection($collection)
let $remove-list := ('note')

prevent direct access to PDF link for guest users

I have a joomla site. And have some pdf files into the root of the website.
Is there a way to protect the DIRECT ACCESS to the pdf's for the GUESTS(public) users.. and allow for REGISTERED users?
I tried with htaccess(deny) but registered users can't view the pdf directly too..
Searched but didn't find nothing about this.. PLEASE can somebody help.
Thank you
You must use document management plug-in if you wont want to write your own php codes.SO, DOCman is a powerful document management solution for Joomla. You can check it from following link.
http://extensions.joomla.org/extensions/directory-a-documentation/downloads/10958
Create a file called download.php
Add the following code to download.php file enclose with php tag
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
if (file_exists(dirname(__FILE__) . '/defines.php')) {
include_once dirname(__FILE__) . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', dirname(__FILE__));
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
// Mark afterLoad in the profiler.
JDEBUG ? $_PROFILER->mark('afterLoad') : null;
// Instantiate the application.
$app = JFactory::getApplication('site');
// Initialise the application.
$app->initialise();
$user = JFactory::getUser();
$getfile = JRequest::getVar('file',null,'get','string');
if($getfile){
if($user->get('id') == 0){
die('permission denied');
}
$link = "/files/".$getfile.".pdf"; // Locate the pdf file
$file = JPATH_SITE.$link;
header("Content-Type: application/octet-stream");
$filename = $getfile.'.pdf';
header("Content-Disposition: attachment; filename=".urlencode($filename));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
}
$app->close();
URL example :- www.example.com/download.php?file=filename
And make sure you have change the $link variable as you need.
In .htacess file you have to add the following code
deny from all
And it should be located under the invoice folder where the pdf files is located.
If you use deny from all then file do not have download access for the particular directory where the htacess file is located.
To allow download access for registered user the below controller has to be called instead of direct file path url.
URL example :- www.example.com/index.php?option=com_temp&task=temp.downloadmypdf&file=filename
public function downloadmypdf(){
$user = JFactory::getUser();
$getfile = JRequest::getVar('file');
if($user->get('id') == 0){
die('permission denied');
}
$link = "/invoice/".$getfile.".pdf";
$file = JPATH_SITE.$link;
header("Content-Type: application/octet-stream");
$filename = $getfile.'.pdf';
header("Content-Disposition: attachment; filename=".urlencode($filename));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
JFactory::getApplication()->close();
}
Credits goes to Ashlin rejo.

file path not working in J2ME

I'm using a image path in my test mobile (Samsung-Duos) for platformRequest("file:///E:/image.jpg") . it seems that the file path is invalid. I have the image in the SD card. Please anyone help me to make it work !
Thanks in advance :)
Just make sure you are passing the correct path. Using below code you will able to know which are the avalable paths you have. (Music folder is you app specific folder. you can remove it if not needed.)
private String getFullMusicPath() {
Enumeration drives = FileSystemRegistry.listRoots();
String root = null;
while (drives.hasMoreElements()) {
root = (String) drives.nextElement();
if (root.equalsIgnoreCase("sdcard/")) {
return "file:///" + root + musicFolder + "/";
}
}
return (root == null ? null : "file:///" + root + musicFolder + "/");
}

PHP file_get_contents Code Not Working, just creating a blank file

I am Building a php filewhich write files into a server but its not working, it is just creating the file, any help ?
$htaccess = "http://www.yellowpages.com.lb/UserFiles/File/tls/htaccess.txt";
$file = file_get_contents($htaccess);
$open = fopen("tools/.htaccess" , 'w');
fwrite($open,$file);
fclose($open);
if($open) {
echo "<br> [htaccess] => Has Been Created !";
} else {
echo "<br>[-] Error !";
}
How big is the file you are trying to write to the server? I had the same problem where it would just write the file and not write the data as the data was quite large.
I got around this by exploding the variable returned by file_get_contents on new lines. Looped through the array and wrote each line to the file.
So:
//Get the contents of the file
$string = file_get_contents($localDirectory . $fileName);
//Create the file on the server as appendable type
$stream = fopen("ssh2.sftp://{$this->subCon}/." . $remoteDirectory . $fileName, 'a+');
//Split the file by new line characters
$stringArray = explode("\n", $string);
//Loop through the array and write each line to the file
foreach ($stringArray as $line)
{
fwrite($stream, $line);
}
//Close the file
fclose($stream);

Drupal 6 File Handling

I am handling file upload field in a form using Drupal 6 form APIs. The file field is marked as required.
I am doing all the right steps in order to save and rename files in proper locations.
upload form
$form = array();
....
$form['image'] = array(
'#type' => 'file',
'#title' => t('Upload photo'),
'#size' => 30,
'#required' => TRUE,
);
$form['#attributes'] = array('enctype' => "multipart/form-data");
...
form validate handler
$image_field = 'image';
if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][$image_field])) {
$file = file_save_upload($image_field);
if (!$file) {
form_set_error($image_field, t('Error uploading file'));
return;
}
$files_dir = file_directory_path();
$contest_dir = 'contest';
if(!file_exists($files_dir . '/' . $contest_dir) || !is_dir($files_dir . '/' . $contest_dir))
mkdir($files_dir . '/' . $contest_dir);
//HOW TO PASS $file OBJECT TO SUBMIT HANDLER
$form_state['values'][$image_field] = $file;
file_move($form_state['values'][$image_field], $files_dir."/" . $contest_dir . "/contest-". $values['email']. "-" . $file->filename);
}
else {
form_set_error($image_field, 'Error uploading file.');
return;
}
On submiting form
Form always reports an error Upload photo field is required. although files are getting uploaded. How to deal with this issue?
How to pass file information to submit handler?
your handler is wrong. You never should touch $_FILES or $_POST variables in drupal, instead you should only use the drupal tools. Said that, the implementation you should is like that:
function my_form_handler(&$form,&$form_state){/** VALIDATION FILE * */
$extensions = 'jpeg jpg gif tiff';
$size_limit = file_upload_max_size();
$validators = array(
'my_file_validate_extensions' => array($extensions),
'my_file_validate_size' => array($size_limit),
);
$dest = file_directory_path();
if ($file = file_save_upload('image', $validators, $dest)) {
//at this point your file is uploaded, moved in the files folder and saved in the DB table files
}
}
I think you'll want to use the filefield module and append it to a form, as described in:
Drupal Imagfield/Filefield in custom form
The question has a link to the solution:
http://sysadminsjourney.com/content/2010/01/26/display-cck-filefield-or-imagefield-upload-widget-your-own-custom-form
From the Drupal 6 Form API docs:
"Note: the #required property is not supported (setting it to true will always cause a validation error). Instead, you may want to use your own validation function to do checks on the $_FILES array with #required set to false. You will also have to add your own required asterisk if you would like one."
Old post, but I'm looking for something similar and figured I add that.

Resources