Cakephp 2x Upload image - php

I'm trying to upload an image to my local folder
webroot/img/
and save the image name to database. Everything seems working fine but the image is not saving to the path
here's my view
<?php echo $this->Form->create(null,['url' => ['controller' => 'users', action' => 'update_image'],
array('enctype'=>'multipart/form-data')]); ?>
<?php echo $this->Form->input('User.id') ?>
<?php echo $this->Form->file('Profile.picture',['type'=>'file']) ?>
<?php echo $this->Form->end('submit') ?>
My controller
public function update_image(){
$id = $this->Auth->user('id');
$this->Profile->id = $id;
$this->set('profile', $this->User->findById($id));
if ($this->request->is(array('post','put'))) {
$frmData = $this->request->data;
//Path to store upload image
$target = "/teamjob_back/img/../img/".basename($frmData['Profile']['picture']);
//Get the data from form
$image = $frmData['Profile']['picture'];
//save data to database
$this->Profile->save($this->request->data);
//Image store to the img folder
if (move_uploaded_file($image['tmp_name']['name'], $target)) {
echo "Image successfull";
}
}
}
And the code
$image['tmp_name']['name']
gives me an Illegal string offset error.
EDITED
This code works on the controller
if ($this->request->is('post')) {
$frmData = $this->request->data;
$tmp = $frmData['picture']['tmp_name'];
$hash = rand();
$date = date("Ymd");
$image = $date.$hash."-".$frmData['picture']['name'];
$target = WWW_ROOT.'img'.DS.'uploads'.DS;
$target = $target.basename($image);
if (move_uploaded_file($tmp, $target)) {
echo "Successfully moved";
}
else
{
echo "Error";
}
}

First you need to remove "type => file" becuase you already use Form helper "file" function , if we are use "Form->input" then we use 'type=>file'
e.g. $this->Form->input('email', array('type' => 'email'));
$this->Form->file('Profile.picture')
check your target path have write permission, pr($image) then you get proper array format of $image['temp_name] or $image[0]['temp_name] etc.
and put your temp_name in move_uploaded_file function
e.g. move_uploaded_file(your temp_name)
Form Helper

First add
['type' => 'file']
as an option to your file instead of trying to send enctype.
Second $image is a $this->request->data['Profile']['picture'] so you can't do ['tmp_name'] and ['name'] together ... debug($this->request->data['Profile']['picture'] and you'll see that you could have
$image['tmp_name']
or
$image['name']
but not both together.
Probably more but those are good starts.

make sure to include enctype when you create the form uploading file
<?= $this->Form->create(NULL, ['enctype' => 'multipart/form-data']) ?>

Related

trying to append bandname to mp3 upload using $_SESSION['bandname'];

Trying to append $_SESSION['bandname']; to an mp3 file upload, The concept
is when someone uploads a song it append the band name to mp3 bandname_songname.mp3 if that makes sense. here is my code so far.
the problem is with this line i think $aditionalnewFileName = $bandname.="_".$aditionofileName; this strange part is when I use the var_dump($bandname); well instead of the band name its the song I'm testing with string(88) "_police.ogg_police.ogg_police.ogg_police.ogg_police.mp3_police.mp3_police.mp3_police.wav". maybe mysqli would be more simple?
<?php
session_start();
if (isset ($_SESSION ['band_id' ]))
{
$band_id = $_SESSION ['band_id' ];
$bandname = $_SESSION ['bandname' ];
$username = $_SESSION ['username' ];
}
var_dump($_SESSION['bandname']);
ini_set( "max_execution_time", "3600" ); // sets the maximum execution
time of this script to 1 hour.
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/mp3';
$aditiontmp_name = $_FILES['song_name']['tmp_name']; // get client
//side file tmp_name
// '/[^A-Za-z0-9\-_\'.]/', '' //$_FILES['song_name']['name']);
$aditionofileName = preg_replace('/[^A-Za-z0-9\-_\'.]/',
'',$_FILES['song_name']['name']); // get client side file name remove
the special character with preg_replace function.
// remove time() to edit name of mp3
$aditionalnewFileName = $bandname.="_".$aditionofileName; //filename
changed with current time
if ( move_uploaded_file($aditiontmp_name,
"$uploads_dir/$aditionalnewFileName")) //Move uploadedfile
{
$uploadFile = $uploads_dir."/".$aditionalnewFileName; //Uploaded file
path
$ext = pathinfo($uploads_dir."/".$aditionalnewFileName,
PATHINFO_EXTENSION); //Get the file extesion.
$uploadFilebasename = basename($uploads_dir."/".$aditionalnewFileName,
".".$ext); //Get the basename of the file without extesion.
$exName = ".mp3";
$finalFile = $uploads_dir."/".$uploadFilebasename.$exName; //Uploaded
file name changed with extesion .mp3
$encode_cmd = "/usr/bin/ffmpeg -i $uploadFile -b:a 256000 $finalFile
2>&1"; // -i means input file -b:a means bitrate 2>&1 is use for debug
command.
exec($encode_cmd,$output); //Execute an external program.
echo "<pre>";
// will echo success , for debugging we can uncomment echo
print_r($output);
// also want to add redirect to this script to send back to profile
after upload
echo "The file was uploaded";
//echo print_r($output); // Report of command excution process.
echo "</pre>";
if($ext !== 'mp3'){ // If the uploaded file mp3 which is not remove
from uploaded directory because we need to convert in to .mp3
unlink( $uploadFile );
}
//0644 vs 0777
chmod( $finalFile, 0777 ); // Set uploaded file the permission.
}
else
{
echo "Uploading failed"; //If uploding failed.
}
?>
so after a while, I decided to go about it a different way. I used mysqli,i quarried the user name and bandname, then used the while loop used var_dump noticed bandname after staring at my code i saw i was editing the wrong line so i change $aditionofileName = preg_replace('/[^A-Za-z0-9-_\'.]/', '',$bandname .
$_FILES['song_name']['name']); and change the line i thought was the problem to $aditionalnewFileName = "_".$aditionofileName; revmoed variable and removed the .
new code below.
<?php
session_start();
if (isset ($_SESSION ['band_id' ]))
{
$band_id = $_SESSION ['band_id' ];
$bandname = $_SESSION ['bandname' ];
$username = $_SESSION ['username' ];
}
if (isset ($_GET ['band_id']))
{ // Yes
$showband = $_GET ['band_id'];
}
else
{ // No
echo "ID not set"; // Just show the member
}
include 'connect.php';
$sql = "SELECT * from members WHERE band_id=$showband";
$result = mysqli_query ($dbhandle, $sql);
while ($row = mysqli_fetch_array ($result))
{
$username = $row ["username" ];
$bandname = $row ["bandname" ];
}
var_dump($bandname);
ini_set( "max_execution_time", "3600" ); // sets the maximum execution time of
this script to 1 hour.
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/mp3';
$aditiontmp_name = $_FILES['song_name']['tmp_name']; // get client side file
tmp_name
// '/[^A-Za-z0-9\-_\'.]/', '' //$_FILES['song_name']['name']);
$aditionofileName = preg_replace('/[^A-Za-z0-9\-_\'.]/', '',$bandname .
$_FILES['song_name']['name']); // get client side file name remove the special
character with preg_replace function.
// remove time() to edit name of mp3
$aditionalnewFileName = "_".$aditionofileName; //filename changed with current
time

display image from database in codeigniter

Good day! I am trying to retrieve from image path with the name stored from database but I am struggling to display that image from folder and I'll explain you that later... here is my code.
in my controller
public function save()
{
$url = $this->do_upload();
$title = $_POST["title"];
$this->main_m->save($title, $url);
}
public function do_upload()
{
$type = explode('.', $_FILES["pic"] ["name"]);
$type = $type[count($type)-1];
$url = "./images/".uniqid(rand()).'.'.$type;
if(in_array($type, array("jpg","jpeg","gif","png")))
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
if (move_uploaded_file($_FILES["pic"]["tmp_name"], $url))
return $url;
}
in my view im trying to retrieve like this.
<?php foreach ($this->b->getalldata() as $row) {
echo '<li>'.
'<a class="ns-img" href="'.base_url("images/".$row->image).'".></a>'.
'<div class="caption">'.$row->title.'</div>'.
'</li>';
} ?>
in my model
public function save($title, $url)
{
$this->db->set('title', $title);
$this->db->set('image', $url);
$this->db->insert('slider');
}
the image stored to path folder and also the new name of the image stored to database but displaying the image like that is not working for me. my image path folder is "images" and the image name stored to database is "./images/new_name.jpg" not the same name as image that stored to the folder path. the image name that stored to folder path has no ./images/ only new_name.jpg...
how to display that image? someone tried that? help!
You need to explode image name from "./images/new_name.jpg".
$image_arr = explode("/", "./images/new_name.jpg");
echo $image_name = end($image_arr);
we used codeigniter upload library
$this->load->library('image_lib');
$config = array(
'upload_path' => APPPATH."upload/folder",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000"
);
$this->load->library('upload', $config);
$this->upload->do_upload('pic');
You need img HTML tag:
<img src="<?php echo base_url('images/' . $row->image);?>">
Try this
On view
<?php foreach ($this->b->getalldata() as $row) {
echo '<li>'.
'<a class="ns-img" href="#">'.base_url().'images/'.$row->image.'</a>'.
'<div class="caption">'.$row->title.'</div>'.
'</li>';
} ?>
You have error here .base_url("images/".$row->image).'n try to use site_url('images').'/'.$row->image
i hope you will get the proper path of your file.

if else in cakePHP not displaying default image

I'm trying to display a default image in cakePHP when the entry for the file path to the image stored in the DB is empty. What I'm finding is happening with the code below, is that if the DB entry is empty the default image is displayed, but it's also displayed if there is an entry in the DB.
So, for some reason if there is an entry in the DB $image is not being displayed. Appreciate the help.
Paul
<?php
$image = $this->Html->image(
$news['News']['imgPath'],
array('title' => $news['News']['alt_tag'], 'class' => 'left'),
array('escape' => false));
$default_image = "<img src=\"/FBCW_new2/files/uploads/default.jpg\" class=\"left\" alt=\"default image\"/>";
if(file_exists("$image")) $filename = $image;
else $filename = $default_image;
echo $filename;
?>
Resolution:
Since $image is an html string, I added a variable to first check if the file path was empty, and then set the $filename by it.
$photo = $news['News']['imgPath'];
$image = $this->Html->image(
$news['News']['imgPath'],
array('title' => $news['News']['alt_tag'], 'class' => 'left'),
array('escape' => false));
$default_image = "<img src=\"/FBCW_new2/files/uploads/default.jpg\" class=\"left\" alt=\"default image\"/>";
if(!empty($photo)) $filename = $image;
else $filename = $default_image;
echo $filename;
You're checking whether $image is a valid file path, but $image holds an HTML string; therefore, file_exists will almost invariably return false. You want to check if the file path is valid:
if(file_exists(APP . WEBROOT_DIR . '/' . $news['News']['imgPath'])){
// ...
}
Note: Depending on where you're storing these images (and how your storing their file paths), you'll likely need to use the APP constant (and others) to check the correct absolute file path.
You might want to create a helper that does image-replacement like this for you, see Helpers - CakePHP Cookbook 2.0.

Delete an image in PHP (WordPress)

I have this code which uploads an image from admin and it works well.
add_action('admin_init', 'register_and_build_fields');
function register_and_build_fields() {
register_setting('theme_options', 'theme_options', 'validate_setting', 'delete_file');
}
function validate_setting($theme_options) {
$keys = array_keys($_FILES); $i = 0; foreach ( $_FILES as $image ) {
// if a files was upload
if ($image['size']) {
// if it is an image
if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) { $override = array('test_form' => false);
$options = get_option('theme_options'); echo "<img src='{$options['logo']}' />";
// save the file, and store an array, containing its location in $file
$file = wp_handle_upload( $image, $override ); $theme_options[$keys[$i]] = $file['url']; } else {
// Not an image.
$options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$logo];
// Die and let the user know that they made a mistake.
wp_die('No image was uploaded or invalid format.<br>Supported formats: jpg, jpeg, png, gif.<br> Go <button onclick="history.back()">Back</button> and try again.'); } } // Else, the user didn't upload a file.
// Retain the image that's already on file.
else { $options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$keys[$i]]; } $i++; }
return $theme_options;
}
and now I want the function to delete the current image.
function delete_file($theme_options) {
if (array_key_exists('delete_file', $_FILES)) {
$image = $_FILES['delete_file'];
if (file_exists($image)) {
unlink($image);
echo 'File '.$image.' has been deleted';
} else {
echo 'Could not delete '.$image.', file does not exist';
}
}
}
I added the button in admin but is doing.. nothing.
I'm building a TemplateOptions in WordPress and now I'm trying to make the logo function to be uploaded and deleted from admin. Like I said, uploading the logo works and now I want to make the field "delete" to work.
I found out that you don't need to insert the record in the DB as you only have a single image and whose name and path are also constant . So you simply need to unlink the image from the directory and it will be deleted, nothing else.
say your logo.png is in your themes's img folder then you should unlink it like this. default is your theme name
$path = ABSPATH.'wp-content/themes/default/img/logo.png';
if(file_exists($path))
{
unlink( $path );
}
Note: Remember that you have to pass the absolute path to the unlink() and not the url having http , because it will give you an error , you can't use http with unlink.

