Undefined variable when calling a class method - php

Getting undefined variable error when calling a static method.
I'm new to coding. please be kind.
I'm trying to dynamically display an event page. It has $title, $price, $location, etc. with a table in the database titled Onlineevent.
I wanted to add a photo gallery to this event page and thought it would be better to have a new table (event_gallery) with columns (id, event_id, and image_name). The event_id is a foreign key from the Onlineevent table.
I'm having no problem calling the Onlineevent data from the database with the method (findy_by_id()). However I cannot call the method that relates to the event_gallery. Please refer to the code.
<?php
$event = Onlineevent::find_by_id($_GET['id']);
if($event){
$event_title = $event->event_title;
$event_type = $event->event_type;
$event_location = $event->event_location;
$event_date = $event->event_date;
$event_start_time = $event->event_start_time;
$event_finish_time = $event->event_finish_time;
$max_participants = $event->max_participants;
$event_price = $event->event_price;
$event_description = $event->event_description;
$event_picture = $event->picture_path();
$event_inclusion_1 = $event->inclusion_1;
$event_inclusion_2 = $event->inclusion_2;
$event_inclusion_3 = $event->inclusion_3;
$event_inclusion_4 = $event->inclusion_4;
$event_inclusion_5 = $event->inclusion_5;
$event_inclusion_6 = $event->inclusion_6;
$event_inclusion_7 = $event->inclusion_7;
$event_inclusion_8 = $event->inclusion_8;
}
$images = Eventgallery::find_by_id($_GET['id']);
if($images){
$image = $images->picture_path();
}
echo $image;
?>
Now I'll share the classes.
class Onlineevent extends Db_object{
protected static $db_table = "onlineevent";
protected static $db_table_fields = array('event_type','event_title','event_picture', 'event_location','event_date','event_start_time','event_finish_time','max_participants','event_price','event_description','event_map','inclusion_1','inclusion_2','inclusion_3','inclusion_4','inclusion_5','inclusion_6','inclusion_7','inclusion_8','inclusion_9','inclusion_10');
public $id;
public $event_type;
public $event_title;
public $event_picture;
public $event_location;
public $event_date;
public $event_start_time;
public $event_finish_time;
public $event_koreans;
public $max_participants;
public $event_foreigners;
public $event_price;
public $event_description;
public $event_map;
public $inclusion_1;
public $inclusion_2;
public $inclusion_3;
public $inclusion_4;
public $inclusion_5;
public $inclusion_6;
public $inclusion_7;
public $inclusion_8;
public $inclusion_9;
public $inclusion_10;
public $tmp_path;
public $upload_directory = "images";
public $errors = array();
public $upload_errors_array = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
This is passing $_FILES['uploaded_file'] as an argument
public function set_file($file) {
if(empty($file) || !$file || !is_array($file)) {
$this->errors[] = "There was no file uploaded here";
return false;
} elseif($file['error'] !=0){
$this->error[] = $this->upload_errors_array[$file['error']];
return false;
} else {
$this->event_picture = basename($file['name']);
$this->tmp_path = $file['tmp_name'];
$this->type = $file['type'];
$this->size = $file['size'];
}
}
public function picture_path(){
return $this->upload_directory.DS.$this->event_picture;
}
public function save(){
if($this->id){
$this->update();
} else {
if(!empty($this->errors)){
return false;
}
if(empty($this->event_picture) || empty($this->tmp_path)){
$this->errors[] = "the file was not available";
return false;
}
$target_path = SITE_ROOT .DS. 'admin'.DS. $this->upload_directory. DS . $this->event_picture;
if(move_uploaded_file($this->tmp_path, $target_path)){
if($this->create()){
unset($this->tmp_path);
return true;
}
} else {
$this->errors[] = "the folder probably does have permission";
return false;
}
}
}
Here is the second class
<?php
class Eventgallery extends Db_object{
protected static $db_table = "event_gallery";
protected static $db_table_fields = array('event_id','image_name');
public $id;
public $event_id;
public $image_name;
public $tmp_path;
public $upload_directory = "images";
public $errors = array();
// public $allowTypes = array('jpg','png','jpeg','gif');
public $upload_errors_array = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
This is passing $_FILES['uploaded_file'] as an argument
public function set_file($file) {
if(empty($file) || !$file || !is_array($file)) {
$this->errors[] = "There was no file uploaded here";
return false;
} elseif($file['error'] !=0){
$this->error[] = $this->upload_errors_array[$file['error']];
return false;
} else {
$this->image_name = basename($file['name']);
$this->tmp_path = $file['tmp_name'];
$this->type = $file['type'];
$this->size = $file['size'];
}
}
public function picture_path(){
return $this->upload_directory.DS.$this->image_name;
}
public function save(){
if($this->id){
$this->update();
} else {
if(!empty($this->errors)){
return false;
}
if(empty($this->image_name) || empty($this->tmp_path)){
$this->errors[] = "the file was not available";
return false;
}
$target_path = SITE_ROOT .DS. 'admin'.DS. $this->upload_directory. DS . $this->image_name;
if(move_uploaded_file($this->tmp_path, $target_path)){
if($this->create()){
unset($this->tmp_path);
return true;
}
} else {
$this->errors[] = "the folder probably does have permission";
return false;
}
}
}
I would like to be able to call the static function Eventgallery::find_by_id(); so that I can access the data and then print it out on the event page.
Thank you

When the if statement fails, the $image variable is not defined.
if ($images) {
$image = $images->picture_path();
}
echo $image;
You can solve this by declaring it first.
$image = '';
if ($images) {
$image = $images->picture_path();
}
echo $image;

Related

I have created a FileUploader class in PHP which validates and uploads any submited file. works fine but does not move the uploaded file

I am working on a project and so I am writing Object Oriented PHP. Hence, I have created a class called FileUploader. This class has all the method to validate file size, and file extension type as well as create directories if not existing.
Everything works just fine but I noticed that it only creates empty directories and does not move the uploaded files. I tried accessing the File error form the stored property but it always gives 0 as the error code
This is the FileUploader class
<?php
namespace Utility\Classes;
class FileUploader
{
//property declarations
protected $error_msg = array();
protected $tmp_file_name;
protected $max_file_size;
protected $target_location;
protected $allowed_file_type = array();
protected $File;
protected $default_file_name = true;
private $backlink_step;
private $unit_size; //to keep track of measurement unit of upload sizes MB|KB|BYTES
function __construct(array $file, array $allowed_ext = [], int $file_max_size = 5)
{
$this->File = $file;
$this->backlink_step = '';
$this->set_allowed_extensions($allowed_ext);
$this->set_max_upload_size($file_max_size);
}
/*This method helps to make sure that files are uploaded to the exact location as desired
*as in the case of deep nesting of subdirectory process
*/
function set_backlink_step($prfx)
{
$this->backlink_step = $prfx;
}
function set_target(string $target, $dated = false)
{
$this->target_location = $target;
if ($dated) {
$this->target_location .= "/" . $date = date("M-Y");
}
}
function get_target()
{
return $this->target_location;
}
//method to set valid/allowed file types
function set_allowed_extensions(array $allowed_ext)
{
$this->allowed_file_type = $allowed_ext;
}
//method to get the allowed file extensions
function get_allowed_extensions()
{
return $this->allowed_file_type;
}
function set_error_msg($err)
{
$this->error_msg[] = $err;
}
function get_error_msg()
{
return $this->error_msg;
}
function set_file_name($name)
{
$this->File['name'] = $name;
}
function get_file_name()
{
return $this->File['name'];
}
function get_tmp_name()
{
return $this->File['tmp_name'];
}
/**
* #description: method to return file size in a specified unit
* #param:String ['TB'|'MB'|'KB'|'B'] default MB
* #return: Int file size
* */
function get_file_size(String $unit = "MB")
{
if (strtolower($unit) === "tb") {
$quadrant = 1024 * 1024 * 1024;
} elseif (strtolower($unit) === "mb") {
$quadrant = 1024 * 1024;
} elseif (strtolower($unit) === "kb") {
$quadrant = 1024;
} elseif (strtolower($unit) === "b") {
$quadrant = 1;
}
$size = $this->file_size() / $quadrant;
return number_format($size, 2);
}
/**
* #return int size of the file
* */
function file_size()
{
$fsize = $this->File['size'];
return $fsize;
}
/* Method to get the extension name of a file eg: jpg,mp4 */
function get_ext()
{
$extension = explode('.', $this->get_file_name());
return "." . end($extension);
}
function validate($allowed_ext = [])
{
//fall back to the object allowed_file_type property if param not set by user
if (empty($allowed_ext)) {
$allowed_ext = $this->get_allowed_extensions();
}
//validate allowed file type if specified in the array
if (!empty($allowed_ext)) {
if (!$this->is_allowed_extension($allowed_ext)) {
$this->set_error_msg("Type of '{$this->get_file_name()} does not match allowed file types [" . implode('|', $this->get_allowed_extensions()) . "]");
return false;
}
}
//validate file size
if ($this->is_above_max_upload_size()) {
$this->set_error_msg("Size of the file '{$this->get_file_name()}' is larger than max allowed size of {$this->get_max_upload_size()}");
return false;
}
return true;
}
/*Method to upload file
* #return: the uploaded target location
*/
function upload_file()
{
//create necessary directories if not in existence
$this->create_dir();
$target = $this->backlink_step . $this->target_location . "/" . $this->get_file_name();
//attempt upload of the file
if (move_uploaded_file($this->tmp_file_name, $target)) {
//update target location with the filename
return $target;
} else {
//return false;
die("tmp_name: {$this->get_tmp_name()} \n target: {$target} \n Error: {$this->File['error']}");
}
}
/*This method sets the maximum upload size for file track and album_art respectively
*This method ignores invalid value for unit and replaces it with bytes*/
function set_max_upload_size($file_size, $unit = "MB")
{
$mulitplicant = 1;
if (strtolower($unit) === "tb") {
$multiplicant = 1024 * 1024 * 1024;
} elseif (strtolower($unit) === "mb") {
$multiplicant = 1024 * 1024;
} elseif (strtolower($unit) === "kb") {
$multiplicant = 1024;
} else {
$unit = "Bytes";
}
$this->max_file_size = $multiplicant * $file_size; //set max size for file
$this->unit_size = strtoupper($unit);
}
function get_max_upload_size()
{
return $this->max_file_size;
}
/*Method to compare the size of files to be uploaded with the maximum allowed size*/
function is_above_max_upload_size()
{
$file_unit = $this->unit_size;
//return FALSE if upload size > max size otherwise TRUE
return ($this->file_size() > $this->get_max_upload_size()) ? true : false;
}
/*Method to check if upload file is allowed in by extension name
*The first paramater takes the string of the actual file extension
*The second parameter takes an array of allowed extensions
*/
function is_allowed_extension(array $allowed_ext)
{
return (!in_array($this->get_ext(), $allowed_ext)) ? false : true;
}
//method to create directories
function create_dir()
{
//check if user set a storage location and attempt to create the location
if (empty($this->get_target())) {
$this->set_error_msg('Target Not set.');
return false;
}
//Create the directory
$location = explode('/', $this->get_target());
$prepend = $this->backlink_step . "";
foreach ($location as $key => $value) {
if (!is_dir($prepend . $value)) {
mkdir($prepend . $value);
}
$prepend .= $value . "/";
}
}
}
Then I have another php script where I process the uploaded file by instantiating the FileUploader Class with the $_FILES variable process.php
require_once "../vendor/autoload.php";
use Utility\Classes\FileUploader;
//Instantiate new FileUploader with the files to be uploaded.
$LogoUploader = new FileUploader($_FILES['logo'], ['.png', '.jpg']);
//validate logo size and type - Upload to folder if everything Ok
$logo_validated = $LogoUploader->validate();
//upload files that passed validation
if ($logo_validated) {
$LogoUploader->set_target($location);
$LogoUploader->set_backlink_step('../');
$ltarget = $LogoUploader->upload_file();
if (!$ltarget) {
//upload error
print_error($LogoUploader->get_error_msg());
exit;
} else { //upload success
print "Logo uploaded successfully";
}
} else { //validation error
print_error($LogoUploader->get_error_msg());
exit;
}
Please what am I not doing right?? everything is ok, validation is working, user can set the upload target and if it does not exist, it will be created but it does not upload the file into the created directory or anywhere else in my working directory
I think you need to change the following line
if (move_uploaded_file($this->tmp_file_name, $target)) {
to
if (move_uploaded_file( $this->get_tmp_name(), $target )) {
in the upload_file method. ie:
public function upload_file(){
$this->create_dir();
$target = $this->backlink_step . $this->target_location . "/" . $this->get_file_name();
if (move_uploaded_file( $this->get_tmp_name(), $target )) {
return $target;
} else {
die("tmp_name: {$this->get_tmp_name()} \n target: {$target} \n Error: {$this->File['error']}");
}
}

Warning: move_uploaded_file( C: \ xampp \ htdocs\photo_gallery\public\images\powder.jpg): failed to open stream: Invalid argument in C:\xampp\

<?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once('database.php');
class Photograph extends DatabaseObject {
protected static $table_name="photographs";
protected static $db_fields=array('id', 'filename', 'type', 'size', 'caption');
public $id;
public $filename;
public $type;
public $size;
public $caption;
private $temp_path;
protected $upload_dir="images";
public $errors=array();
protected $upload_errors = array(
// http://www.php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
// Pass in $_FILE(['uploaded_file']) as an argument
public function attach_file($file) {
// Perform error checking on the form parameters
if(!$file || empty($file) || !is_array($file)) {
// error: nothing uploaded or wrong argument usage
$this->errors[] = "No file was uploaded.";
return false;
} elseif($file['error'] != 0) {
// error: report what PHP says went wrong
$this->errors[] = $this->upload_errors[$file['error']];
return false;
} else {
// Set object attributes to the form parameters.
$this->temp_path = $file['tmp_name'];
$this->filename = basename($file['name']);
$this->type = $file['type'];
$this->size = $file['size'];
// Don't worry about saving anything to the database yet.
return true;
}
}
public function save() {
// A new record won't have an id yet.
if(isset($this->id)) {
// Really just to update the caption
$this->update();
} else {
// Make sure there are no errors
// Can't save if there are pre-existing errors
if(!empty($this->errors)) { return false; }
// Make sure the caption is not too long for the DB
if(strlen($this->caption) > 255) {
$this->errors[] = "The caption can only be 255 characters long.";
return false;
}
// Can't save without filename and temp location
if(empty($this->filename) || empty($this->temp_path)) {
$this->errors[] = "The file location was not available.";
return false;
}
// Determine the target_path
$target_path = SITE_ROOT .DS. 'public' .DS. $this->upload_dir .DS. $this->filename;
// Make sure a file doesn't already exist in the target location
if(file_exists($target_path)) {
$this->errors[] = "The file {$this->filename} already exists.";
return false;
}
// Attempt to move the file
if(move_uploaded_file($this->temp_path, $target_path)){
// Success
// Save a corresponding entry to the database
if($this->create()) {
// We are done with temp_path, the file isn't there anymore
unset($this->temp_path);
return true;
}
} else {
// File was not moved.
$this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
return false;
}
}
}
public function destroy() {
// First remove the database entry
if($this->delete()) {
// then remove the file
// Note that even though the database entry is gone, this object
// is still around (which lets us use $this->image_path()).
$target_path = SITE_ROOT.DS.'public'.DS.$this->image_path();
return unlink($target_path) ? true : false;
} else {
// database delete failed
return false;
}
}
public function image_path() {
return $this->upload_dir.DS.$this->filename;
}
public function size_as_text() {
if($this->size < 1024) {
return "{$this->size} bytes";
} elseif($this->size < 1048576) {
$size_kb = round($this->size/1024);
return "{$size_kb} KB";
} else {
$size_mb = round($this->size/1048576, 1);
return "{$size_mb} MB";
}
}
public function comments() {
return Comment::find_comments_on($this->id);
}
// Common Database Methods
public static function find_all() {
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function count_all() {
global $database;
$sql = "SELECT COUNT(*) FROM ".self::$table_name;
$result_set = $database->query($sql);
$row = $database->fetch_array($result_set);
return array_shift($row);
}
private static function instantiate($record) {
// Could check that $record exists and is an array
$object = new self;
// Simple, long-form approach:
// $object->id = $record['id'];
// $object->username = $record['username'];
// $object->password = $record['password'];
// $object->first_name = $record['first_name'];
// $object->last_name = $record['last_name'];
// More dynamic, short-form approach:
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
// We don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute, $this->attributes());
}
protected function attributes() {
// return an array of attribute names and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $database;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
// replaced with a custom save()
// public function save() {
// // A new record won't have an id yet.
// return isset($this->id) ? $this->update() : $this->create();
// }
public function create() {
global $database;
// Don't forget your SQL syntax and good habits:
// - INSERT INTO table (key, key) VALUES ('value', 'value')
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update() {
global $database;
// Don't forget your SQL syntax and good habits:
// - UPDATE table SET key='value', key='value' WHERE condition
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
public function delete() {
global $database;
// Don't forget your SQL syntax and good habits:
// - DELETE FROM table WHERE condition LIMIT 1
// - escape all values to prevent SQL injection
// - use LIMIT 1
$sql = "DELETE FROM ".self::$table_name;
$sql .= " WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
// NB: After deleting, the instance of User still
// exists, even though the database entry does not.
// This can be useful, as in:
// echo $user->first_name . " was deleted";
// but, for example, we can't call $user->update()
// after calling $user->delete().
}
}
?>
I am getting some warnings on move_upload_file. I tried to diagnose the problem but I failed. Here is the error i am getting.
Warning: move_uploaded_file( C: \ xampp \
htdocs\photo_gallery\public\images\powder.jpg): failed to open stream:
Invalid argument in
C:\xampp\htdocs\photo_gallery\includes\photograph.php on line 88
Warning: move_uploaded_file(): Unable to move
'C:\xampp\tmp\php46A4.tmp' to ' C: \ xampp \
htdocs\photo_gallery\public\images\powder.jpg' in
C:\xampp\htdocs\photo_gallery\includes\photograph.php on line 88
Problem seems to be in SITE_ROOT variable, it should have no spaces on it
As it seems, SITE_ROOT has this value
C: \ xampp \ htdocs\photo_gallery
but it should have this
C:\xampp\htdocs\photo_gallery
If you show us the code where you set SITE_ROOT, we could help you fix it
EDIT (as per your comment on this question)
Your error is in this line you put on the comment of this question
define('SITE_ROOT', " c:\ xampp\htdocs\photo_gallery" );
It should have no spaces, like this
define('SITE_ROOT', "c:\xampp\htdocs\photo_gallery" );

upload multiple images - php

I'm new to PHP, how to make that code support multiple image upload?
I have here 3 button and every one of them can upload single image. I need to make it support multiple upload image. Thank you.
This is all code:
<?php
class Products extends CI_Controller{
function __construct()
{
parent::__construct();
if(!isset($_SESSION['user'])){
redirect('admin/dashboard');
}else{
$user=$_SESSION['user'][0];
if($user->perm==USER){
redirect('admin/denied');
}
}
$this->load->model('product_model');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|JPG|JPEG|GIF|PNG';
$config['max_size'] = '2000';
$this->load->library('upload', $config);
$this->load->helper('Ultils');
$this->form_validation->set_error_delimiters('<span class="help-inline msg-error" generated="true">', '</span>');
}
function index(){
$page = $this->input->get('page') ? $this->input->get('page') : 0;
$per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 10;
$order = $this->input->get('order') ? $this->input->get('order') : 'DESC';
$config['base_url']= base_url() . 'index.php/admin/products?order='.$order;
$config['per_page']=$per_page;
$data['msg_label']=$this->config->item('msg_label');
$config['total_rows'] = $this->product_model->total(array(), array());
$this->pagination->initialize($config);
$data['list'] = $this->product_model->get("*,products.id as id,products.activated as activated", array(),array(),$page, $per_page, array('products.id' => 'DESC'));
$data['page_link'] = $this->pagination->create_links();
$this->template->write_view('content','backends/products/index',array('data'=>$data));
$this->template->render();
}
public function create(){
$error=null;
$images=array();
$image_path=null;
$insert_id =0;
$thumb=null;
if(isset($_SESSION['user'])){
if(isset($_POST['title'])){
$user=$_SESSION['user'][0];
$this->form_validation->set_rules('title','title', 'trim|required|min_length[5]|max_length[100]|xss_clean');
$this->form_validation->set_rules('price', 'price', 'trim|numeric|xss_clean');
$this->form_validation->set_rules('aim', 'aim', 'trim|required|xss_clean');
$this->form_validation->set_rules('content', 'content', 'trim|required|min_length[5]|max_length[2000]|xss_clean');
$this->form_validation->set_rules('provinces', 'provinces', 'trim|required|xss_clean');
$this->form_validation->set_rules('cities', 'cities', 'trim|required|xss_clean');
$this->form_validation->set_rules('categories', 'categories', 'trim|required|xss_clean');
if($this->form_validation->run()!=false){
$data['title']=preg_replace('/[\r\n]+/', "", $this->input->post('title'));
$data['price']=$this->input->post('price');
$data['aim']=$this->input->post('aim');
$data['content']=preg_replace('/[\r\n]+/', "", htmlspecialchars($this->input->post('content')));
$data['county_id']=$this->input->post('provinces');
$data['categories_id']=$this->input->post('categories');
$data['user_id']=$user->id;
$data['cities_id']=$this->input->post('cities');
$insert_id = $this->product_model->insert($data);
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['image']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext,$allowed)) {
$upload_result=self::upload();
if($upload_result!=null){
$image_path=$upload_result;
array_push($images, $upload_result);
$this->form_validation->set_rules('image', 'image', 'callback_upload');
}else{
$error['error_upload_file']="Can not upload file, please check again";
}
}else{
$error['eror_upload_file']="Your upload file contains invalid allow upload file type";
}
$filename = $_FILES['image1']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext,$allowed)) {
$upload_result=self::upload1();
if($upload_result!=null){
$image_path=$upload_result;
array_push($images, $upload_result);
$this->form_validation->set_rules('image', 'image', 'callback_upload');
}else{
$error['error_upload_file_1']="Can not upload file, please check again";
}
}else{
$error['eror_upload_file_1']="Your upload file contains invalid allow upload file type";
}
$filename = $_FILES['image2']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext,$allowed)) {
$upload_result=self::upload2();
if($upload_result!=null){
$image_path=$upload_result;
array_push($images, $upload_result);
$this->form_validation->set_rules('image', 'image', 'callback_upload');
}else{
$error['error_upload_file_2']="Can not upload file, please check again";
}
}else{
$error['eror_upload_file_2']="Your upload file contains invalid allow upload file type";
}
if($insert_id!=0){
if($image_path!=null){
$config=array(
"source_image" => 'uploads/'.$image_path, //get original image
"new_image" => "uploads/thumbs", //save as new image //need to create thumbs first
"maintain_ratio" => true,
"width" => 200,
"height" => 200
);
$this->load->library('image_lib',$config);
$this->image_lib->resize();
$image_path= 'uploads/thumbs/'.$image_path;
$this->product_model->update(array('image_path'=>$image_path), array('id'=>$insert_id));
$this->load->model('images_model');
for ($i=0; $i < count($images); $i++) {
$this->images_model->insert(array('path'=>'uploads/'.$images[$i],'product_id'=>$insert_id));
}
}
$this->session->set_flashdata('msg_ok',$this->lang->line('add_successfully'));
redirect('admin/products/create');
}
}
}
; }else{
redirect('admin/dashboard');
}
$this->load->model('county_model');
$data['provinces']=$this->county_model->get();
$this->load->model('categories_model');
$data['categories']=$this->categories_model->get();
$this->template->write_view('content','backends/products/add',array('data'=>$data,'error'=>$error));
$this->template->render();
}
public function upload(){
if(isset($_FILES['image'])){
$filename=$_FILES['image']['name'];
$_FILES['image']['name']=rename_upload_file($filename);
}
if ($this->upload->do_upload('image'))
{
return $_FILES['image']['name'];
}
else
{
return null;
}
}
public function upload1(){
if(isset($_FILES['image1'])){
$filename=$_FILES['image1']['name'];
$_FILES['image1']['name']=rename_upload_file($filename);
}
if ($this->upload->do_upload('image1'))
{
return $_FILES['image1']['name'];
}
else
{
return null;
}
}
public function upload2(){
if(isset($_FILES['image2'])){
$filename=$_FILES['image2']['name'];
$_FILES['image2']['name']=rename_upload_file($filename);
}
if ($this->upload->do_upload('image2'))
{
return $_FILES['image2']['name'];
}
else
{
return null;
}
}
public function check_username_exist_add($name){
$data=$this->product_model->get_by_exact_name($name, 0, 1);
if ($data!=null)
{
$this->form_validation->set_message('check_username_exist_add', 'This name has exist');
return FALSE;
}
else
{
return TRUE;
}
}
public function check_username_exist_edit(){
$id=$this->input->post('id');
$name=$this->input->post('name');
$data=$this->product_model->get_by_name_and_diff_id($id,$name);
if($data!=null) {
$this->form_validation->set_message('check_username_exist_edit', 'This name has exist');
return FALSE;
} else {
return TRUE;
}
}
public function edit_get(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$data=parent::getDataView();
$data['obj']=$this->product_model->get_by_id($id);
$this->blade->render('backends/products/edit',array('data'=>$data));
}
}
public function edit_post(){
if(isset($_POST['id'])){
$id=$_POST['id'];
$name=$_POST['name'];
$data=parent::getDataView();
$this->form_validation->set_rules('name','name', 'trim|required|min_length[5]|max_length[60]|xss_clean|callback_check_username_exist_edit');
if($this->form_validation->run()){
$this->product_model->update(array('name'=>$name),array('id'=>$id));
}
$data['obj']=$this->product_model->get_by_id($id);
$this->blade->render('backends/products/edit',array('data'=>$data));
}
}
public function delete(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$product=$this->product_model->get_by_id($id);
if($product!=null){
$this->load->model('images_model');
$images=$this->images_model->get_by_product_id($id);
foreach ($images as $r) {
try {
unlink($r->path);
$this->images_model->remove_by_id($r->id);
} catch (Exception $e) {
}
}
try {
unlink($product[0]->image_path);
} catch (Exception $e) {
}
}
$this->product_model->remove_by_id($id);
redirect('admin/products');
}
}
public function activate(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
echo $id;
$this->product_model->update(array('activated'=>1),array('id'=>$id));
}
redirect('admin/products');
}
public function lock(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$this->product_model->update(array('activated'=>0),array('id'=>$id));
}
redirect('admin/products');
}
public function search(){
if(isset($_GET['query'])){
$query=$this->input->get('query');
$data=parent::getDataView();
$page = $this->input->get('page') ? $this->input->get('page') : 0;
$per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 10;
$order = $this->input->get('order') ? $this->input->get('order') : 'DESC';
$config['total_rows'] = $this->product_model->total(array(), array('title'=>$query));
$config['base_url']= base_url() . 'index.php/admin/products/search?order='.$order.'&query='.$query;
$config['per_page']=$per_page;
$data['msg_label']=$this->config->item('msg_label');
$this->pagination->initialize($config);
$data['list'] = $this->product_model->get_by_name($query,$page,$per_page);
$data['page_link'] = $this->pagination->create_links();
$data['search_title']='Result search for "'.$query.'"';
$this->template->write_view('content','backends/products/index',array('data'=>$data));
$this->template->render();
}
}
}
?>
Allow your HTML file input to select many files like <input type="file" name="images[]" multiple> and then loop through the same $_FILES var. Also, don't forget to add the <form> enctype attribute like enctype="multipart/form-data".
$image_files = $_FILES['images']['tmp_name'];
foreach($image_files as $key=>$value){
// write some code to process the information
// this will loop through all the images, no matter how many, so the same code inside these curly braces will be applied to each file/image/whatever.
}

