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
?>
Related
I'm trying to create a new folder within the upload folder so that a user can upload file to there own folder.
Can I do this using PHP or do I need to a column "LONGBLOB" in MYSQL?
I've read that it's not good practice to store images in you database
<?php
header('Content-Type: application/json');
$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];
if(!empty($_FILES["file"])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if ($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file
);
}else{
$failed[] = array(
'name' => $name);
}
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed ));
}
?>
Assuming you have the user's username or id in a session variable then that could be used as the basis for the new folder into which he/she would upload files.
Obiously that same username,id would have to be used when they wish to download the file. By storing a hash and the filepath you can generate links that do not reveal filename, folder path, owner etc as the db could check the ash and return the file and path when needed.
The following is an untested example of generating the user's own folder and using that in the upload process - hope it gives you some ideas / guidance.
<?php
$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];
/*
generate a suitable name for the new folder,
remove characters which might be troublesome
*/
$userdir = str_replace(
array("'",'"','-'),
array('','','_'),
$_SESSION['username']
);
/*
new path into which the files are saved
It might be better to have the files
stored outside of the document root.
*/
$savepath = 'uploads/' . $userdir;
/* create the folder if it does not exist */
if( !file_exists( $savepath ) ) {
mkdir( $savepath );
chown( $savepath, $username );
chmod( $savepath, 0644 );
}
if( !empty( $_FILES["file"] ) ) {
foreach( $_FILES['file']['name'] as $key => $name ) {
if( $_FILES['file']['error'][$key] === 0 ) {
$temp = $_FILES['file']['tmp_name'][$key];
/*
is there anything to be gained by hashing the filename?
the hash would be the same for filenames with the same
name anyway.
If the file is large, calculating the hash of the file could
take some time...
*/
$ext = explode('.', $name);
$ext = strtolower( end( $ext ) );
$file = md5_file( $temp ) . time() . '.' . $ext;
/* generate a random hash to use in downloads */
$hash=uniqid( md5( date(DATE_COOKIE) ) );
/* here probably - store reference in db? Assign permissions based upon owner etc */
$sql='insert into `table` (`filename`,`username`,`uid`,`datetime`,`hash`) values (?,?,?,?,?);';
/* bind params and execute - not shown */
if ( in_array( $ext, $allowed ) === true && move_uploaded_file( $temp, "{$savepath}/{$file}") === true ) {
$succeeded[] = array( 'name' => $name, 'file' => $file );
}else{
$failed[] = array( 'name' => $name );
}
}
}
}
if (!empty($_POST['ajax'])) {
header('Content-Type: application/json');
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed ));
} else {
header( 'HTTP/1.1 404 Not Found', true, 404 );
}
?>
In my database I have a varchar field to save the path include the name of an imagefile. In my viewscript I also use this field. If I insert for a test a pathname in my database via phpadmin everything works fine.
If I use my Controller addAction I can´t save the path, without error.
Here is my addAction:
$form = new Application_Form_Buch();
$form->submit->setLabel('Add');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$autor = $form->getValue('autor');
$verlag = $form->getValue('verlag');
$titel = $form->getValue('titel');
if( $form->getElement('datei')->receive() <> 1)
{
echo ' filename: '. $form->getElement('datei')->receive();
$imagepath = $form->getElement('datei')->getFileName();
//echo ' filename: '. $form->getElement('datei')->getFileName();
$pathparts = pathinfo($form->getElement('datei')->getFileName());
//echo ' pathparts: '. $pathparts;
//then get the part that you want to use
$originalFilename = $pathparts['basename'];
//echo ' originalFilename: '. $originalFilename;
//echo ' Test basename: '. $originalFilename['basename'];
$form->getElement('datei')->addFilter('Rename','images' ); //'/images/upload/',$originalFilename
//rename funktioniert so nicht
$originalFilename = $pathparts['basename'];
$imagepath=$form->getElement('datei')->getFileName();
$imagepath = str_replace($imagepath, "/images/cover/".$originalFilename, $imagepath); //funktioniert !!!
//echo ' imagepath: '. $imagepath;
$books = new Application_Model_DbTable_Bibliothek();
$books->addBook( $autor, $titel, $verlag, $imagepath );
}
else{
$imagepath=NULL;
}
// $this->_helper->redirector('index');
} else {
$form->populate($formData);
}
}
Please don´t mind I tried a bit around, so I have some comments left. I tested the variable $imagepath and it delivers the wanted value, which is: /images/cover/imagename.jpg. Where is the error in this pathvalue?
And here is my add Function which I use to store in my database:
public function addBook($autor, $titel, $verlag, $pfad)
{
$data = array(
'autor' => $autor,
'titel' => $titel,
'verlag' => $verlag,
'pfad' => $pfad,
);
$this->insert($data);
}
It works quite fine, it saves all comming data instead of the $pfad variable.
NEW:
must be something with the format of $imagepath, I just added for testing: $imagepath= '/images/cover/Labyrinth_200.jpg'; and find the value in my database table. So the error should be in the format of getting the value of $imagepath.
I just found my (very stupid) error.
I changed the blocks in my control structure like following:
if( $form->getElement('datei')->receive() <> 1)
{
$imagepath=NULL;
}
else{
echo ' filename: '. $form->getElement('datei')->receive();
$imagepath = $form->getElement('datei')->getFileName();
//echo ' filename: '. $form->getElement('datei')->getFileName();
$pathparts = pathinfo($form->getElement('datei')->getFileName());
//echo ' pathparts: '. $pathparts;
//then get the part that you want to use
$originalFilename = $pathparts['basename'];
//echo ' originalFilename: '. $originalFilename;
//echo ' Test basename: '. $originalFilename['basename'];
$form->getElement('datei')->addFilter('Rename','images' ); //'/images/upload/',$originalFilename
//rename funktioniert so nicht
$originalFilename = $pathparts['basename'];
$imagepath=$form->getElement('datei')->getFileName();
$imagepath = str_replace($imagepath, "/images/cover/".$originalFilename, $imagepath); //funktioniert !!!
//echo ' imagepath: '. $imagepath;
}
//$imagepath= '/images/cover/Labyrinth_200.jpg';
$books = new Application_Model_DbTable_Bibliothek();
$books->addBook( $autor, $titel, $verlag, $imagepath );
Before that I tried if( $form->getElement('datei')->receive() = 1) to validate my condition. But I got an error. So I switched the two blocks and now it works.
Earlier I have a form that ask user to upload a picture and I have this function:
function fileUploaded() {
$fileName = $_FILES ['picture'] ['name'];
$pathOfFile = "/images/";
$fileTmpLoc = $_FILES ['picture'] ["tmp_name"];
$fileResult = move_uploaded_file ( $fileTmpLoc, $pathOfFile );
if (isset ( $fileName )) {
return true;
}
}
Basically it moves the uploaded picture to images file. Then I am calling this function in an if statement:
if (fileUploaded () == true) {
if ($fileResult) {
/*checking the size of file*/
}
}
else {
$fileName = "default.jpg";
}
After when I try to upload and submit it gives the error in the below:
Fatal error: Call to undefined function fileUploaded()
What should be the problem?
Thanks.
You don't return a default value in your function. Maybe it's the problem :
function fileUploaded() {
$fileName = $_FILES ['picture'] ['name'];
$pathOfFile = "/images/";
$fileTmpLoc = $_FILES ['picture'] ["tmp_name"];
$fileResult = move_uploaded_file ( $fileTmpLoc, $pathOfFile );
if (isset ( $fileName )) {
return true;
}
return false;
}
//functions.php
function fileUpload($path) {
if(!isset($_FILES['picture'])) return false;
$fileName = $_FILES['picture']['name'];
$fileTmpLoc = $_FILES['picture']['tmp_name'];
if(move_uploaded_file ($fileTmpLoc, $path)) return $fileName;
return false;
}
//main.php
include('functions.php');
$fileName = fileUpload('/images/');
if($fileName === false) {
$fileName = 'default.jpg';
}
//do the rest here
Something similar to the above code. Since your function is in a different file, you need to include it (or require it)
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?
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 .