Add File Uploader to Joomla Admin Component

I made Joomla admin component according to Joomla guide - http://docs.joomla.org/Developing_a_Model-View-Controller_Component/2.5/Developing_a_Basic_Component
In that i need to have file uploader which let user to upload single file.
In administrator\components\com_invoicemanager\models\forms\invoicemanager.xml i have defined
<field name="invoice" type="file"/>
In the controller administrator\components\com_invoicemanager\controllers\invoicemanager.php im trying to retrieve that file like below. But its not working (can't retrieve file)
Where am i doing it wrong ?
How can i get file and save it on disk ?
class InvoiceManagerControllerInvoiceManager extends JControllerForm
{
function save(){
$file = JRequest::getVar( 'invoice', '', 'files', 'array' );
var_dump($file);
exit(0);
}
}
make sure that you have included enctype="multipart/form-data" in the form that the file is being submitting. This is a common mistake
/// Get the file data array from the request.
$file = JRequest::getVar( 'Filedata', '', 'files', 'array' );
/// Make the file name safe.
jimport('joomla.filesystem.file');
$file['name'] = JFile::makeSafe($file['name']);
/// Move the uploaded file into a permanent location.
if (isset( $file['name'] )) {
/// Make sure that the full file path is safe.
$filepath = JPath::clean( $somepath.'/'.strtolower( $file['name'] ) );
/// Move the uploaded file.
JFile::upload( $file['tmp_name'], $filepath );}
Think i found the solution :)
$file = JRequest::getVar('jform', null, 'files', 'array');
Saving part is mentioned here - http://docs.joomla.org/Secure_coding_guidelines
For uploading the file from your component, you need to write your code in the controller file and you can extend the save() method. check the code given below -
public function save($data = array(), $key = 'id')
{
// Neccesary libraries and variables
jimport('joomla.filesystem.file');
//Debugging
ini_set("display_error" , 1);
error_reporting(E_ALL);
// Get input object
$jinput = JFactory::getApplication()->input;
// Get posted data
$data = $jinput->get('jform', null, 'raw');
$file = $jinput->files->get('jform');
// renaming the file
$file_ext=explode('.',JFile::makeSafe($file['invoice']['name'])); // invoice - file handler name
$filename = round(microtime(true)) . '.' . strtolower(end($file_ext));
// Move the uploaded file into a permanent location.
if ( $filename != '' ) {
// Make sure that the full file path is safe.
$filepath = JPath::clean( JPATH_ROOT."/media/your_component_name/files/". $filename );
// Move the uploaded file.
if (JFile::upload( $file['invoice']['tmp_name'], $filepath )) {
echo "success :)";
} else {
echo "failed :(";
}
$data['name'] = $filename ; // getting file name
$data['path'] = $filepath ; // getting file path
$data['size'] = $file['invoice']['size'] ; // getting file size
}
JRequest::setVar('jform', $data, 'post');
$return = parent::save($data);
return $return;
}
Joomla 2.5 & 3 style:
$app = JFactory::getApplication();
$input = $app->input;
$file= $input->files->get('file');
if(isset($file['name']))
{
jimport('joomla.filesystem.file');
$file['name'] = strtolower(JFile::makeSafe($file['name']));
$fileRelativePath = '/pathToTheRightFolder/'.$file['name'];
$fileAbsolutePath = JPath::clean( JPATH_ROOT.$fileRelativePath);
JFile::upload( $file['tmp_name'], $fileAbsolutePath );
}
http://docs.joomla.org/How_to_use_the_filesystem_package
has a full upload sample.
Little sample where admin choose the file type or all, enter the users to access the form upload. Folder to upload files in Joomla directory or with absolute path. Only selected users access the form upload.

Categories