In my database I have a varchar field to save the path include the name of an imagefile. In my viewscript I also use this field. If I insert for a test a pathname in my database via phpadmin everything works fine.
If I use my Controller addAction I can´t save the path, without error.
Here is my addAction:
$form = new Application_Form_Buch();
$form->submit->setLabel('Add');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$autor = $form->getValue('autor');
$verlag = $form->getValue('verlag');
$titel = $form->getValue('titel');
if( $form->getElement('datei')->receive() <> 1)
{
echo ' filename: '. $form->getElement('datei')->receive();
$imagepath = $form->getElement('datei')->getFileName();
//echo ' filename: '. $form->getElement('datei')->getFileName();
$pathparts = pathinfo($form->getElement('datei')->getFileName());
//echo ' pathparts: '. $pathparts;
//then get the part that you want to use
$originalFilename = $pathparts['basename'];
//echo ' originalFilename: '. $originalFilename;
//echo ' Test basename: '. $originalFilename['basename'];
$form->getElement('datei')->addFilter('Rename','images' ); //'/images/upload/',$originalFilename
//rename funktioniert so nicht
$originalFilename = $pathparts['basename'];
$imagepath=$form->getElement('datei')->getFileName();
$imagepath = str_replace($imagepath, "/images/cover/".$originalFilename, $imagepath); //funktioniert !!!
//echo ' imagepath: '. $imagepath;
$books = new Application_Model_DbTable_Bibliothek();
$books->addBook( $autor, $titel, $verlag, $imagepath );
}
else{
$imagepath=NULL;
}
// $this->_helper->redirector('index');
} else {
$form->populate($formData);
}
}
Please don´t mind I tried a bit around, so I have some comments left. I tested the variable $imagepath and it delivers the wanted value, which is: /images/cover/imagename.jpg. Where is the error in this pathvalue?
And here is my add Function which I use to store in my database:
public function addBook($autor, $titel, $verlag, $pfad)
{
$data = array(
'autor' => $autor,
'titel' => $titel,
'verlag' => $verlag,
'pfad' => $pfad,
);
$this->insert($data);
}
It works quite fine, it saves all comming data instead of the $pfad variable.
NEW:
must be something with the format of $imagepath, I just added for testing: $imagepath= '/images/cover/Labyrinth_200.jpg'; and find the value in my database table. So the error should be in the format of getting the value of $imagepath.
I just found my (very stupid) error.
I changed the blocks in my control structure like following:
if( $form->getElement('datei')->receive() <> 1)
{
$imagepath=NULL;
}
else{
echo ' filename: '. $form->getElement('datei')->receive();
$imagepath = $form->getElement('datei')->getFileName();
//echo ' filename: '. $form->getElement('datei')->getFileName();
$pathparts = pathinfo($form->getElement('datei')->getFileName());
//echo ' pathparts: '. $pathparts;
//then get the part that you want to use
$originalFilename = $pathparts['basename'];
//echo ' originalFilename: '. $originalFilename;
//echo ' Test basename: '. $originalFilename['basename'];
$form->getElement('datei')->addFilter('Rename','images' ); //'/images/upload/',$originalFilename
//rename funktioniert so nicht
$originalFilename = $pathparts['basename'];
$imagepath=$form->getElement('datei')->getFileName();
$imagepath = str_replace($imagepath, "/images/cover/".$originalFilename, $imagepath); //funktioniert !!!
//echo ' imagepath: '. $imagepath;
}
//$imagepath= '/images/cover/Labyrinth_200.jpg';
$books = new Application_Model_DbTable_Bibliothek();
$books->addBook( $autor, $titel, $verlag, $imagepath );
Before that I tried if( $form->getElement('datei')->receive() = 1) to validate my condition. But I got an error. So I switched the two blocks and now it works.
Related
I'm trying to import CSV file to the database using yii2 framework.
Controller
public function actionIndex($message=””)
{
// $model = new ProjectDocument;
//error_reporting(E_ALL);
//ini_set('display_error', 1);
$model = new ProjectDocument();
if ($model->load(Yii::$app->request->post()) ) {
$model->file = UploadedFile::getInstance($model, 'file');
// if ($model->load(Yii::$app->request->post())){
// $filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$title = _file[1];
$description = $file[2];
$phase = $file[3];
$modelnew->title = $title;
$modelnew->description = $description;
$modelnew->phase = $phase;
$modelnew->save();
}
unlink('uploads/'.$filename);
return $this->render('create',array('model'=>$model, 'message'=>$message));
}
}else{
return $this->render('create',array('model'=>$model, 'message'=>$message
));
}
return $this->render('create',array('model'=>$model, 'message'=>$message
));
}
But I getting an error like this,
"Access to undeclared static property: Yii::$app"
Anyone can help me to rectify the error, Thank you in advance..
I am making a plugin with a custom post_type called circular I use a meta box to upload PDF or image file now I can retrive the url of the file but how can I get the file name and size from my custom post_type meta field .
Here is my Meta Box code
function add_custom_meta_boxes() {
// Define the custom attachment for posts
add_meta_box(
'wp_custom_attachment',
'Custom Attachment',
'wp_custom_attachment',
'circular',
'side'
);
} // end add_custom_meta_boxes
add_action('add_meta_boxes', 'add_custom_meta_boxes');
function wp_custom_attachment() {
wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
$html = '<p class="description">';
$html .= 'Upload your PDF here.';
$html .= '</p>';
$html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" />';
echo $html;
} // end wp_custom_attachment
function save_custom_meta_data($id) {
/* --- security verification --- */
if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
return $id;
} // end if
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $id;
} // end if
if('circular' == $_POST['post_type']) {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} else {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} // end if
/* - end security verification - */
// Make sure the file array isn't empty
if(!empty($_FILES['wp_custom_attachment']['name'])) {
// Setup the array of supported file types. In this case, it's just PDF.
$supported_types = array('application/pdf');
// Get the file type of the upload
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
// Check if the type is supported. If not, throw an error.
if(in_array($uploaded_type, $supported_types)) {
// Use the WordPress API to upload the file
$upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($id, 'wp_custom_attachment', $upload);
update_post_meta($id, 'wp_custom_attachment', $upload);
} // end if/else
} else {
wp_die("The file type that you've uploaded is not a PDF.");
} // end if/else
} // end if
} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');
function update_edit_form() {
echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');
do out put the link of that file
<?php $img = get_post_meta(get_the_ID(), 'wp_custom_attachment', true); ?>
Download PDF Here
First need to get the file url the we can get the size and name . here wp_custom_attachment is the custom field id.
// retrieve file of the custom field
$file = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);
//get the url
$url = $file['url'];
//Replace url to directory path
$path = str_replace( site_url('/'), ABSPATH, esc_url( $url) );
if ( is_file( $path ) ){
$filesize = size_format( filesize( $path ) );
$filename = basename($path);
}
echo '<p>Name: ' . $filename . '</p>';
echo '<p>Size: ' . $filesize . '</p>';
If you can get the attachment ID number ($attachment_id below) you should be able to do something like this to get the name/size:
$attachment_id = 'YOUR_PDF_ID';
$attahment_file = get_attached_file( $attachment_id );
function getSize($file) {
$bytes = filesize($file);
$s = array('b', 'Kb', 'Mb', 'Gb');
$e = floor(log($bytes)/log(1024));
return sprintf( '%.2f ' . $s[$e], ( $bytes/pow( 1024, floor($e) ) ) );
}
echo '<p>Name: ' . basename( $attahment_file ) . '</p>';
echo '<p>Size: ' . getSize( $attahment_file ) . '</p>';
I found the "getSize" function on another post here. It was more accurate than using the native PHP "filesize" function in terms of matching the size shown in the WP media library meta.
add.php(When user click add photo)
<div class="col-lg-12">
<div class="form-group" id="image">
<label>Auction Image</label>
<div action="uploadImages.php" class="dropzone" id="uploadImageForm"></div>
<span class="help-block" id="image-error"></span>
</div>
</div>
<script>
$(function () {
Dropzone.options.uploadImageForm = false;
Dropzone.options.uploadImageForm = {
paramName: "file",
maxFilesize: 1,
acceptedFiles: 'image/*',
maxFiles: 5,
dictDefaultMessage: '<img src="images/icon_images.svg" width="100"/><br/><br/>Drop auction image here',
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'POST',
url: 'delete.php',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
};
</script>
UploadImages.php
<?php
session_start();
require 'config/database.php';
if (!isset($_SESSION['user'])) {
exit;
}
else if (!empty($_FILES)) {
$auctionImage = array();
$size = getimagesize($_FILES['file']['tmp_name']);
if (!$size) {
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode(['error']);
exit;
}
else {
$n = 0;
$tempFile = $_FILES['file']['tmp_name'];
$imageName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
$targetFile = $targetPath . $imageName;
$filename = $_FILES["file"]["name"];
move_uploaded_file($tempFile,$targetFile);
// isset id = insert gallery image into database
if (isset($_GET['id'])) {
$stmt = $db->prepare("INSERT INTO image (user_id, related_id, related_type, url) VALUES (:uid, :id, 'gallery', :url)");
$stmt->bindParam(':uid', $_SESSION['user']['id']);
$stmt->bindParam(':id', $_GET['id']);
$stmt->bindParam(':url', $imageName);
$stmt->execute();
}
else {
$auctionImage[] = $filename;
}
}
if (!empty($auctionImage)) {
// record uploaded image name, will store into session
// store uploaded image into session
//$_SESSION["auctionImages"] = array();
$_SESSION["auctionImages"][] = $auctionImage;
}
}
delete.php
<?php
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
unlink($targetPath.$_POST['id']);
session_start();
$a = $_POST['id'];
$key=array_search($a,$_SESSION['auctionImages']);
if($key!==false){
unset($_SESSION['auctionImages'][$key]);
$_SESSION["auctionImages"] = array_values($_SESSION["auctionImages"]);
echo '<pre>'; print_r($_SESSION['auctionImages']);
}
To use session variables, please add session_start() at the begin of your files, otherwise they aren't used. Secondly you are adding an array into a next array.
so you have to use
$_SESSION["auctionImages"] = $auctionImage;
or
$key=array_search($a[0],$_SESSION['auctionImages']);
Further debugging can be done by print_r($_SESSION); so you can track the contents of this array
The Problem -- What you should do:
You basically have to populate the SESSION variable like this:
$_SESSION["auctionImages"] = array(
"IMG_2923.JPG", "IMG_2924.JPG"
);
You're meant to address each element therefore, like this:
$_SESSION["auctionImages"][$n];
$n is the numbered index value for a particular element in the array. Therefore, if $n is 0, the array would return "IMG_29.29.JPG" and if the $n is 1, the array would return "IMG_2924.JPG".
However, you are populating the array like this:
$_SESSION["auctionImages"][] = array(
"IMG_2923.JPG", "IMG_2924.JPG"
);
If you dump this array, it will give you:
array(
array(
"IMG_2923.JPG", "IMG_2924.JPG"
)
);
Which is not the behaviour you require.
Solution
$filename = $_FILES["file"]["name"];
if(!is_array($_SESSION["auctionImages"])) {
$_SESSION["auctionImages"] = [];
}
$_SESSION["auctionImages"][] = $filename;
This is more shorter, cleaner and neater.
Also, you can use the alternative array syntax which is [ and ]. So, you can declare arrays using $var = []; which is shorter than $var = array();.
Firstly, the variable $a is the text to be searched in the array.
$key = array_search($a, $_SESSION["auctionImages"]);
if ($key !== false) {
unset($_SESSION["auctionImages"][$key]);
}
This is the second part of the code. This is all you need to have.
Also, make sure you have started the session by invoking session_start() in the top of the file if you haven't done yet.
A few comments
Consider taking a look at the Unofficial PHP standards here. It would be better if you name your variables in $camelCase. Therefore, it would be better to rename $filename to $fileName.
Also good job on using strict comparison which is !==.
Also, use more meaningful variable names. $a does not make sense. Something like $searchString would be really meaningful and the code will self-document your code.
Links
is_array - Returns TRUE if the passed identifier is an array, otherwise returns FALSE.
Let's now solve the problem with the full code you have given me. Let's start with delete.php:
<?php
session_start();
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
if(!isset($_POST['id'])) {
echo "ID has not been defined!";
exit;
}
$id = $_POST['id'];
unlink($targetPath . $id);
$key = array_search($id, $_SESSION['auctionImages']);
if ($key !== false) {
unset($_SESSION['auctionImages'][$key]);
echo '<pre>';
print_r($_SESSION['auctionImages']);
}
Now, let's fix your UploadImages.php file:
<?php
session_start();
require 'config/database.php';
if (!isset($_SESSION['user'])) {
exit;
}
if (!empty($_FILES)) {
if(!isset($_SESSION["auctionImages"]) && !is_array($_SESSION["auctionImages"])) {
$_SESSION["auctionImages"] = [];
}
$size = getimagesize($_FILES['file']['tmp_name']);
if (!$size) {
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode(['error']);
exit;
}
else {
$tempFile = $_FILES['file']['tmp_name'];
$imageName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
$targetFile = $targetPath . $imageName;
$fileName = $_FILES["file"]["name"];
move_uploaded_file($tempFile, $targetFile);
// isset id = insert gallery image into database
if (isset($_GET['id'])) {
$stmt = $db->prepare("INSERT INTO image (user_id, related_id, related_type, url) VALUES (:uid, :id, 'gallery', :url)");
$stmt->bindParam(':uid', $_SESSION['user']['id']);
$stmt->bindParam(':id', $_GET['id']);
$stmt->bindParam(':url', $imageName);
$stmt->execute();
}
else {
$_SESSION["auctionImages"][] = $fileName;
}
}
}
You have a problem here
$_SESSION["auctionImages"][]= $auctionImage;
Variable $auctionImage itself an array so need not to assign as an array again in SESSION variable. Make it as
$_SESSION["auctionImages"]= $auctionImage;
It works fine for me.
below is the code I worked.
<?php
//$filename = $_FILES["file"]["name"];
$auctionImage = array();
$auctionImage = array('IMG_2923.JPG', 'IMG_2924.JPG', 'IMG_2925.JPG'); // assigning sample variables // will be IMG_2923.JPG, IMG_2924.JPG and etc
$_SESSION["auctionImages"]= $auctionImage; // Removed '[]' from your coding
$a = 'IMG_2923.JPG'; // Assigning for testing purpose
$key=array_search($a,$_SESSION['auctionImages']);
if($key!==false)
unset($_SESSION['auctionImages'][$key]);
$_SESSION["auctionImages"] = array_values($_SESSION["auctionImages"]);
echo '<pre>'; print_r($_SESSION['auctionImages']); // Printing final session value. It prints without the key image name
?>
I currently have this script where users (using a form where they can upload up to seven images) can upload multiple images to a folder and the image name to my database, without any success. Please help.
if (isset($_POST['submit'])) { $ref_49 = $_POST['ref_49'];
$name = $_POST['name'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$rent_sell = $_POST['rent_sell'];
$heading = $_POST['heading'];
$price = $_POST['price'];
$limitedtextarea = $_POST['limitedtextarea'];
$type = $_POST['type'];
$where = $_POST['where'];
$address = $_POST['address'];
$bedroom = $_POST['bedroom'];
$bathroom = $_POST['bathroom'];
$garages = $_POST['garages'];
$carports = $_POST['carports'];
$granny_flat = $_POST['granny_flat'];
$ref_99 = $_POST['ref_99'];
$fulldesc = $_POST['full_desc'];
if ($ref_99=="") {
$full_ad = "yes";
} else {
$full_ad = "no";
}
$todays_date = date("Y-m-d");
mkdir("gallery/" . $_POST["name"], 0777);
for ($i = 0; $i < 7; $i++)
{
$file_name = $_FILES['uploadFile' . $i]['name'];
// strip file_name of slashes
$file_name = stripslashes($file_name);
$file_name = str_replace("'", "", $file_name);
// $copy = copy($_FILES['uploadFile'. $i]['tmp_name'], "gallery/" . $_POST["name"] . "/" . $file_name);
if ((($_FILES['uploadFile' . $i]["type"] == "image/gif")
|| ($_FILES['uploadFile' . $i]["type"] == "image/jpeg")
|| ($_FILES['uploadFile' . $i]["type"] == "image/pjpeg"))
&& ($_FILES['uploadFile' . $i]["size"] < 200000000))
{
if ($_FILES['uploadFile' . $i]["error"] > 0)
{
$message = "Return Code: " . $_FILES['uploadFile' . $i]["error"] . "<br />";
}
else
{
$query = "INSERT INTO property (
name, contact, email, type_of_listing, rent_sell, address, prop_desc, area, price, main_image, image_1, image_2, image_3, image_4, image_5, image_6, heading, bathroom, bedroom, garages, carports, granny_flat, full_description, full_ad, 49_ref, 99_ref, listed
) VALUES (
'{$name}', '{$contact}', '{$email}', '{$type}', '{$rent_sell}', '{$address}', '{$limitedtextarea}', '{$where}', '{$price}', '{$photo_1}', '{$photo_2}', '{$photo_3}', '{$photo_4}', '{$photo_5}', '{$photo_6}', '{$photo_7}', '{$heading}', '{$bathroom}', '{$bedroom}', '{$garages}', '{$carports}', '{$granny_flat}', '{$fulldesc}', '{$full_ad}', 'ref_49_{$ref_49}', 'ref_99_{$ref_99}', ''
)";
$result = mysql_query($query, $connection);
if (file_exists("gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]))
{
$message = "<h3>" . $_FILES['uploadFile' . $i]["name"] . " already exists.</h3>";
}
else
{
move_uploaded_file($_FILES['uploadFile' . $i]["tmp_name"], "gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]);
$message = "File: " . $_FILES['uploadFile' . $i]["name"] . " uploaded.";
}
}
}
else
{
$message = "<h3>Invalid file or no file selected.</h3><br />• Only JPEG OR GIF allowed.<br />• Size limited may not exceed 200KB.<br />Return";
}
}
}
}
There could be a lot of things going wrong here. Have you tried to break this up into pieces? Are you sure the DB is connecting? Are you sure php has access to write to the directories it's attempting to write to? Are you sure those directories exist...etc. etc.
Comment out the vast majority of the code, and start testing all the components piece by piece, or wrap stuff in try/catch and see what errors are produced.
[edit]
If the problem only occurs when you upload < 7 files then the problem is in that you've hard coded a 7 into your loop!
Loop through how many files are actually being uploaded, not a fixed number.
Assuming they're all being named sequentially (and starting at 0) you can test for the existence of your hashed FILE value in the loop and just keep ingesting until it comes up null (probably good to add a limiter to make sure it can't go on for ever)
something like this...
[edit 2] modified the condition to include a test for file size
for($i=0; $_FILES['uploadFile' . $i] && $_FILES['uploadFile' . $i]['size'] > 0 && $i<100 ; $i++){
try{
//do your upload stuff here
}catch(e){}
}
[EDIT]
To modify your page to include a dynamic number of fields do this:
check out this fiddle: http://jsfiddle.net/RjcHY/2/
Click the plus and minus buttons on the right side to see how it works. I made it so that it's naming the file buttons as per your php's expectations.
While dealing with common tasks like file uploading, write some library for handling those tasks and call necessary function wherever needed . If you create an uploader class file , you can simply invoke one of the methods you created to handle file uploads .
Here i will give you a Uploader class
<?php
//Save file as Uploader.php
//File Uploading Class
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;
function setDir($path){
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats(){
$this->allowAll = true;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string){
$ext = "";
try{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}catch(Exception $c){
$ext = "";
}
return $ext;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function setSequence($seq){
$this->imageSeq = $seq;
}
function getRandom(){
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath)){
$this->setMessage("Destination folder is not a directory ");
}else if(!is_writable($this->destinationPath)){
$this->setMessage("Destination is not writable !");
}else if(empty($name)){
$this->setMessage("File not selected ");
}else if($size>$this->maxSize){
$this->setMessage("Too large file !");
}else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
if($this->sameName==false){
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
}else{
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
$result = true;
}else{
$this->setMessage("Upload failed , try later !");
}
}else{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded(){
unlink($this->destinationPath.$this->uploadName);
}
}
?>
Using Uploader.php
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>
For handling multiple uploads , ex 3 images uploading
repeat the block as follows
<?php
for($i=1;$i<=3;$i++){
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
$uploader->setSequence($i);
if($uploader->uploadFile('txtFile'.$i)){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
}
?>
in above example , file browse components are named as txtFile1,txtFile2,txtFile3
Hope you will understand my explanation .
I am trying to put the file path to database, I already uploaded the file but I don't know how to get the path of the file to put it in the database?
Here is the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class dogo extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('insert_article');
}
public function index()
{
$this->load->view('dogo/dashboard.php');
}
//add new post to database including uploading image
public function new_post()
{
//used for the dropdown menu (category)
$this->load->model('dogo_cat');
$data['categores_dropdown'] = $this->dogo_cat->get_categories();
//form validation
$this->load->library('form_validation');//load the validation library
$this->form_validation->set_rules('title', 'title of the post', 'required');
$this->form_validation->set_rules('text', 'text of the post', 'required');
//$this->form_validation->set_rules('image', 'image of the post', 'required');
$this->form_validation->set_rules('category', 'category of the post', 'required');
//the form validation condition
if($this->form_validation->run() == FALSE){
//error
//$this->view_data
$this->load->view('dogo/new_post.php', $data);
}else{
//no error in the form
$title = $this->input->post('title');
$text = $this->input->post('text');
$category = $this->input->post('category');
$publish = $this->input->post('publish');
//$img_nw = $this->input->post('img_nw');
//$img_nw = $this->input->post('img_nw');
$image_file = $this->input->post('image_file');
//uploading
$this->load->model('upload_new_post');
if($this->input->post('upload')){
$this->upload_new_post->do_upload();
//$this->insert_article->insert_new_post($title, $category, $img_nw, $text, $source, $publish);
$data['images'] = $this->upload_new_post->get_images();
echo "title of the post: " . $title . "<br /> and the text of the post " . $text . "<br /> and category is: " . $category . "<br /> and publish is: " .$publish . "<br /> and image: <pre>" . $do_upload ."</pre>";
//echo $img_nw;
$this->load->view('dogo/new_post.php', $data);
}
}
}
}
And here is the model to upload it:
<?php
class upload_new_post extends CI_Model{
// retreive categories
var $file_path;
var $file_path_url;
function __construct() {
parent::__construct();
$this->file_path = realpath(APPPATH . '../post_data/images');
$this->file_path_url = base_url().'post_data/images/';
}
function do_upload(){
$config=array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->file_path,
'max_size' => 2000
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->file_path . '/thumbs',
'maintain_ration' => true,
'width' => 150,
'height' => 150
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
function get_images(){
$files = scandir($this->file_path);
$files = array_diff($files, array('.', '..', 'thumbs'));
$images = array();
foreach ($files as $file){
$images [] = array(
'url' => $this->file_path_url . $file,
'thumb_url' => $this->file_path_url . 'thumbs/' .$file
);
}
return $images;
}
}
And here the model to insert query:
<?php
class Insert_article extends CI_Model{
//insert new post
function __construct() {
parent::__construct();
}
function insert_new_post($title, $category, $img_nw, $text, $source, $publish)
{
$query_insert = "INSERT INTO hs_news_nw (idcat_nw, idsc_nw, idusr_nw, title_nw, img_nw, text_nw, active_nw, totalview_nw, date_nw) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$this->db->query($query_insert, array($category, $source, 1, $title, $img_nw, $text, 1, 1000, '2011-10-12 02:01:24'));
}
}
You should return $image_data from do_upload() function in your upload_new_post model.
$image_data = $this->upload->data();
..
..
return $image_data;
$image_data contains all the info about uploaded file including file name and path (do a print_r). Then you can pass it onto Insert_article model from your controller to store in database.
For reference:
http://codeigniter.com/user_guide/libraries/file_uploading.html
Please try if $fpath gives you the correct path:
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|jpeg|png|txt|php|pdf';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$image_data = $this->upload->data();
$fname=$image_data[file_name];
$fpath=$image_data[file_path].$fname;
you can use realpath to get real file location if I correctly understood you
You can try to upload by File Processing Library..
Controller :
public function add_slide() {
// set the page name
$data['title_admin'] = "Add & View Slide Information";
// load the custom file processing library
$this->load->library('file_processing');
$this->load->library('form_validation');
// check if click on the submit button
if ($this->input->post('Save')) {
// write the validation rule
$this->form_validation->set_rules('slide_name', 'Name', 'required');
$this->form_validation->set_rules('slide_short_description', 'Short Description', '');
$this->form_validation->set_rules('slide_long_description', 'Detail Description', '');
$this->form_validation->set_rules('slide_image', 'Image', 'callback_file_validate[no.slide_image.jpg,gif,png]');
//$this->form_validation->set_rules('slide_mission_vision', 'Diabetes Profile', 'callback_file_validate[no.slide_mission_vision.pdf]');
// check the validation
if ($this->form_validation->run()) {
$addData['slide_name'] = $this->input->post('slide_name');
$addData['slide_short_description'] = $this->input->post('slide_short_description');
$addData['slide_long_description'] = $this->input->post('slide_long_description');
$addData['slide_image'] = $this->file_processing->image_upload('slide_image', './images/slide/', 'size[500,1000|100,500]');
//$addData['slide_mission_vision'] = $this->file_processing->file_upload('slide_mission_vision', './images/slide_mission_vision/', 'pdf');
$addData['slide_add_date'] = date('Y-m-d');
// call the crate model and inset into database
if ($this->sa_model->save_slide_info($addData)) {
$this->session->set_flashdata('success_msg', 'Save Information Successfully!!');
redirect('super_admin/add_slide');
}
else
$data['error_msg'] = mysql_error();
}
}
// load the views
$data['s2'] = TRUE;
$data['slide_info'] = $this->sa_model->select_all_slide_info();
$data['admin_main_content'] = $this->load->view('admin/add_slide', $data, true);
$this->load->view('admin/admin_master', $data);
}
// file validation
public function file_slide_validate($fieldValue, $params) {
// get the parameter as variable
list($require, $fieldName, $type) = explode('.', $params);
// get the file field name
$filename = $_FILES[$fieldName]['name'];
if ($filename == '' && $require == 'yes') {
$this->form_validation->set_message('file_validate', 'The %s field is required');
return FALSE;
} elseif ($type != '' && $filename != '') {
// get the extention
$ext = strtolower(substr(strrchr($filename, '.'), 1));
// get the type as array
$types = explode(',', $type);
if (!in_array($ext, $types)) {
$this->form_validation->set_message('file_validate', 'The %s field must be ' . implode(' OR ', $types) . ' !!');
return FALSE;
}
}
else
return TRUE;
}
Model :
// insert new record into user table
public function save_slide_info($data) {
$this->db->insert('tbl_slide', $data);
return $this->db->affected_rows();
}