Uploading multiple image with different input file in Codeigniter - php

So I have four input files in my forms and I send it on my global $_FILES with the following indices: front,rear,right and left.
I want to upload these using codeigniter image class library. This is my code:
public function upload_to_temp($id, $folder, $tags){
$path = realpath(APPPATH . '../public/resources/temps/' . $folder );
//makes a directory
mkdir($path . '/' . $id, 0700);
//navigate to the newly created path
$path = realpath(APPPATH . '../public/resources/temps/' . $folder . '/' . $id);
if(isset($tags)){
//use these tags to check the files present on submission
foreach($tags as $tag){
if(array_key_exists($tag,$_FILES)){
if(!empty($_FILES) && $_FILES[$tag]["name"] != "" && isset($_FILES[$tag]["name"])){
$config = array (
'source_image' => $_FILES[$tag]["name"],
'image_library' => 'gd',
'upload_path' => $path,
'file_name' => $id . '_' . $tag . '.jpg',
'allowed_types' => 'png|jpg|jpeg',
'overwrite' => TRUE,
'max_size' => '2000',
);
$this->_CI->upload->initialize($config);
if(!$this->_CI->upload->do_upload()){
echo 'Error creating image. ';
echo $this->_CI->upload->display_errors();
}else{
echo 'Success saving to temp folder';
}
//kapag failed
if(!$this->_CI->upload->do_upload()){
echo 'Error creating image.';
echo $this->_CI->upload->display_errors();
}else{
//now, the $path will become our resource path for copying and creating thumbnails.
$resouce_path = $config['upload_path'] . '/' . $config['file_name'];
$this->img_create_thumb($resouce_path, $folder);
}
}else{
//Hindi na dapat marating to!
echo $tag . ' not present ';
}
}else{
//use default pictures
echo $tag . ' not present ';
}
}
}
}
However it gives me the following error:
Error creating image. You did not select a file to upload.Error
creating image.You did not select a file to upload.You did
not select a file to upload.Error creating image. You did not
select a file to upload.Error creating image.You did not select
a file to upload.You did not select a file to upload.right
not present left not present
I think I did not correctly specified which resource on the $_FILES should be uploaded.
Your response would be greatly appreciated.
Thanks

I solved it by supplying the indices in codeigniter's do_upload()
$this->_CI->upload->do_upload($tag);

Related

php Scan function not returning results as expected after moving script path:

note.. all folders chmod set to 777 for testing.
Okay, so i have been trying to design a simple cloud storage file system in php.After users log in they can upload and browse files in their account.
I am having an issue with my php code that scans the user's storage area. I have a script called scan.php that is called to return all of the users files and folders that they saved.
I originally placed the scan script in the directory called files and it worked properly, when the user logged in the scan script scanned the users files using "scan(files/usernamevalue)".
However I decided that I would prefer to move the scan script inside the files area that way the php script would only have to call scan using "scan(usernamevalue)". However now my script does not return the users files and folders.
<?php
session_start();
$userfileloc = $_SESSION["activeuser"];
$dir = $userfileloc;
// Run the recursive function
$response = scan($dir);
// This function scans the files folder recursively, and builds a large array
function scan($dir)
{
$files = array();
// Is there actually such a folder/file?
$i=0;
if(file_exists($dir))
{
foreach(scandir($dir) as $f)
{
if(!$f || $f[0] === '.')
{
continue; // Ignore hidden files
}
if(!is_dir($dir . '/' . $f))
{
// It is a file
$files[] = array
(
"name" => $f,
"type" => "file",
"path" => $dir . '/' . $f,
"size" => filesize($dir . '/' . $f) // Gets the size of this file
);
//testing that code actually finding files
echo "type = file, ";
echo $f .", ";
echo $dir . '/' . $f. ", ";
echo filesize($dir . '/' . $f)." ";
echo"\n";
}
else
{
// The path is a folder
$files[] = array
(
"name" => $f,
"type" => "folder",
"path" => $dir . '/' . $f,
"items" => scan($dir . '/' . $f) // Recursively get the contents of the folder
);
//testing that code actually finding files
echo "type = folder, ";
echo $f .", ";
echo $dir . '/' . $f. ", ";
echo filesize($dir . '/' . $f)." ";
echo"\n";
}
}
}
else
{
echo "dir does not exist";
}
}
// Output the directory listing as JSON
if(!$response)
{ echo"failes to respond \n";}
header('Content-type: application/json');
echo json_encode(array(
"name" => $userfileloc,
"type" => "folder",
"path" => $dire,
"items" => $response
));
?>
As you can see i added i echoed out all of the results to see if there
was any error in the scan process, here is what i get from the output as you
can see the function returns null, but the files are being scanned, i cant
seem to figure out where i am going wrong. Your help would be greatly
appreciated. Thank you.
type = file, HotAirBalloonDash.png, test/HotAirBalloonDash.png, 658616
type = folder, New directory, test/New directory, 4096
type = file, Transparent.png, test/Transparent.png, 213
failes to respond
{"name":"test","type":"folder","path":null,"items":null}
You forgot to return files or folders in scan function, just echo values. That is the reason why you get null values in the response.
Possible solution is to return $files variable in all cases.

