Function not uploading correctly - php

I am trying to upload images to a directory that is defined on input page and passed to the $path variable within the function. Right now it uploads the image in to the same directory as the upload script and not the defined image folder. I have re-worked this several ways the the result is always the same. Both $path and $this->destination remain empty and the image is uploaded to the wrong place. Can anyone else see what I have done wrong?
<?php
//set the max upload size in bytes
$max = 51200;
if(isset($_POST['upload'])){
//define path to the upload directory
$destination = '../../../../image_folder/test/';
require_once('upload.php');
try {
$upload = new Ps2_Upload("$destination");
$upload->move();
$result = $upload->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<body>
<?php
if (isset($result)) {
echo '<ul>';
foreach ($result as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
echo "the place the files will be put is $destination";
?>
<form action="" method="post" enctype="multipart/form-data" id="uploadImage">
<label for="image">Upload New Image</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>" />
<input type="file" name="image" id="image" />
<input type="submit" name="upload" id="upload" value="Upload" />
</form>
</body>
</html>
<?php
class Ps2_Upload {
//protected variables
protected $_uploaded = array();
protected $_destination;
protected $_max = 51200;
protected $_messages = array();
protected $_permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');
protected $_renamed = false;
public function __construct($path){
if(!is_dir($path) || !is_writable($path)){
throw new Exception("$path must be a valid, writable directory.");
}
$this->_destination = $path;
$this->_uploaded = $_FILES;
}
public function move(){
$field = current($this->_uploaded);
$success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
if($success){
$this->_messages[] = $field['name'] . " uploaded successfully to $this->destination";
} else {
$this->_messages[] = 'Could not upload ' . $field['name'];
}
}
public function getMessages() {
return $this->_messages;
}
}
?>

In your constructor, you have this: $this->_destination = $path;
In your move() method, you have this: $success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
your protected variable is _destination but what you are using in the move() method is destination. No underscore before it. Work on that, might solve your problem:
$success = move_uploaded_file($field['tmp_name'], $this->_destination . $field['name']);
Should work.

$success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
should be
$success = move_uploaded_file($field['tmp_name'], $this->_destination . $field['name']);
note that you have a typo in $this->destination, and it should be $this->_destination

Related

Code: 403 Value: This request is not authorized to perform this operation. details (if any): AuthorizationFailure

I get "Fail: Code: 403 Value: This request is not authorized to perform this operation. details (if any): AuthorizationFailureThis request is not authorized to perform this operation. RequestId:a433a473-e01e-005a-2fa7-30f90a000000 Time:2020-05-23T02:12:36.6988696Z." error. Please see my code below.
require_once 'vendor/autoload.php';
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Blob\BlobSharedAccessSignatureHelper;
use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions;
use MicrosoftAzure\Storage\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Common\Exceptions\InvalidArgumentTypeException;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\StorageServiceSettings;
use MicrosoftAzure\Storage\Common\Models\Range;
use MicrosoftAzure\Storage\Common\Models\Logging;
use MicrosoftAzure\Storage\Common\Models\Metrics;
use MicrosoftAzure\Storage\Common\Models\RetentionPolicy;
use MicrosoftAzure\Storage\Common\Models\ServiceProperties;
use MicrosoftAzure\Storage\Blob\Models\Block;
use MicrosoftAzure\Storage\Blob\Models\BlockList;
use MicrosoftAzure\Storage\Blob\Models\BlobBlockType;
$blobendpoint = "<Blob service SAS URL>"
$connectionString = "BlobEndpoint=".$blobendpoint.";SharedAccessSignature=sv=2019-10-10&ss=bfqt&srt=sco&sp=rwdlacupx&se=2020-06-06T08:58:51Z&st=2020-05-23T00:58:51Z&sip=52.175.254.10&spr=https,http&sig=<Signature>";
$containerName = "samples";
$blobRestProxy = BlobRestProxy::createBlobService($connectionString);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$file_name = $_FILES["resFile"]["name"];
$blob_name = basename($file_name);
$block_list = new BlockList();
define('CHUNK_SIZE', 4 * 1024 * 1024);
try {
$fptr = fopen($file_name, "rb");
$index = 1;
while (!feof($fptr)) {
$block_id = base64_encode(str_pad($index, 6, "0", STR_PAD_LEFT));
$block_list->addUncommittedEntry($block_id);
$data = fread($fptr, CHUNK_SIZE);
$blobRestProxy->createBlobBlock($containerName, $blob_name, $block_id, $data);
++$index;
}
echo "Index :".$index;
$blobRestProxy->commitBlobBlocks($containerName, $blob_name, $block_list);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
?>
<form action="fileuploadblock.php" method="POST" enctype="multipart/form-data">
<input type="file" class="btn btn-default" name="resFile" id="resFile" value="" />
<input type="submit" class="btn btn-default" name = "share "value="Submit" data-inline="true"/>
</form>
Edit:
After removing the IP from SAS I get different error :The value for one of the HTTP headers is not in the correct format. details (if any): InvalidHeaderValueThe value for one of the HTTP headers is not in the correct format. RequestId:cdb1b3c1-b01e-0078-29fd-303c15000000 Time:2020-05-23T12:28:57.6060563ZContent-Length0.
This is the New $connectionString
BlobEndpoint=https://<account>.blob.core.windows.net/;SharedAccessSignature=sv=2019-10-10&ss=bfqt&srt=sco&sp=rwdlacupx&se=2020-05-23T20:17:23Z&st=2020-05-23T12:17:23Z&spr=https,http&sig=<SignatureValue>
I was sending the empty data from file upload.. now I am storing the data in the hosting server and uploading in to the blob..
require_once 'vendor/autoload.php';
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Blob\BlobSharedAccessSignatureHelper;
use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions;
use MicrosoftAzure\Storage\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Common\Exceptions\InvalidArgumentTypeException;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\StorageServiceSettings;
use MicrosoftAzure\Storage\Common\Models\Range;
use MicrosoftAzure\Storage\Common\Models\Logging;
use MicrosoftAzure\Storage\Common\Models\Metrics;
use MicrosoftAzure\Storage\Common\Models\RetentionPolicy;
use MicrosoftAzure\Storage\Common\Models\ServiceProperties;
use MicrosoftAzure\Storage\Blob\Models\Block;
use MicrosoftAzure\Storage\Blob\Models\BlockList;
use MicrosoftAzure\Storage\Blob\Models\BlobBlockType;
$connectionString = "BlobEndpoint=https://<account>.blob.core.windows.net/;SharedAccessSignature=sv=2019-10-10&ss=bfqt&srt=sco&sp=rwdlacupx&se=2021-05-26T17:39:04Z&st=2020-05-27T09:39:04Z&spr=https,http&sig=<Signature>";
$containerName = "samples";
$blobRestProxy = BlobRestProxy::createBlobService($connectionString);
/*****************Upload file to hosting ********/
function uploadFile($fieldName, $fileType)
{
$flg = 0;
$MaxID = "";
$ext = "";
$uploadfile = "";
if (isset($fieldName) AND $fieldName['name'] != '')
{
$flg = 1;
$allowed_filetypes = $fileType;
$max_filesize = 40548576;
$filename = $fieldName['name'];
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if($ext==".xlsx")
$ext=".xls";
if (!in_array($ext, $allowed_filetypes))
echo "<h1>The file you attempted to upload is not allowed...</h1>";
else if (filesize($fieldName['tmp_name']) > $max_filesize)
echo "<h1>The file you attempted to upload is too large...</h1>";
else
{
$uploadfile = $filename;//$MaxID . $ext;
if (move_uploaded_file($fieldName['tmp_name'], $uploadfile) == FALSE)
{
echo "<h1>Error in Uploading File...</h1>";
$MaxID = "";
}
else
$MaxID = $filename;
echo "file uploaded success!!";
}
}
return $MaxID;
}
/***************************************/
if(isset($_POST['share']))
{
if($_FILES['resFile']['name']!="")
{
$file_name=uploadFile($_FILES['resFile'],array(".xls",".xlsx",".csv"));
}
if ($file_name != '')
{
$blob_name = basename($file_name);
$block_list = new BlockList();
define('CHUNK_SIZE', 1 * 1024 * 1024);
try {
$fptr = fopen($file_name, "rb");
$index = 1;
while (!feof($fptr)) {
$block_id = base64_encode(str_pad($index, 6, "0", STR_PAD_LEFT));
$block_list->addUncommittedEntry($block_id);
$data = fread($fptr, CHUNK_SIZE);
//echo "Data :".$block_id;
$blobRestProxy->createBlobBlock($containerName, $blob_name, $block_id, $data);
//echo "ID :".$block_id;
++$index;
}
$blobRestProxy->commitBlobBlocks($containerName, $blob_name, $block_list);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo "Error Code :".$code."Error Message : ".$error_message."<br />";
}
}
else
{
echo " No file selected";
}
}
?>
<html lang="en">
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="upload_excel"
enctype="multipart/form-data">
<input type="file" class="btn btn-default" name="resFile" id="resFile" value="" />
<input type="submit" class="btn btn-default" name = "share" value="Submit" data-
inline="true"/>
<!--<div id="res"></div>-->
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</body>
</html>

Multiple file upload method in PHP OOP

I am trying to build a method in PHP to upload multiple files into and insert the files names into a MySQL database.
I am trying to build this based on PHP OOP.
Multiple issues I am facing and I have been stucking with this for more than 2 weeks.
First: the method is only inserting 1 row into the database even if I selected multiple files in the form.
Second: the method is not getting the files name, so even if it inserts only 1 row, it inserts an empty row.
Here is the images class:
<?php
class Images extends Crud{
protected static $db_table = "images";
protected static $table_fields = array("id", "image_url", "property_id", "date");
public $id;
public $image_url;
public $property_id;
public $date;
public $filename;
public $tmp_path = array();
public $upload_dir = "images";
public $errors = array();
public $upload_errors_array = array(
UPLOAD_ERR_OK => "There is no error.",
UPLOAD_ERR_INI_SIZE => "The file size exceeds the upload_max_filesize",
UPLOAD_ERR_FORM_SIZE => "The file upload exceeds the MAX_FILE_SIZE",
UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded",
UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder",
UPLOAD_ERR_CANT_WRITE => "Failed to write file on desk",
UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload"
);
public function image_path(){
return $this->upload_dir.DS.$this->image_url;
}
public function set_files($file){
if(empty($file) || !$file || !is_array($file)){
$this->errors[] = "There was no file uploaded here";
return false;
}else{
$this->image_url = $file['name'];
$this->tmp_path = $file['tmp_name'];
}
}
public function new_images(){
foreach ($_FILES['images'] as $file) {
$this->set_files($file);
$this->property_id = "1";
$this->date = date('Y-m-d H:i:s');
$target_path = $this->upload_dir . DS . $this->image_url;
move_uploaded_file($this->tmp_path, $target_path);
if($this->create()){
print_r($file);
var_dump($file);
return true;
}
}
}
}
?>
print_r is showing the following:
Array ( [0] => download (1).jpg [1] => download (2).jpg [2] => download (3).jpg [3] => download.jpg )
and var_dump is showing the following:
array(4) { [0]=> string(16) "download (1).jpg" [1]=> string(16) "download (2).jpg" [2]=> string(16) "download (3).jpg" [3]=> string(12) "download.jpg" }
More details:
Here is the main class which the images class extends from:
<?php
class Crud{
protected static $db_table;
public static function find(){
return static::find_query("SELECT * FROM " . static::$db_table . "");
}
public static function find_limit($limit){
return static::find_query("SELECT * FROM " . static::$db_table . " LIMIT " . $limit. "");
}
public static function find_id($id){
global $database;
$the_result_array = static::find_query("SELECT * FROM " . static::$db_table . " WHERE id='$id'");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function find_query($sql){
global $database;
$set_result = $database->query($sql);
$object_array = array();
while($rows = mysqli_fetch_array($set_result)){
$object_array[] = static::instantiation($rows);
}
return $object_array;
}
public static function instantiation($records){
$calling_class = get_called_class();
$object = new $calling_class;
foreach ($records as $attribute => $value) {
if($object->has_attribute($attribute)){
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute){
$object_properties = get_object_vars($this);
return array_key_exists($attribute, $object_properties);
}
protected function properties(){
$properties = array();
foreach (static::$table_fields as $field){
if(property_exists($this, $field)){
$properties[$field] = $this->$field;
}
}
return $properties;
}
protected function clean_properties(){
global $database;
$clean_properties = array();
foreach ($this->properties() as $key => $value) {
$clean_properties[$key] = $database->escape_string($value);
}
return $clean_properties;
}
public function create(){
global $database;
$properties = $this->clean_properties();
$sql = "INSERT INTO ".static::$db_table."(". implode(",", array_keys($properties)).")";
$sql .= "VALUES ('". implode("','", array_values($properties)) ."')";
if($database->query($sql)){
$this->id = $database->last_id();
print_r($sql);
var_dump($sql);
return true;
}else{
return false;
}
}
}
?>
print_r is showing the following result:
INSERT INTO images(id,image_url,property_id,date)VALUES ('','','1','2017-10-20 20:24:05')
var_dump is showing the follwoing:
string(89) "INSERT INTO images(id,image_url,property_id,date)VALUES ('','','1','2017-10-20 20:24:05')"
Furthermore, here is the HTML page:
<?php include_once "admin/head.php"; ?>
<?php if(!$session->is_signed_in()) {redirect("../index");} ?>
<?php
if(isset($_POST['submit'])){
$images = new Images();
$images->new_images();
}
?>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6">
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="images" class="control-label">نص الصورة البديل</label>
<input type="file" class="form-control" name="images[]" id="images" multiple="">
</div>
<input type="submit" name="submit" value="Submit" class="btn btn-primary">
</form>
</div>
</div>
</div>
<?php include "admin/footer.php"; ?>
Your loop through $_FILES['images'] is wrong. Each element of this is not all the properties for a single file. Each element is a different property, which contains an array of those properties of all the uploads. E.g. $_FILES['images']['name'] is an array of all the names. So you need to loop through one of these properties, and then get the corresponding elements of the other properties.
foreach ($_FILES['images']['name'] as $index => $name) {
$file = array('name' => $name, 'tmp_name' => $_FILES['images']['tmp_name'][$index]);
$this->set_files($file);
...
}

how to import data from csv file into the database?

controller:
public function student()
{
if($this->input->post('save'))
{
$client_id[0]['client_id'] = $this->session->userdata('client_id');
$radio = $this->input->post('class');
$client = $client_id[0]['client_id'];
$filename = $_FILES['students_list']['name'];
$path = base_url()."resources/imported_file/".$filename;
$path = FCPATH."resources/imported_file/";
$move=move_uploaded_file($_FILES['students_list']['tmp_name'],$path.$_FILES['students_list']['name']);
if($_FILES["students_list"]["size"] > 0)
{
$file = fopen($path, "r");
while (($importdata = fgetcsv($file, 10000, ",")) !== FALSE)
{
$data = array(
'name' => $importdata[0],
'email' =>$importdata[1],
'phone' =>$importdata[2],
'uploaded_date' => date('d-m-y'),
'session' => date('Y'),
'client_id' => $client[0]['client_id'],
'class' => $radio
);
$this->partner_model->insertCSV($data);
echo $this->db->last_query();
}
fclose($file);
$this->session->set_flashdata('err_csv', '<p style="color: #87b87f;font-weight: bold;text-align:center;">Data are imported successfully..</p>');
}
else
{
$this->session->set_flashdata('err_csv', '<p style="color: red;font-weight: bold;text-align:center;">Something went wrong..</p>');
}
}
}
view:
<?php echo $this->session->flashdata('err_csv')?>
<form class="form-horizontal" method="post" role="form" enctype="multipart/form-data">
<input type="radio" name="class" value="11th"/><b>XI</b>
<input type="radio" name="class" value="12th Appearing"/><b>XII Appearing</b>
<input type="radio" name="class" value="12th Passed"/><b>XII Passed</b>
<input type="file" id="students_list" name="students_list" accept=".csv" class="required">
<input type="submit" name="save" id="save" value="save" class="btn btn-info" />
</form>
model:
<?php
class Partner_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function insertCSV($data)
{
$this->db->insert('students', $data);
return TRUE;
}
}
In this code I have an input having name student_list where I am uploading only csv file. Now, I want to import data from csv file into database but right now it can't work. So, How can I do this ? Please help me.
Thank You
Unless you have some compelling reason to perform the import in code, I suggest you look at Pentaho (https://sourceforge.net/projects/pentaho/), which can upload data from a csv file to most popular databases.
Hey you need to add the library csvReader in your project and use the below code to setup this helps you lot
public function student(){
$this->load->library('CSVReader');
if (isset($_FILES['csv']))
{
if($_FILES["csv"]["error"] > 0)
{ //if there was an error uploading the file
$this->session->set_flashdata('bulkUploadError', 'Invalid CSV File.');
redirect('/');
}
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "csv" . date('m-d-Y') . ".xls";
move_uploaded_file($_FILES["csv"]["tmp_name"], realpath(dirname(__FILE__) . '/../../..') . "/uploads/" . $storagename);
if ($file = fopen(realpath(dirname(__FILE__) . '/../../..') . "/uploads/" . $storagename, 'r+'))
{
$result = $this->csvreader->parse_file('uploads/' . $storagename);
$finalResult = $array = array_values(array_filter($result));
$this->data['worksheet'] = $finalResult;
foreach ($this->data['worksheet'] AS $key => $val)
{
$data['id'] = $val['table field name'];
$this->common->save('table_name',$data);
}
}
}
}
You can use PHPExcel to fetch data and insert it to database:
https://github.com/PHPOffice/PHPExcel
<?php
$target_dir = "/tmp/";
$target_file = $target_dir . basename($_FILES["students_list"]["name"]);
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
$filename = $_FILES["students_list"]["name"];
if (isset($_FILES["students_list"])) {
if($FileType == "csv" ) {
if (move_uploaded_file($_FILES["students_list"]["tmp_name"], $target_file)) {
$target_file = $target_dir . $filename;
set_include_path(get_include_path() . PATH_SEPARATOR . 'resources/imported_file/');
include 'PHPExcel/IOFactory.php';
try {
$objPHPExcel = PHPExcel_IOFactory::load($target_file);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($filename,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$name = trim($allDataInSheet[$i]["A"]);
$email = trim($allDataInSheet[$i]["B"]);
$phone = trim($allDataInSheet[$i]["C"]);
$uploaded_date = trim($allDataInSheet[$i]["D"]);
$session = trim($allDataInSheet[$i]["E"]);
$client_id = trim($allDataInSheet[$i]["F"]);
$class = trim($allDataInSheet[$i]["G"]);
$insert = $db->Queryinsert("students",array('',$name,$email,$phone,$uploaded_date,$session,$client_id,$class));
}
}
}
}
?>
This sample helps you to get data from csv file as row by row and after row 1 that involves column title, you try to get other rows then insert them to database.
In top of script i am saving file in /tmp/ folder and then doing needed actions.
You must set your own folder directions and needed Codeigniter syntaxes in this snippet.

How to upload Multiple images at a time with single button in Zend Framework 1.12?

This is my Controller
Image Controller:
class Admin_xxxxController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->layout()->setLayout('admin');
if ($this->_helper->FlashMessenger->hasMessages()) {
$messages = $this->_helper->FlashMessenger->getMessages();
$this->view->messages = $messages[0];
}
}
public function preDispatch()
{
if(!Zend_Auth::getInstance()->hasIdentity()) {
if ('login' != $this->getRequest()->getActionName()) {
$this->_helper->redirector('index','login');
} else {
}
}
parent::preDispatch();
}
public function saveAction()
{
try {
if(isset($_POST['submit'])) {
$i=0;
$lmgdata=array();
foreach($_FILES as $k=>$v){
$post=$this->_request->getPost();
$path = "images/landimages";
$thumb="images/landimages/thumbnails";
if(!is_dir($path)){ // to check is folder exist or not
mkdir($path,'0777',true);
}
if(!is_dir($thumb)){ // to check is folder exist or not
mkdir($thumb,'0777',true);
}
$maxWidth="600"; $maxHeidht="500";$thumbwidth="100";$thumbheidht="75";
list($width,$height,$y) = getimagesize($v['tmp_name'][$i]);
$scale = min($maxWidth/$width, $maxHeidht/$height);
$scale1 = min($thumbwidth/$width, $thumbheidht/$height);
$s1=$v['name'][$i]; $destpath = $path.'/'.$s1; $thumbpath = $thumb.'/'.$s1;
if(move_uploaded_file($v['tmp_name'][$i],$destpath)){
//$this->resize($thumbpath, $destpath,$width, $height,$scale1,1);
$this->resize($destpath, $destpath,$width, $height,$scale,0 );
$lmgdata[$i]['lm_image']=$s1; // to save new image name in db
}else{
echo "not uploaded"; die();
}
$i++;
}
}
$post=$this->_request->getPost();
$data=array();
if($post['land_id'])
$data['land_id']=$post['land_id'];
$mapper= new Application_Model_xxxMapper();
$lmmapper= new Application_Model_yyyMapper();
if($lid = $mapper->save($data)){
$lmmapper->save($lmgdata, $lid);
$this->_helper->FlashMessenger(array('success'=>'xxx added Sucessfully'));
}else{
$this->_helper->FlashMessenger(array('failed'=>'xxx not added ,please try again'));
}
$this->_helper->redirector('index','xxxx','admin');
}
catch(Zend_Db_Exception $e)
{
echo $e->getMessage();
}
}
This is my add form where I upload multiple images
Add form:
<form action="<?php echo $this->url(array('controller'=>'lands','action'=>'save'),'admin',true);?>" method="post" enctype="multipart/form-data">
Upload Images:<input type="file" multiple name="land_image[]" id="land_image" class="form-control" autocomplete="off" title="">
I used for loop in controller to save multiple images and When I tried to upload multiple images and submit in add form. Only 1 image is getting save and that too only the thumnail is saved. How to get all the images saved
Your loop should look as follows:
foreach($_FILES['land_image']['tmp_name'] as $key => $tmp_name) {
$fileName = $_FILES['land_image']['name'][$key];
$fileSize = $_FILES['land_image']['size'][$key];
$fileTmp = $_FILES['land_image']['tmp_name'][$key];
$fileType = $_FILES['land_image']['type'][$key];
...
}
The answer is not relevant to the question asked. I will answer to my question:
public function saveAction($lmgdata)
{
try{
if(isset($_POST['submit']))
{ $i = 0;
foreach($_FILES as $k=>$v){
// to test is form submited or not
$post=$this->_request->getPost(); // get post result
$data=array(); // create an array to stroe posted details
$data['land_id']=$_SESSION['lid'];
//$data['lm_order']=$post['lm_order'];
/* below code for create a directory */
$path = "/propladder/public/images/landimages";
$thumb="/propladder/public/images/landimages/thumbnails";
if(!is_dir($path)){ // to check is folder exist or not
mkdir($path,'0755',true);
}
if(!is_dir($thumb)){ // to check is folder exist or not
mkdir($thumb,'0755',true);
}
/* below code for uploading in property image */
$maxWidth="600";
$maxHeidht="500";
list($width,$height,$y) = getimagesize($v['tmp_name'][$i]);
$scale = min($maxWidth/$width, $maxHeidht/$height);
$thumbwidth="100";
$thumbheidht="75";
$scale1 = min($thumbwidth/$width, $thumbheidht/$height);
$s1=$v['name'][$i];
$destpath = $path.'/'.$s1; // this is image fulll path
$thumbpath = $thumb.'/'.$s1; // this is image fulll path
if(move_uploaded_file($v['tmp_name'][$i],$destpath)){ // to upload image to destination
$this->resize($thumbpath, $destpath,$width, $height,$scale1,1);
$this->resize($destpath, $destpath,$width, $height,$scale,0 );
$data['lm_image']=$s1; // to save new image name in db
}else{
echo "not uploaded"; die();
}
$mapper=new Application_Model_xxxxMapper();
if($mapper->save($data)){
$this->_helper->FlashMessenger(array('success'=>'xxxx added sucessfully'));
}else{
$this->_helper->FlashMessenger(array('failed'=>'xxxx not added ,Try again'));
}
$i++;
}
} // end is post
//$this->_helper->redirector('index','xxxx','admin');
}catch(Zend_Db_Exception $e){
echo $e->getMessage();
}
}

Multiple upload and resize class.upload.php

I'm trying to upload multiple image to the server and to make different resolution version of each image.
To do this I'm using class.upload.php for the first time. http://www.verot.net/php_class_upload.htm
I look at the documentation and starting from the demo example http://www.verot.net/php_class_upload_download_zip.htm
I made a form with multiple input
<form name="form3" enctype="multipart/form-data" method="post" action="upload.php">
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p class="button"><input type="hidden" name="action" value="multiple" />
<input type="submit" name="Submit" value="upload" /></p>
</form>
the original php from the example only upload the image without resizing them:
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
// now we can loop through $files, and feed each element to the class
foreach ($files as $file) {
// we instanciate the class for each element of $file
$handle = new Upload($file);
// then we check if the file has been uploaded properly
// in its *temporary* location in the server (often, it is /tmp)
if ($handle->uploaded) {
// now, we start the upload 'process'. That is, to copy the uploaded file
// from its temporary location to the wanted location
// It could be something like $handle->Process('/home/www/my_uploads/');
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
echo 'ok';
} else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
} else {
// if we're here, the upload file failed for some reasons
// i.e. the server didn't receive the file
echo ' Error: ' . $handle->error . '';
}
}
What I'd like to do is to process each file inside the if ($handle->processed) {}
so I took the function form the example that resize img and paste it inside the if ($handle->processed) {} part. Now it look like this:
if ($handle->uploaded) {
// now, we start the upload 'process'. That is, to copy the uploaded file
// from its temporary location to the wanted location
// It could be something like $handle->Process('/home/www/my_uploads/');
// now, we start a serie of processes, with different parameters
// we use a little function TestProcess() to avoid repeting the same code too many times
function TestProcess(&$handle, $title) {
global $dir_pics, $dir_dest;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
echo 'ok';
} else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
}
if (!file_exists($dir_dest)) mkdir($dir_dest);
// ----------- save the uploaded img adding _xl to the name
$handle->file_name_body_add = '_xl';
$handle->file_overwrite = true;
TestProcess($handle, 'File originale', '');
// ----------- save the uploaded img adding _l to the name and downsizing it
$handle->file_name_body_add = '_l';
$handle->image_resize = true;
$handle->image_ratio_y = true;
$handle->image_x = 1024;
$handle->file_overwrite = true;
TestProcess($handle, 'Ridimensionato a 1024px');
}
At this point the script works fine only with the first img.
it not make the "foreach ($files as $file)" trow the $files array...
could you help my find where the error is?
thaks
Daniele
Creator of the class here... You need to change the $files array first, as following. It is in the FAQ:
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
Okay, so i tried to use verot's answer but i got ALOT of errors, i tried other answers around the web.
Here is the working solution.
$placeDir = $_SERVER['DOCUMENT_ROOT'] . '/myuploadfolder';
$files = [];
foreach ($_FILES['image_field']['name'] as $key => $value) {
if(!empty($_FILES['image_field']['name'][$key])){
$name = $_FILES['image_field']['name'][$key];
$type = $_FILES['image_field']['type'][$key];
$tmp = $_FILES['image_field']['tmp_name'][$key];
$error = $_FILES['image_field']['error'][$key];
$size = $_FILES['image_field']['size'][$key];
$files[] = [
'name' => $name
, 'type' => $type
, 'tmp_name' => $tmp
, 'error' => $error
, 'size' => $size
];
}
}
foreach($files as $file){
$image = new uploadHelper($file);
$image->allowed = array('image/*');
if ($image->uploaded) {
$image->process($placeDir);
if ($image->processed) {
echo 'image done';
$image->clean();
} else {
echo 'error : ' . $image->error;
}
} else {
echo '<h1>IMAGE NOT UPLOADED</H1>';
}
}
I really hope this helps people out there.

Categories