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 .
Related
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']}");
}
}
I have this code, to upload multiple files.
I would like to add a custom name for each file, beacuse i will store them in sql like this:
filename-1-2017-05-02-12:30:00 (1 is the actual array index, and after a date time)
if(isset($_POST['submitButton']))
{
if(isset($_FILES['gallery']))
{
if($_FILES["gallery"]["size"] > 0 )
{
foreach($_FILES['gallery']["name"] AS $key=>$file)
{
if($_FILES['gallery']['size'][$key] != 0 )
{
$target_path = "../documents/";
$target_path = $target_path . $_FILES['gallery']['name'][$key];
printr($_FILES['gallery']);
die();
if(move_uploaded_file($_FILES['gallery']['tmp_name'][$key], $target_path))
{
//$file_name = basename($_FILES['dok_file']['name']);
header("Location: ".$host."/".$admin_folder."/feltoltott-fajlok.php?new=1");
}
else
{
$error[] = "A fájl feltöltése nem sikerült, próbálja újra.";
}
}
}
}
}
}
http://php.net/manual/en/function.date.php
$target_path = "../documents/" . $_FILES['gallery']['name'][$key] . "-$key-" . date( "Y-m-d-H:i:s" );
move_uploaded_file( $_FILES['gallery']['tmp_name'][$key], $target_path );
I'm having trouble figuring out why it is that when an image size is too big, I get the error 'Invalid File Type' 'Uploaded file is not an image' instead of getting 'File is too big' (The image validation/upload script I didn't completely write myself- I found the code and made it work with for my needs). Everything else seems to work fine except for this. Also I get the following warning
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\minnow\includes\create-post.php on line 75
Here is my code
<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}
$postEmpty = 0;
$imageError = 0;
if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}
// validate post
if( $postEmpty == 0 && !empty($body) ){
$cleanBody = clean_input($body);
}
// validate image (if any)
if( $has_image == 1 ){
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');
// Create an array to hold any output
$errors = array();
// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}
//If $check image is set as true
if ( !getimagesize($_FILES[$image]['tmp_name']) ) {
$errors[] = "Uploaded file is not a valid image";
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}else {
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
}
}
// if no errors:
// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){
$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";
}else{
$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";
}
$result = $db->query($query);
// send response
//check to make sure the user was added
if( $db->affected_rows == 1 ){
$user_id = $_SESSION['user_id'];
$post_id = $db->insert_id;
$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);
if($result->num_rows == 1){
$row = $result->fetch_assoc();
}
$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}
if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }
if($row['has_image'] == 1){
$data = "<article class='post'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><img src='users/user_".$rowuser['user_id']."/posts/".$row['image']."' alt=''><div class='post-body'><div class='post-options'><a class='likes' href=''>156 likes</a></div><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}else{
$data = "<article class='post no-img'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><div class='post-body'><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><div class='post-options'><a class='likes' href=''>1 like</a></div><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}
}else{
$errors[] = "Server Error!";
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
}
die();
It could be that the file was just not uploaded to the server.
Check $_FILES[$image]['error'] to see what may have gone wrong.
Refer to the error messages here.
Edit: After these lines:
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
Do this:
// check for error greater than zero
if($_FILES[$image]['error'] > 0) {
// something went wrong with the upload, handle the error
echo $_FILES[$image]['error']; exit; // as an example to find out what the error was
}
Then refer to http://php.net/manual/en/features.file-upload.errors.php to find out the reason.
So I'm seeing an odd behavior and I asked over on serverfault but it looks to be a code issue. The thing is this code works fine when I test locally with MAMP, once I put it on HostGator I get this oddness.
So the process is
Upload file;
Check the state of things;
Unzip the file;
Read in a data file;
Copy and thumbnail images;
dump data into database.
I know 1 to 5 happen as I can see the thumbnails. The oddness is I get an error from step 2 saying the file didn't upload. So it looks like the whole process is started over with "blank" POST data.
So, step 1 is this bit of code. It's called when my form is posted:
function action_upload() {
$ownerName = $this->request->post('ownerName', '');
$ownerEmail = $this->request->post('ownerEmail', '');
$ownerPhone = $this->request->post('ownerPhone', '');
$username = $this->request->post('username', '');
$password = $this->request->post('password', '');
$treeName = $this->request->post('treeName', '');
$error = $this->util->process_datafile($ownerName, $ownerEmail, $ownerPhone, $username, $password, false, $treeName);
if ($error != "") {
echo json_encode(array(
'error' => $error,
));
} else {
echo json_encode(array(
'gotoURL' => "/" . $treeName,
));
}
exit;
}
The action reads in some form fields and calls a function process_datafile that, well, processes the uploaded file. Below is that function, the error I'm recieving is from the 9th line, "No tree name provided". But I know it at some point gets past that error.
public function process_datafile($ownerName, $ownerEmail, $ownerPhone, $username, $password, $update, $treeName) {
// Make sure we have a tree name
if ($treeName != "") {
$this->scriptPath = dirname(__FILE__);
$this->treePath = dirname(dirname($this->scriptPath)) . "/assets/trees/" . $treeName . "/";
$this->tempFilePath = dirname(dirname($this->scriptPath)) . "/assets/temp/" . $this->guid() . "/";
} else {
return "No tree name provided";
}
// Check to make sure the tree is in the expect condition
$treeExists = false;
if (file_exists($this->treePath)) {
$treeExists = true;
}
if ($treeExists && !$update) {
return "Tree name already exists " . $this->treePath;
} else if (!$treeExists && $update) {
return "Tree does not exists";
}
// Make sure there are no upload errors
if ($_FILES['treeFile']['error'] == '1' || $_FILES['treeFile']['error'] == '2') {
return "File size to large, try to upload your tree without media.";
} else if ($_FILES['treeFile']['error'] != '0') {
return "File upload error: " . $_FILES['treeFile']['error'];
}
// Move the uploaded file
if (!file_exists($this->tempFilePath)) {
mkdir($this->tempFilePath, 0700, true);
}
$name = $_FILES["treeFile"]["name"];
$tempfile = $this->tempFilePath . $name;
copy($_FILES['treeFile']['tmp_name'], $tempfile);
// Make sure it is something we can deal with
$finfo = finfo_open(FILEINFO_MIME);
$fileparts = explode(";", finfo_file($finfo, $tempfile));
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$filetype = $fileparts[0];
$valid = "text/plain,image/png";
if (($filetype != "text/plain" && $filetype != "application/zip") || ($ext != "ged" && $ext != "zip")) {
return "Only gedcom (.ged) or archive (.zip) files may be uploaded.";
}
$gedfile = $tempfile;
$archive_tmp = "";
if ($filetype == "application/zip" && $ext == "zip") {
$archive_tmp = $this->tempFilePath . "archive/";
if (!file_exists($archive_tmp)) {
mkdir($archive_tmp, 0700, true);
}
// Extract the archive
$zip = new \ZipArchive;
$res = $zip->open($tempfile);
if ($res === TRUE) {
$zip->extractTo($archive_tmp);
$zip->close();
} else {
$this->delTree($archive_tmp);
return "Error processing archive";
}
// Find the gedcom
$found = false;
$it = new \RecursiveDirectoryIterator($archive_tmp);
foreach(new \RecursiveIteratorIterator($it) as $file)
{
$file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (strtolower($file_ext) == "ged") {
$gedfile = $file;
$found = true;
}
}
if (!$found) {
$this->delTree($archive_tmp);
return "Could not find gedcom (.ged) file in archive.";
}
}
// Make the tree folder if needed
if (!file_exists($this->treePath)) {
mkdir($this->treePath, 0700, true);
}
$this->mediaPath = $this->treePath . "media/";
$this->delTree($this->mediaPath);
if (!file_exists($this->mediaPath)) {
mkdir($this->mediaPath, 0700, true);
}
if (file_exists($this->treePath . "tree.ged")) {
unlink($this->treePath . "tree.ged");
}
copy($gedfile, $this->treePath . "tree.ged");
// Deal with the database
if (!$this->create_database($ownerName, $ownerEmail, $ownerPhone, $username, $password, $update)) {
return "Could not open database";
}
// Process the gedcom
$this->process_gedcom($this->mediaPath, $archive_tmp);
// Remove the temp folder
$this->delTree($this->tempFilePath);
return "";
}
I know at some point it gets into the process_gedcom as that where the thumbnailing takes place... I also know it never gets to foreach ($ged->people as $person) as there are no entries in the database.
private function process_gedcom($mediaPath, $archivePath) {
// Insert statements
$personInsert = "INSERT INTO people (id, gender, first, last, middle, title, suffix) VALUES (:id, :gender, :first, :last, :middle, :title, :suffix)";
$nameInsert = "INSERT INTO names (personID, `type`, first, last) VALUES (:id, :type, :first, :last)";
$familyInsert = "INSERT INTO families (id, personAID, personBID) VALUES (:id, :personAID, :personBID)";
$childInsert = "INSERT INTO children (familyID, `type`, personID) VALUES (:familyID, :type, :personID)";
$eventInsert = "INSERT INTO events (personID, familyID, `type`, date, place, description) VALUES (:personID, :familyID, :type, :date, :place, :description)";
$factInsert = "INSERT INTO facts (personID, name, value) VALUES (:personID, :name, :value)";
$mediaInsert = "INSERT INTO media (id, file, `type`, title) VALUES (:id, :file, :type, :title)";
$peopleMediaInsert = "INSERT INTO people_media (mediaID, personID) VALUES (:mediaID, :personID)";
$familyMediaInsert = "INSERT INTO family_media (mediaID, familyID) VALUES (:mediaID, :familyID)";
// Load in the gedcom file
$ged = new \App\Gedcom();
$ged->import($this->treePath . "tree.ged", array($this, 'log'));
// Add objects to the database
foreach ($ged->objects as $obj) {
$file = $this->findFile($obj->getFilename(), $archivePath);
if ($file !== false) {
$finfo = finfo_open(FILEINFO_MIME);
$fileparts = explode(";", finfo_file($finfo, $file));
$filetype = $fileparts[0];
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
$hash = md5_file($file);
copy($file, $mediaPath . $hash . "." . $ext);
$this->makeThumb($mediaPath . $hash . "." . $ext, 200, 200, "thumb");
$this->makeThumb($mediaPath . $hash . "." . $ext, 1024, 768, "resized");
$this->database($mediaInsert, array(':id' => $obj->getId(),
':file' => $hash . "." . $ext,
':type' => $filetype,
':title' => $obj->getTitle()));
}
}
// Add people to the databsse
foreach ($ged->people as $person) {
$this->database($personInsert, array(':id' => $person->getId(),
':gender' => $person->getGender(),
':first' => $person->getFirstName(),
':last' => $person->getLastName(),
':middle' => $person->getMiddleName(),
':title' => $person->getTitleName(),
':suffix' => $person->getSuffixName()));
More data inserts...
What would cause things to restart as it looks like its calling process_datafile twice, once with valid inputs, the second time everything is '' blanks?
hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>
You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}
Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}