Why is this upload file code not working in CakePHP

I have a problem with the upload of files in CakePHP 2.1. In fact, I always have the error:
Column not found: 1054 Unknown column 'Array' in 'field list'.
for the view:
<?php echo $this->Form->create('Ecole',array('enctype' => 'multipart/form-data')); ?>
<?php echo $this->Form->input('Ecole.logo_ecole', array('type'=>'file','class'=>'','label'=>'')); ?>
When I remove array('enctype' => 'multipart/form-data') I don't have the error but the upload don't work either.
For the controller:
if(!empty($this->data))
{
debug($this->data);
$ext = 'jpg';
// Save success
if($this->Ecole->save($this->data))
{
// Destination folder, new filename and destination path
$dest_folder = IMAGES . DS . 'galleries' . DS . $this->Ecole->id;
$new_filename = $this->Ecole->id. '.' .$ext;
$dest_path = $dest_folder . DS . $new_filename;
// Check if destination folder exists and create if it doesn't
if(!is_dir($dest_folder))
{
mkdir($dest_folder, 0755, true);
}
// We move the picture and rename it with his id
if(move_uploaded_file($this->data['Ecole']['logo_ecole']['tmp_name'], $dest_path))
{
// Show success flash message
$this->Session->setFlash(__('Picture successfully added !', true), 'default', array('class' => 'success'));
echo "<script> parent.location.reload(true); parent.jQuery.fancybox.close(); </script>";
}
// Move failed
else
{
// Delete picture
//$this->Ecole->delete($this->Ecole->id);
// Show error flash message
$this->Session->setFlash(__('Error occurred while adding picture !', true), 'default', array('class' => 'error'));
}
}
// Save failed
else
{
// Show error flash message
$this->Session->setFlash(__('Error occurred while adding picture !', true), 'default', array('class' => 'error'));
}
}
Can anyone explain what I'm doing wrong and how to do it right?
to do multipart/form-data, you have to specify it this way with the helper
<?php echo $this->Form->create('Ecole', array('type' => 'file')); ?>
The type can be ‘post’, ‘get’, ‘file’, ‘put’ or ‘delete’. Please see the sections Options for create here in the FormHelper documentation !
It's probably because you're trying to save the array cake generates when uploading a file ($this->data['Ecole']['logo_ecole'] is an array). Are you meaning to save only the filename to the database?
i have modify your code please take a look
and please not remove array('enctype' => 'multipart/form-data') this line in form
<?php
if(!empty($this->data))
{
debug($this->data);
$ext = 'jpg';
// Destination folder, new filename and destination path
$dest_folder = IMAGES . DS . 'galleries' . DS . $this->Ecole->id;
$new_filename = $this->Ecole->id. '.' .$ext;
$dest_path = $dest_folder . DS . $new_filename;
// Check if destination folder exists and create if it doesn't
if(!is_dir($dest_folder))
{
mkdir($dest_folder, 0755, true);
}
$image='';
// We move the picture and rename it with his id
if(move_uploaded_file($this->data['Ecole']['logo_ecole']['tmp_name'], $dest_path))
{
$image = basename($this->data['Ecole']['logo_ecole']['name'])
// Show success flash message
$this->Session->setFlash(__('Picture successfully added !', true), 'default', array('class' => 'success'));
echo "<script> parent.location.reload(true); parent.jQuery.fancybox.close(); </script>";
}else
{
// Delete picture
//$this->Ecole->delete($this->Ecole->id);
// Show error flash message
$this->Session->setFlash(__('Error occurred while adding picture !', true), 'default', array('class' => 'error'));
}
$this->data['Ecole']['logo_ecole'] = $image;
// Save success
if(!$this->Ecole->save($this->data))
{
// Show error flash message
$this->Session->setFlash(__('Error occurred while adding picture !', true), 'default', array('class' => 'error'));
}
}

