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?
Related
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.
I have the following directory structure of my database dump (total of: 18,042,482 products):
/home/nataliya/dump/10xxxxx/100xxxx/1000006/
/home/nataliya/dump/10xxxxx/100xxxx/1000007/
...
Where 1000006 and 1000007 are the product's id.
Each folder contains:
description.txt (text)
details.csv (name, oldprice, price)
images.csv (url, size)
How do I import them into MySQL, using PHP, as following:
id, name, oldprice, price, description (table `products`)
product_id, url, size (table `images`)
I apologize in advance if the question is not relative to this website, and thank everyone who wish to help me.
EDIT: Just to clarify, I'm asking only for a guidance, not for a full code example. Just the proper functions of PHP, which will make it with a good performance, since I'm talking about a directory with more than 30 million files.
EDIT: Here's what I've done for now:
<?php
function ArrayCSV($file) {
$fh = fopen($file, 'r');
while (!feof($fh) ) {
$result[] = fgetcsv($fh, 1024);
}
fclose($fh);
return $result[1];
}
$products = array();
$images = array();
foreach(scandir(dirname(__FILE__) . '/dump/') as $dir_global) {
if($dir_global != '.' && $dir_global != '..' && $dir_global != '.DS_Store') {
foreach(scandir(dirname(__FILE__) . '/dump/' . $dir_global) as $dir_local) {
if($dir_local != '.' && $dir_local != '..' && $dir_local != '.DS_Store') {
foreach(scandir(dirname(__FILE__) . '/dump/' . $dir_global . '/' . $dir_local) as $id) {
if($id != '.' && $id != '..' && $id != '.DS_Store') {
$dir = dirname(__FILE__) . '/dump/' . $dir_global . '/' . $dir_local . '/' . $id;
$product = ArrayCSV($dir . '/details.csv');
$image = ArrayCSV($dir . '/images.csv');
$products[] = array(
'id' => $id,
'name' => $product[0],
'oldprice' => $product[1],
'price' => $product[2],
'description' => file_get_contents($dir . '/description.txt')
);
$images[] = array(
'product_id' => $id,
'url' => $image[0],
'size' => $image[1]
);
}
}
}
}
}
}
try {
$DBH = new PDO("mysql:host=localhost;dbname=application", 'root', '');
$DBH->exec("SET NAMES utf8");
}
catch(PDOException $e) {
//
}
foreach($products as $product) {
$STH = $DBH->prepare("INSERT INTO products (id, name, oldprice, price, description) VALUES (:id, :name, :oldprice, :price, :description)");
$STH->execute($product);
}
foreach($images as $image) {
$STH = $DBH->prepare("INSERT INTO images (product_id, url, size) VALUES (:product_id, :url, :size)");
$STH->execute($image);
}
?>
I would suggest familiarizing yourself with the following function scandir() , file_get_contents() and finally, all the mysqli functions of PHP as they would be the key to what you'd need to do here.
Hope this helps!
add.php(When user click add photo)
<div class="col-lg-12">
<div class="form-group" id="image">
<label>Auction Image</label>
<div action="uploadImages.php" class="dropzone" id="uploadImageForm"></div>
<span class="help-block" id="image-error"></span>
</div>
</div>
<script>
$(function () {
Dropzone.options.uploadImageForm = false;
Dropzone.options.uploadImageForm = {
paramName: "file",
maxFilesize: 1,
acceptedFiles: 'image/*',
maxFiles: 5,
dictDefaultMessage: '<img src="images/icon_images.svg" width="100"/><br/><br/>Drop auction image here',
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'POST',
url: 'delete.php',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
};
</script>
UploadImages.php
<?php
session_start();
require 'config/database.php';
if (!isset($_SESSION['user'])) {
exit;
}
else if (!empty($_FILES)) {
$auctionImage = array();
$size = getimagesize($_FILES['file']['tmp_name']);
if (!$size) {
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode(['error']);
exit;
}
else {
$n = 0;
$tempFile = $_FILES['file']['tmp_name'];
$imageName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
$targetFile = $targetPath . $imageName;
$filename = $_FILES["file"]["name"];
move_uploaded_file($tempFile,$targetFile);
// isset id = insert gallery image into database
if (isset($_GET['id'])) {
$stmt = $db->prepare("INSERT INTO image (user_id, related_id, related_type, url) VALUES (:uid, :id, 'gallery', :url)");
$stmt->bindParam(':uid', $_SESSION['user']['id']);
$stmt->bindParam(':id', $_GET['id']);
$stmt->bindParam(':url', $imageName);
$stmt->execute();
}
else {
$auctionImage[] = $filename;
}
}
if (!empty($auctionImage)) {
// record uploaded image name, will store into session
// store uploaded image into session
//$_SESSION["auctionImages"] = array();
$_SESSION["auctionImages"][] = $auctionImage;
}
}
delete.php
<?php
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
unlink($targetPath.$_POST['id']);
session_start();
$a = $_POST['id'];
$key=array_search($a,$_SESSION['auctionImages']);
if($key!==false){
unset($_SESSION['auctionImages'][$key]);
$_SESSION["auctionImages"] = array_values($_SESSION["auctionImages"]);
echo '<pre>'; print_r($_SESSION['auctionImages']);
}
To use session variables, please add session_start() at the begin of your files, otherwise they aren't used. Secondly you are adding an array into a next array.
so you have to use
$_SESSION["auctionImages"] = $auctionImage;
or
$key=array_search($a[0],$_SESSION['auctionImages']);
Further debugging can be done by print_r($_SESSION); so you can track the contents of this array
The Problem -- What you should do:
You basically have to populate the SESSION variable like this:
$_SESSION["auctionImages"] = array(
"IMG_2923.JPG", "IMG_2924.JPG"
);
You're meant to address each element therefore, like this:
$_SESSION["auctionImages"][$n];
$n is the numbered index value for a particular element in the array. Therefore, if $n is 0, the array would return "IMG_29.29.JPG" and if the $n is 1, the array would return "IMG_2924.JPG".
However, you are populating the array like this:
$_SESSION["auctionImages"][] = array(
"IMG_2923.JPG", "IMG_2924.JPG"
);
If you dump this array, it will give you:
array(
array(
"IMG_2923.JPG", "IMG_2924.JPG"
)
);
Which is not the behaviour you require.
Solution
$filename = $_FILES["file"]["name"];
if(!is_array($_SESSION["auctionImages"])) {
$_SESSION["auctionImages"] = [];
}
$_SESSION["auctionImages"][] = $filename;
This is more shorter, cleaner and neater.
Also, you can use the alternative array syntax which is [ and ]. So, you can declare arrays using $var = []; which is shorter than $var = array();.
Firstly, the variable $a is the text to be searched in the array.
$key = array_search($a, $_SESSION["auctionImages"]);
if ($key !== false) {
unset($_SESSION["auctionImages"][$key]);
}
This is the second part of the code. This is all you need to have.
Also, make sure you have started the session by invoking session_start() in the top of the file if you haven't done yet.
A few comments
Consider taking a look at the Unofficial PHP standards here. It would be better if you name your variables in $camelCase. Therefore, it would be better to rename $filename to $fileName.
Also good job on using strict comparison which is !==.
Also, use more meaningful variable names. $a does not make sense. Something like $searchString would be really meaningful and the code will self-document your code.
Links
is_array - Returns TRUE if the passed identifier is an array, otherwise returns FALSE.
Let's now solve the problem with the full code you have given me. Let's start with delete.php:
<?php
session_start();
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
if(!isset($_POST['id'])) {
echo "ID has not been defined!";
exit;
}
$id = $_POST['id'];
unlink($targetPath . $id);
$key = array_search($id, $_SESSION['auctionImages']);
if ($key !== false) {
unset($_SESSION['auctionImages'][$key]);
echo '<pre>';
print_r($_SESSION['auctionImages']);
}
Now, let's fix your UploadImages.php file:
<?php
session_start();
require 'config/database.php';
if (!isset($_SESSION['user'])) {
exit;
}
if (!empty($_FILES)) {
if(!isset($_SESSION["auctionImages"]) && !is_array($_SESSION["auctionImages"])) {
$_SESSION["auctionImages"] = [];
}
$size = getimagesize($_FILES['file']['tmp_name']);
if (!$size) {
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode(['error']);
exit;
}
else {
$tempFile = $_FILES['file']['tmp_name'];
$imageName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
$targetFile = $targetPath . $imageName;
$fileName = $_FILES["file"]["name"];
move_uploaded_file($tempFile, $targetFile);
// isset id = insert gallery image into database
if (isset($_GET['id'])) {
$stmt = $db->prepare("INSERT INTO image (user_id, related_id, related_type, url) VALUES (:uid, :id, 'gallery', :url)");
$stmt->bindParam(':uid', $_SESSION['user']['id']);
$stmt->bindParam(':id', $_GET['id']);
$stmt->bindParam(':url', $imageName);
$stmt->execute();
}
else {
$_SESSION["auctionImages"][] = $fileName;
}
}
}
You have a problem here
$_SESSION["auctionImages"][]= $auctionImage;
Variable $auctionImage itself an array so need not to assign as an array again in SESSION variable. Make it as
$_SESSION["auctionImages"]= $auctionImage;
It works fine for me.
below is the code I worked.
<?php
//$filename = $_FILES["file"]["name"];
$auctionImage = array();
$auctionImage = array('IMG_2923.JPG', 'IMG_2924.JPG', 'IMG_2925.JPG'); // assigning sample variables // will be IMG_2923.JPG, IMG_2924.JPG and etc
$_SESSION["auctionImages"]= $auctionImage; // Removed '[]' from your coding
$a = 'IMG_2923.JPG'; // Assigning for testing purpose
$key=array_search($a,$_SESSION['auctionImages']);
if($key!==false)
unset($_SESSION['auctionImages'][$key]);
$_SESSION["auctionImages"] = array_values($_SESSION["auctionImages"]);
echo '<pre>'; print_r($_SESSION['auctionImages']); // Printing final session value. It prints without the key image name
?>
I'm creating a form to upload a file, using yii and php 5.5.3. Here is my code in the controller:
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if (!empty($setting->image_file)) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
mkdir("uploads", 0777, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
image_file is an extra attribute in model:
array('image_file', 'file', 'types' => 'gif, jpg, jpeg, png', 'maxSize' => 1024 * 1024, 'tooLarge' => 'File upload must not exceed 1MB.'),
and here is the view:
<input type="file" name="settings[store_logo]" class="input-small">
$setting->image_file->saveAs can successfully upload the file, but it also generates
Error 500 Creating default object from empty value
What went wrong? Any help would be much appreciated.
i guess, the $_FILES['settings']['name'] has a empty value in the last Key.
If you upload a File(s), they will be process as expected. The last value in your POST-array cause a NULL-return here:
// $setting === null
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName))
and this call throws the 500.
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
This is my Version of your code:
<?php
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
// catch null-return
if(!$setting) {
echo "can't find stuff at<pre>"; print_r($settingName); echo "</pre>";
continue;
}
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if ($setting->image_file) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
// dont 0777!
mkdir("uploads", 0740, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
?>
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 .