show uploaded image yii - yii

I am new to php and yii. I have a file field in my form to upload images. I use the following code to upload the image using file field.
Code in View:
<?php echo $form->fileField($model,'logo', array('class'=>'input-file')); ?>
<img src="<?php
echo Yii::app()->request->baseUrl.'/protected/uploads/sitelogo/'.$savedvalues['varLogo'];
?>" width="50" height="50" />
<?php echo $form->hiddenField($model,'hiddenfile',
array('value'=>$savedvalues['varLogo'])); ?>
code in controller:
$randnum = rand(0,100);
$home->varLogo = $randnum.$model->logo;
$file= Yii::app()->getBasePath().'/uploads/sitelogo/'.$randnum.$model->logo;
$model->logo->saveAs($file);
The images are uploading fine now. I have saved the uploaded images in protected\uploads\ folder. I am trying to show the uploaded image in edit image section. But the image doesn't display. It Shows failed to load the given url in firebug.
How can i correct this issue?

protected folder is protected for some reason - nobody can access it
if you want to access your pictures move them to public folder (or public/uploaded)
here is .htaccess content for protected
deny from all
EDIT:
of course you can put your files into protected folder(or make uploaded folder not accessible too) if you want some ACL for your users, and then check access, read and output file by your script(class)
in view:
<img src="<?php
echo Yii::app()->request->baseUrl.'/image.php?url=protected/uploads/sitelogo/'.$savedvalues['varLogo'];
?>" width="50" height="50" />
in your controller or class:
if (Yii::app()->session['user_can_access_files']) {
header('Content-Type: image/jpeg');
readfile($_GET['url']);
} else {
Yii::app()->user->loginRequired();
}

Caveat: I'm a total yii noob, so take this w/ a grain of salt :)
I took a similar approach, but have user-specific folders & added a MIME type check.
I upload files in a similar way, then view them with this in the view:
echo '<embed src="/tim_0.5/index.php/files/Getdatafile/' . $modelid . '" width=100% height=400>';
And from my controller I have:
public function actionGetdatafile($id)
{
$model=$this->loadModel($id);
$imgpath = $model->user_id . '/' . $model->filename;
$file=Yii::app()->getBasePath().'/datafiles/'.$imgpath;
if (file_exists($file))
{
$img=getimagesize($file);
header('Content-Type: '.$img['mime']);
readfile($file);
exit;
} else {
echo 'File not found!';
}
}