Codeigniter 2.1 controller not found

I have conroller baner, and when I try to run it (run upload function http://localhost/010/baner/upload_img), I got 404 error:
The page you requested was not found
What is wrong here?
The controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Upload_Baner extends CI_Controller {
protected $path_img_upload_folder;
protected $path_img_thumb_upload_folder;
protected $path_url_img_upload_folder;
protected $path_url_img_thumb_upload_folder;
protected $delete_img_url;
function __construct() {
parent::__construct();
$this->setPath_img_upload_folder("public/img/promotions/");
$this->setPath_img_thumb_upload_folder("public/img/promotions/thumbnails/");
$this->setDelete_img_url(base_url() . 'upload_baner/deleteImage/');
$this->setPath_url_img_upload_folder(base_url() . "public/img/promotions/");
$this->setPath_url_img_thumb_upload_folder(base_url() . "public/img/promotions/thumbnails/");
}
public function upload_img() {
//Format the name
$name = $_FILES['userfile']['name'];
$name = strtr($name, 'ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃà áâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
// replace characters other than letters, numbers and . by _
$name = preg_replace('/([^.a-z0-9]+)/i', '_', $name);
//Your upload directory, see CI user guide
$config['upload_path'] = $this->getPath_img_upload_folder();
$config['allowed_types'] = 'gif|jpg|png|JPG|GIF|PNG';
$config['max_size'] = '1000';
$config['file_name'] = $name;
//Load the upload library
$this->load->library('upload', $config);
if ($this->do_upload()) {
//If you want to resize
$config['new_image'] = $this->getPath_img_thumb_upload_folder();
$config['image_library'] = 'gd2';
$config['source_image'] = $this->getPath_img_upload_folder() . $name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 193;
$config['height'] = 94;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data = $this->upload->data();
//Get info
$info = new stdClass();
$info->name = $name;
$info->size = $data['file_size'];
$info->type = $data['file_type'];
$info->url = $this->getPath_img_upload_folder() . $name;
$info->thumbnail_url = $this->getPath_img_thumb_upload_folder() . $name; //I set this to original file since I did not create thumbs. change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$name
$info->delete_url = $this->getDelete_img_url() . $name;
$info->delete_type = 'DELETE';
//Return JSON data
if (IS_AJAX) { //this is why we put this in the constants to pass only json data
echo json_encode(array($info));
//this has to be the only the only data returned or you will get an error.
//if you don't give this a json array it will give you a Empty file upload result error
//it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
} else { // so that this will still work if javascript is not enabled
$file_data['upload_data'] = $this->upload->data();
echo json_encode(array($info));
}
} else {
// the display_errors() function wraps error messages in <p> by default and these html chars don't parse in
// default view on the forum so either set them to blank, or decide how you want them to display. null is passed.
$error = array('error' => $this->upload->display_errors('',''));
echo json_encode(array($error));
}
}
public function do_upload() {
if (!$this->upload->do_upload()) {
return false;
} else {
//$data = array('upload_data' => $this->upload->data());
return true;
}
}
//Function Delete image
public function deleteImage() {
//Get the name in the url
$file = $this->uri->segment(3);
$success = unlink($this->getPath_img_upload_folder() . $file);
$success_th = unlink($this->getPath_img_thumb_upload_folder() . $file);
//info to see if it is doing what it is supposed to
$info = new stdClass();
$info->sucess = $success;
$info->path = $this->getPath_url_img_upload_folder() . $file;
$info->file = is_file($this->getPath_img_upload_folder() . $file);
if (IS_AJAX) {//I don't think it matters if this is set but good for error checking in the console/firebug
echo json_encode(array($info));
} else { //here you will need to decide what you want to show for a successful delete
var_dump($file);
}
}
public function get_files() {
$this->get_scan_files();
}
public function get_scan_files() {
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
}
protected function get_file_object($file_name) {
$file_path = $this->getPath_img_upload_folder() . $file_name;
if (is_file($file_path) && $file_name[0] !== '.') {
$file = new stdClass();
$file->name = $file_name;
$file->size = filesize($file_path);
$file->url = $this->getPath_url_img_upload_folder() . rawurlencode($file->name);
$file->thumbnail_url = $this->getPath_url_img_thumb_upload_folder() . rawurlencode($file->name);
//File name in the url to delete
$file->delete_url = $this->getDelete_img_url() . rawurlencode($file->name);
$file->delete_type = 'DELETE';
return $file;
}
return null;
}
protected function get_file_objects() {
return array_values(array_filter(array_map(
array($this, 'get_file_object'), scandir($this->getPath_img_upload_folder())
)));
}
public function getPath_img_upload_folder() {
return $this->path_img_upload_folder;
}
public function setPath_img_upload_folder($path_img_upload_folder) {
$this->path_img_upload_folder = $path_img_upload_folder;
}
public function getPath_img_thumb_upload_folder() {
return $this->path_img_thumb_upload_folder;
}
public function setPath_img_thumb_upload_folder($path_img_thumb_upload_folder) {
$this->path_img_thumb_upload_folder = $path_img_thumb_upload_folder;
}
public function getPath_url_img_upload_folder() {
return $this->path_url_img_upload_folder;
}
public function setPath_url_img_upload_folder($path_url_img_upload_folder) {
$this->path_url_img_upload_folder = $path_url_img_upload_folder;
}
public function getPath_url_img_thumb_upload_folder() {
return $this->path_url_img_thumb_upload_folder;
}
public function setPath_url_img_thumb_upload_folder($path_url_img_thumb_upload_folder) {
$this->path_url_img_thumb_upload_folder = $path_url_img_thumb_upload_folder;
}
public function getDelete_img_url() {
return $this->delete_img_url;
}
public function setDelete_img_url($delete_img_url) {
$this->delete_img_url = $delete_img_url;
}
}
Your controller is named Upload_Baner so unless you have a route defined that maps baner to upload_Baner this won't work. Does this url work?:
http://localhost/010/upload_Baner/upload_img
That is what your current controller will map to without the route.

MYSQL file size not showing

I'm learning how to build a photo_gallery using a PHP video book/tutorial. I was able to upload a photo, but in the MySQL database, it's not registering a size of the photo. It just says 0 (see image)
The instructor's Mysql gives the size of the file.
Any idea why the file size wouldn't show up in SQL?
UPDATE... This is the photograph class.
<?php
require_once(LIB_PATH.DS.'database.php');
class Photograph extends DatabaseObject {
protected static $table_name="photographs";
protected static $db_fields=array('id', 'filename', 'type', 'caption');
public $id;
public $filename;
public $type;
public $size;
public $caption;
private $temp_path;
protected $upload_dir="images";
public $errors=array();
protected $upload_errors = array(
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
// Pass in $_FILE(['uploaded_file']) as an argument
public function attach_file($file) {
//perform error checking on the form parameters
if(!file || empty($file) || !is_array($file)){
//error: nothing uploaded or wrong usage
$this->errors[] = "No file was uploaded.";
return false;
} elseif($file['error'] !=0) {
//error: report what PHP says went wrong
$this->errors[] = $this->upload_errors[$file['error']];
return false;
} else {
//set object attributes to the form parameters.
$this->temp_path = $file['tmp_name'];
$this->filename = basename($file['name']);
$this->type = $file['type'];
$this->size = $file['size'];
//don't worry about saving anything to the database yet
return true;
}
}
public function save() {
// a new record won't have an id yet.
if(isset($this->id)) {
//really just to update the caption
$this->update();
} else {
//make sure there are no errors
//Can't save if there are pre-existing errors
if(!empty($this->errors)) {return false; }
//make sure the caption is not too long for the DB
if(strlen($this->caption) > 255) {
$this->error[] = "The caption can only be 255 characters long.";
return false;
}
//Can't save without filename and temp location
if(empty($this->filename) || empty($this->temp_path)){
$this->errors[] = "The file location was not available.";
return false;
}
//Determine the target_path
$target_path = SITE_ROOT .DS. 'public' .DS. $this->upload_dir .DS. $this->filename;
//Make sure a file doesn't already exist
if(file_exists($target_path)) {
$this->errors[] = "The file {$this->filename} already exists.";
return false;
}
//attempt to move the file
if(move_uploaded_file($this->temp_path, $target_path)) {
//success
//save a corresponding entry to the database
if($this->create()) {
//we are done with temp_path, the file isn't there anymore
unset($this->temp_path);
return true;
}
} else {
//failure
$this->errors[] = "The file upload failed, possibly due to incorrect permissions
on the upload folder.";
return false;
}
}
}
//common database methods
public static function find_all(){
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql=""){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record){
$object = new self;
//$object->id = $record['id'];
//$object->username = $record['username'];
//$object->password = $record['password'];
//$object->first_name = $record['first_name'];
//$object->last_name = $record['last_name'];
foreach($record as $attribute=>$value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = $this->attributes();
return array_key_exists($attribute, $object_vars);
}
protected function attributes() {
//return an array of attribute keys and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $database;
$clean_attributes = array();
//sanitize the values before submitting
//Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key=> $value) {
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
//replaced with a custom save()
//public function save() {
//return isset($this->id) ? $this->update() : $this->create();
//}
public function create() {
global $database;
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if ($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update() {
global $database;
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
public function delete() {
global $database;
$sql = "DELETE FROM ".self::$table_name." ";
$sql .= "WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
}
?>
I think you forget to put size in your $db_fields
protected static $db_fields=array('id', 'filename', 'type', 'size', 'caption');
if you look at your attributes() function it checks to see if property_exists within the $db_fields and then assign the value to $attributes array and since 'size' was not within the array that you are checking against, it basically gets filtered out is what i am guessing:
protected function attributes() {
//return an array of attribute keys and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}

Categories