Create Folder and Insert if Not Present

I wonder whether someone may be able to help me please.
I'm using Aurigma's Image uploader software to allow users to upload images for locations they visit. The information is saved via the script shown below:
<?php
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
//Do not forget about the slash in the end of the folder name.
$galleryPath = 'UploadedFiles/';
require_once 'Includes/gallery_helper.php';
require_once 'ImageUploaderPHP/UploadHandler.class.php';
/**
* FileUploaded callback function
* #param $uploadedFile UploadedFile
*/
function onFileUploaded($uploadedFile) {
$packageFields = $uploadedFile->getPackage()->getPackageFields();
$username=$packageFields["username"];
$locationid=$packageFields["locationid"];
global $galleryPath;
$absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;
$absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR;
if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) {
initGallery($absGalleryPath, $absThumbnailsPath, FALSE);
}
$locationfolder = $_POST['locationid'];
$locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder);
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
$dirName = $_POST['folder'];
$dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $dirName);
if (!is_dir($absGalleryPath . $dirName)) {
mkdir($absGalleryPath . $dirName, 0777);
}
$path = rtrim($dirName, '/\\') . '/';
$originalFileName = $uploadedFile->getSourceName();
$files = $uploadedFile->getConvertedFiles();
// save converter 1
$sourceFileName = getSafeFileName($absGalleryPath, $originalFileName);
$sourceFile = $files[0];
/* #var $sourceFile ConvertedFile */
if ($sourceFile) {
$sourceFile->moveTo($absGalleryPath . $sourceFileName);
}
// save converter 2
$thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName);
$thumbnailFile = $files[1];
/* #var $thumbnailFile ConvertedFile */
if ($thumbnailFile) {
$thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName);
}
//Load XML file which will keep information about files (image dimensions, description, etc).
//XML is used solely for brevity. In real-life application most likely you will use database instead.
$descriptions = new DOMDocument('1.0', 'utf-8');
$descriptions->load($absGalleryPath . 'files.xml');
//Save file info.
$xmlFile = $descriptions->createElement('file');
$xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName);
$xmlFile->setAttribute('source', $sourceFileName);
$xmlFile->setAttribute('size', $uploadedFile->getSourceSize());
$xmlFile->setAttribute('originalname', $originalFileName);
$xmlFile->setAttribute('thumbnail', $thumbnailFileName);
$xmlFile->setAttribute('description', $uploadedFile->getDescription());
//Add additional fields
$xmlFile->setAttribute('username', $username);
$xmlFile->setAttribute('locationid', $locationid);
$xmlFile->setAttribute('folder', $dirName);
$descriptions->documentElement->appendChild($xmlFile);
$descriptions->save($absGalleryPath . 'files.xml');
}
$uh = new UploadHandler();
$uh->setFileUploadedCallback('onFileUploaded');
$uh->processRequest();
?>
In additon to the original script I've added code that creates a folder, with it's name based on the current 'locationid'. This is shown below.
$locationfolder = $_POST['locationid'];
$locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder);
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
What I like to incorporate, is a check that looks to see whether there is a folder already setup with the current 'locationid' value, if not create the folder. I'm ceratianly no expert in PHP, but I know that to check to see whether a file exists, the if(file exists....) can be used, but I just wondered whether someone could tell me please how I can implement this check for the folder name?
Many thanks
Chris
I think is_dir() is what you are looking for.
UPDATE:
The code you have:
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
Does exactly what you want. It checks for the folder and if it does not exist then it creates one for you (with CHMOD 777). Don't see what your question is then...

Save 'Username' as Filename