<b><?php echo CHtml::encode($data->getAttributeLabel('binaryfile')); ?>:</b>
<?php echo CHtml::image(Yii::app()->request->baseUrl.'/upload/'.$data->fileName); ?>
<br />
filename is name of your file which you have stored in upload folder in root directory.
(Yii::app()->request->baseUrl.'/upload/' point to your upload folder which is in your root directory
Hope it works....

Related

Install ckeditor in YII framework

I am using Yii Framework version 1.1.14. I am able to install FCK editor but I want to use ck editor.
I download files from this links http://www.yiiframework.com/extension/the-ckeditor-integration/
and upload files on location but i get this error
check image
I am using this code in my view
<?php $this->widget('application.extensions.ckeditor.CKEditorWidget',array(
'model'=>$model, # Data-Model (form model)
'attribute'=>'content', # Attribute in the Data-Model
'height'=>'400px',
'width'=>'100%',
'toolbarSet'=>'Basic', # EXISTING(!) Toolbar (see: ckeditor.js)
'ckeditor'=>Yii::app()->basePath.'/../ckeditor/ckeditor.php',
# Path to ckeditor.php
'ckBasePath'=>Yii::app()->baseUrl.'/ckeditor/',
# Relative Path to the Editor (from Web-Root)
'css' => Yii::app()->baseUrl.'/css/index.css',
# Additional Parameters
) ); ?>
Download CKEditor from http://ckeditor.com/download (Select full package) and put it in your root directory (You can put it any where according to you)
Add this is your view file
<script src="<?php echo Yii::app()->baseUrl.'/ckeditor/ckeditor.js'; ?>"></script>
<script type="text/javascript">
CKEDITOR.replace( 'Articles_meta_description');
</script>
Where Articles_meta_description is id of input fields
If you want add image upload in ckeditor you can download KCfinder from this link http://kcfinder.sunhater.com/download and put it in your root directory (you can put it any where according to you)
Set upload path into session : in your view file
$_SESSION['KCFINDER']['disabled'] = false; // enables the file browser in the admin
$_SESSION['KCFINDER']['uploadURL'] = Yii::app()->baseUrl."/uploads/"; // URL for the uploads folder
$_SESSION['KCFINDER']['uploadDir'] = Yii::app()->basePath."/../uploads/"; //
For ckeditor with image upload
<script type="text/javascript">
CKEDITOR.replace( 'Articles_meta_description', { // input field id
filebrowserBrowseUrl: '<?php echo Yii::app()->baseUrl; ?>/kcfinder/browse.php?type=files',
filebrowserImageBrowseUrl: '<?php echo Yii::app()->baseUrl; ?>/kcfinder/browse.php?type=images',
filebrowserFlashBrowseUrl: '<?php echo Yii::app()->baseUrl; ?>/kcfinder/browse.php?type=flash',
filebrowserUploadUrl: '<?php echo Yii::app()->baseUrl; ?>/kcfinder/upload.php?type=files',
filebrowserImageUploadUrl: '<?php echo Yii::app()->baseUrl; ?>/kcfinder/upload.php?type=images',
filebrowserFlashUploadUrl: '<?php echo Yii::app()->baseUrl; ?>/kcfinder/upload.php?type=flash'
});
</script>

Yii2: How to use backend web folders files in frontend

I have many images in backends web folder, I want to use those images in frontend how to get those files?
I need to display 1 (first) image which path is saved in database like Img1.jpg;img2.jpg;
<?php
foreach (explode(';',rtrim($row['images'],';'),1) as $key_img => $value_img)
{
?>
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
<?php
}
?>
<?= \yii\helpers\Html::img('#backend/web/images/your-image.jpg') ?>
The src parameter, containing the backend alias, will be processed by Url::to()
Check the docs for details on Html::img().
Simply try:
<?= \yii\helpers\Html::img( Yii::getAlias('#backend'). '/web/images/your-image.jpg') ?>

Opencart - Upload Specific File Type

I am using OpenCart 1.5.6 and have two options for the customer to upload files to a product (image and video). When the users clicks upload I would like them to only be able to select specific file types from their computer while they browse for the files. So instead of "All Files" in the browser window, I want it to only allow .png, .jpg, .jpeg, .pdf, etc. for the image upload and for the video file I just want it to look for .mp4, .mov, .flv.
Here is an example: http://jsfiddle.net/VCdvA/
I have tried to use the accept attribute according to this post but it doesn't work.
Here is my code for the product.tpl:
<input type="button" accept="video/*,image/*" value="<?php echo $button_upload; ?>" id="button-option-<?php echo $option['product_option_id']; ?>" class="button" >
<input type="hidden" name="option[<?php echo $option['product_option_id']; ?>]" value="" />
I think that the problem is that it is type="button" and not type="file". Is there another way to limit the upload file type within the OpenCart product page?
The problem is the jQuery plugin used. It is AjaxUpload which seems to be taken over by different developer (completely) and reworked (completely) and the links to the original (old) documentation are dead (completely).
Well, after exploring that jQuery plugin I have found out that it works this way: in the ptoduct.tpl You can see:
<?php foreach ($options as $option) { ?>
<?php if ($option['type'] == 'file') { ?>
<script type="text/javascript"><!--
new AjaxUpload('#button-option-<?php echo $option['product_option_id']; ?>', {
//...
});
//--></script>
<?php } ?>
<?php } ?>
This means that for each option of type file this AjaxUpload is instanciated. Basically it only creates a DIV containing INPUT of type FILE with 0 opacity that is rendered above the Upload File button. This means that when user clicks on Upload File he clicks on the INPUT of type FILE instead (without knowing this). Now, looking at the code I can see that there is no possibility to set this accept="image/*" attribute because there is no support for this (original code):
_createInput: function(){
var self = this;
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
addStyles(input, {
// ...
});
// ...
},
So now if You'd like to add support for this, You'd need to change this code to this (file: catalog/view/javascript/jquery/ajaxupload.js, around line 350):
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
if (this._settings.accept) {
input.setAttribute('accept', this._settings.accept);
}
And change the code for plugin initializiation in product.tpl to:
<?php foreach ($options as $option) { ?>
<?php if ($option['type'] == 'file') { ?>
<script type="text/javascript"><!--
new AjaxUpload('#button-option-<?php echo $option['product_option_id']; ?>', {
<?php if ($option['product_option_id'] == <IMAGE_FILE_OPTION_ID>) { ?>
accept: 'image/*',
<?php } else if ($option['product_option_id'] == <VIDEO_FILE_OPTION_ID>) { ?>
accept: 'video/*',
<?php } ?>
//...
});
//--></script>
<?php } ?>
<?php } ?>
This should be enough.

View PDF in Yii

I have PDF stored in a folder, now i want to view it via link on my form page. How will i do it using Yii framework.
echo CHtml::link(
'pdf',
Yii::app()->createUrl('/uploads/Tutorial.pdf') ,
array('class'=>'button','target'=>'_blank'));
The error i am receiving mentioned below, i have also tried by including uploads in allow of controller.
Error
Error 404
Unable to resolve the request "uploads/Tutorial.pdf".
I am using mPDF to generate PDF but i don't know how to view an already generated PDF using Yii.
You need several more things to make this work. You may have already done some of this and not pasted it but here goes...
I'm assuming you've set up your site to use clean URLs with .htaccess by following this tutorial. Now you can add:
in config/main.php, urlMananger section you need a route to a controller class and action method. This tells Yii which controller to use when you go to the URL /uploads/Tutorial.pdf
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=>false,
'rules'=>array(
'uploads/<filename:[a-zA-Z]+\.pdf>' => 'upload/viewPdf', // actionViewPdf Method in UploadController class
// ... all your other rules
),
),
And a controller class, and a method with the same name as in your route above (prepended with action):
class UploadController extends Controller
{
// Put the usual Yii access control stuff here or whatever...
public function actionViewPdf()
{
$filename = $_GET['filename'] . '.pdf';
$filepath = '/path/to/your/pdfs/' . $filename;
if(file_exists($filepath))
{
// Set up PDF headers
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filepath));
header('Accept-Ranges: bytes');
// Render the file
readfile($filepath);
}
else
{
// PDF doesn't exist so throw an error or something
}
}
}
Then you should be able to use
echo CHtml::link(
'pdf',
Yii::app()->createUrl('/uploads/viewPdf', array('filename' => 'Tutorial')) ,
array('class'=>'button','target'=>'_blank'));
Hope that's helpful.
Well.... are you sure that the uploads folder is available on the server and it is in a location that is link friendly? Yii does not pass everything through it's index.php file, if a file already exists then it just used it like it is. That is why you can access the files in your images or css folder without having a controller for it.
If you are using the normal Yii structure then you should have your "uploads" folder next to your protected folder.
If your uploads folder is not in a web accessible location, use what JamesG told you to. The only change I would to is to the pattern, it only matches letters, you might have other chars in the name too.
Do not add ".pdf" to your link:
Yii::app()->createUrl('/uploads/Tutorial')
in PHP you can print your pdf like this (must be in the actionTutorial):
$mPDF = Yii::app()->ePdf->mpdf();
$mPDF->WriteHTML($this->render('tutorial', array(), true));
$mPDF->Output();
The tutorial is a simply html page that should be rendered into your pdf.
Here you can find the doku to the mpdf Yii extension

I am unable to upload file to my local host folder in php

I have the follwing code
<form enctype="multipart/form-data" action="upload.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
my page is in http://local.host/nausal/upload.php
now I am having the follwing error though i have created a folder in site with name upload.
Notice: Undefined index: uploaded in C:\wamp\www\Nausal\upload.php on line 15
Notice: Undefined index: uploaded in C:\wamp\www\Nausal\upload.php on line 17
Sorry, there was a problem uploading your file.
If the form is a part of upload.php too, you need to encapsulate the PHP-code and first check if $_FILES is not empty, otherwise you will always get a Notice if you only want to display the form.
<?php
if(!empty($_FILES))
{
//your PHP-code here
}
?>
<!-- your form here -->
Khan sb Place this code in file
called upload.php
create a folder called upload where
you created upload.php
change echo "The file ". basename(
$_FILES['uploadedfile']['name']). "
has been uploaded"; to echo "The
file ". basename(
$_FILES['uploaded']['name']). " has
been uploaded";
This will upload file successfully. First time when upload.php is uploaded there is no file selected so you will see some errors. But after you select a file and click upload you will not see any error. To avoid this error do as suggested by Dr. Molle