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);
...
}
Related
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;
<?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" );
I am trying to put my files in a folder from the file_put_contents can someone help me with that.
$invoegen_titel=$_POST['titel_form'];
$invoegen_datum=$_POST['datum'];
$invoegen_tekst=$_POST['tekst'];
$html_tekst= $invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>";
$previous = $_SERVER['HTTP_REFERER'];
$folder='blog';
var_dump(file_put_contents($folder."/".time().".html","<h1>".$invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>"));
make sure that the directory is present. file_put_contents doesn't create the directory if it is not present.
Please specify what problems you are encountering on your code.
change these parts
$folder = time(); //make sure that time() returns string
$folder = "blog/".$folder.'.html';
file_put_contents($folder, $html_tekst);
var_dump(file_get_contents($folder));
Use this:
$lifeTime = 5; // life time, seconds
$cached = TRUE;
$config = array(
'group'=>'default', // dir
'id' => '1', // id cache
'echo' => TRUE, // echo or return
'log'=>false, // echo log, or not
'ext' => 'js' // extention cache file, default .html
);
$CacheFile = new CacheFile('/usr/cache/', $cached);
$CacheFile->config($config, $lifeTime);
if (!$CacheFile->start()){
echo $invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>";
$CacheFile->end();
}
PHP class:
class CacheFile{
private $cacheDir = '';
private $cacheSubDir = '';
private $fileName = '';
private $cache = false;
private $lifeTime = 0;
private $echo = true;
private $group = true;
private $log = true;
private $fileExt = 'html';
public function __construct($cacheDir, $cache){
$this->cacheDir = $cacheDir;
$this->cache = $cache;
}
private function createdPatch(){
if ($this->cache){
if (!is_dir($this->cacheSubDir)){
mkdir($this->cacheSubDir, 0777, true);
}
chmod($this->cacheSubDir, 0755);
}
}
private function getSubDir($keyType, $keyValue){
return (($keyType != '')?($keyType.'/'):'').mb_substr($keyValue, 0, 1)."/".mb_substr($keyValue, 1, 1)."/".mb_substr($keyValue, 2, 1)."/";
}
private function getCacheName($key){
return md5($key).".".$this->fileExt;
}
public function config($conf = array('group'=>'post', 'id' => '0', 'echo' => TRUE), $time = 31536000){
$this->group = $conf['group'];
$this->cacheSubDir = $this->cacheDir.$this->getSubDir($conf['group'], md5($conf['id']));
$this->fileName = $this->getCacheName($conf['group'].$conf['id']);
$this->lifeTime = $time;
if (isset($conf['echo']))
$this->echo = $conf['echo'];
if (isset($conf['log']))
$this->log = $conf['log'];
if (isset($conf['ext']))
$this->fileExt = $conf['ext'];
}
public function start(){
if ($data = $this->get()) {
if ($this->echo){
echo $data;
return true;
}else{
return $data;
}
}
ob_start();
ob_implicit_flush(false);
return false;
}
function end(){
$data = ob_get_contents();
ob_end_clean();
if ($this->cache){
$this->save($data.(($this->log)?'<!-- c:'.$this->group.':('.date("Y-m-d H:i:s", (time()+$this->lifeTime)).'/'.date("Y-m-d H:i:s").') -->':""));
}
$return = $data.(($this->log)?'<!-- g:'.$this->group.':('.date("Y-m-d H:i:s", (time()+$this->lifeTime)).'/'.date("Y-m-d H:i:s").') -->':"");
if ($this->echo){
echo $return;
return true;
}
return $return;
}
public function get(){
if (!file_exists($this->cacheSubDir.$this->fileName))
return false;
if (time() >= filemtime($this->cacheSubDir.$this->fileName) + $this->lifeTime){
unlink($this->cacheSubDir.$this->fileName);
return false;
}
if ($this->cache && file_exists($this->cacheSubDir.$this->fileName))
if ($data = file_get_contents($this->cacheSubDir.$this->fileName, false))
return $data;
return false;
}
public function remove(){
if (file_exists($this->cacheSubDir.$this->fileName)){
echo unlink($this->cacheSubDir.$this->fileName);
return true;
}
return false;
}
public function save($data){
$this->createdPatch();
if (file_put_contents($this->cacheSubDir.$this->fileName, $data, LOCK_EX))
return true;
return false;
}
}
I fixed it
<?php $list = file_get_contents('list.json'); $list = json_decode($list, true); $selector = $_POST['selector']; $d_or_t = $_POST['d_or_t']; if (isset($selector) && isset($d_or_t)) { // overwrite the selected domain of the list with the new value if they are not empty if ($d_or_t == "domain") { $list[$selector]['domain'] = $_POST['new']; } if ($d_or_t == "template") { $list[$selector]['template'] = $_POST['new']; } /*else { echo '<script type="text/javascript">alert("U bent vergeten een veld in te voelen!");</script>'; }*/ // store the new json } ?>
<!DOCTYPE html>
<html>
<head>
<title>Json values veranderen</title>
</head>
<body>
<h2>Domain of Template veranderen met PHP script</h2>
<form action="test.php" id="form" method="post">
<select name="selector">
<?php foreach ($list AS $key => $value) : ?>
<option value="<?php echo $key; ?>">
<?php echo $key; ?>
</option>
<?php endforeach; ?>
</select>
<select name="d_or_t">
<option>domain</option>
<option>template</option>
</select>
<input type="text" name="new" placeholder="Nieuw">
<input type="submit" value="Veranderen">
</form>
</body>
</html>
<?php
echo "<ul>";
foreach ($list as $key => $value)
{
echo "<li>".$key."<ul>";
foreach ($value as $key1 => $value1)
{
echo "<li>".$key1.": ".$value1."</li>"; }
echo "</ul>"."</li>";
}
echo "</ul>";
file_put_contents('list.json', json_encode($list));
?>
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
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;
}