I wonder whether someone could help me please.
I'm using Image Uploader from Aurigma, and to save the uploaded images, I've put this script together.
<?php
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
//Do not forget about the slash in the end of the folder name.
$galleryPath = 'UploadedFiles/';
require_once 'Includes/gallery_helper.php';
require_once 'ImageUploaderPHP/UploadHandler.class.php';
/**
* FileUploaded callback function
* #param $uploadedFile UploadedFile
*/
function onFileUploaded($uploadedFile) {
$packageFields = $uploadedFile->getPackage()->getPackageFields();
$userid = $packageFields["userid"];
$locationid= $packageFields["locationid"];
global $galleryPath;
$absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;
$absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR;
if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) {
initGallery($absGalleryPath, $absThumbnailsPath, FALSE);
}
$dirName = $_POST['folder'];
$dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $dirName);
if (!is_dir($absGalleryPath . $dirName)) {
mkdir($absGalleryPath . $dirName, 0777);
}
$path = rtrim($dirName, '/\\') . '/';
$originalFileName = $uploadedFile->getSourceName();
$files = $uploadedFile->getConvertedFiles();
// save converter 1
$sourceFileName = getSafeFileName($absGalleryPath, $originalFileName);
$sourceFile = $files[0];
/* #var $sourceFile ConvertedFile */
if ($sourceFile) {
$sourceFile->moveTo($absGalleryPath . $sourceFileName);
}
// save converter 2
$thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName);
$thumbnailFile = $files[1];
/* #var $thumbnailFile ConvertedFile */
if ($thumbnailFile) {
$thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName);
}
//Load XML file which will keep information about files (image dimensions, description, etc).
//XML is used solely for brevity. In real-life application most likely you will use database instead.
$descriptions = new DOMDocument('1.0', 'utf-8');
$descriptions->load($absGalleryPath . 'files.xml');
//Save file info.
$xmlFile = $descriptions->createElement('file');
$xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName);
$xmlFile->setAttribute('source', $sourceFileName);
$xmlFile->setAttribute('size', $uploadedFile->getSourceSize());
$xmlFile->setAttribute('originalname', $originalFileName);
$xmlFile->setAttribute('thumbnail', $thumbnailFileName);
$xmlFile->setAttribute('description', $uploadedFile->getDescription());
//Add additional fields
$xmlFile->setAttribute('userid', $userid);
$xmlFile->setAttribute('locationid', $locationid);
$xmlFile->setAttribute('folder', $dirName);
$descriptions->documentElement->appendChild($xmlFile);
$descriptions->save($absGalleryPath . 'files.xml');
}
$uh = new UploadHandler();
$uh->setFileUploadedCallback('onFileUploaded');
$uh->processRequest();
?>
What I'd like to do is replace the files element of the filename and replace it with the username, so each saved folder and associated files can be indentified to each user.
I've added a username text field to the form which this script saves from
I think I'm right in saying that this is line that needs to change $descriptions->save($absGalleryPath . 'files.xml');.
So amongst many attempts I've tried changing this to $descriptions->save($absGalleryPath . '$username.xml, $descriptions->save($absGalleryPath . $username '.xml, but none of these have worked, so I'm not quite sure what I need to change.
I just wondered whether someone could perhaps have a look at this please and let me know where I'm going wrong.
Many thanks
'$username.xml' will be interpreted as $username.xml, you need to use "$username.xml". Single quotes "disable" the variable use inside strings.
What you are tryiing can be a bad idea, as you are making so a username can't contain 'special characters' like "/". Perhaps is not a problem if you aready have a rule that stop "/" being part of a username.

How do I set relative paths in PHP?

I have an absolute path of (verified working)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
for use in
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
However when I move to a production server I need a relative path:
If /archemarks is at the root directory of your server, then this is the correct path. However, it is often better to do something like this:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
This takes the directory in which the current file is running, and saves the image into a directory called images that is at the same level as it.
In the above case, the currently running file might be:
/var/www/archemarks/include/upload.php
The image directory is:
/var/www/archemarks/images
For example, if /images was two directory levels higher than the current file is running in, use
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
notice the first "/"
/ => absolute, like /home
no "/" => relative to current folder
That is an absolute path. Relative paths do not begin with a /.
If this is the correct path for you on the production server, then PHP may be running in a chroot. This is a server configuration issue.
Assuming the /archemarks directory is directly below document root - and your example suggests that it is -, you could make the code independent of a specific OS or environment. Try using
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
as a generic path to your target location. Should work fine. This notation is also independent of the location of your script, or the current working directory.
Below is code for a php file uploader I wrote with a relative path.
Hope it helps. In this case, the upload folder is in the same dir as my php file. you can go up a few levels and into a different dir using ../
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
#date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>

Categories