PHP - values not saved in array - php

Apologies, but couldn't find an answer to this already...
I have some PHP code that hits an error, which I echo and save to an array:
echo "File is not an image.";
$errors[] = "File is not an image";
The array is defined earlier:
$errors = array();
When I debug my web page, I can see the echo (so I know it's hitting that error) but the array is empty...screenshot below:
screenshot of web page
Any idea what I'm doing wrong? Or how to debug further?
Thanks!
Simon
EDIT: I noticed the array was declared twice. Removed that, no change.
Full code below
<?php
class BanditquotecustomformModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$varCountry = '';
$varRemarks = '';
$varContactEmail = '';
$varCustomerName = '';
$varPhone = '';
$varUrgency = '';
$sql = '';
$user_id ='';
/* For when I get this working!
$id_lang = Context::getContext()->language->id;
$category = Category::searchByName($id_lang,"personalised",true);*/
/*parent::initContent();*/
if ($this->context->customer->isLogged())
{
$this->setTemplate('customform.tpl');
$custfirstname = $this->context->customer->firstname;
$custlastname = $this->context->customer->lastname;
$custemail = $this->context->customer->email;
$this->context->smarty->assign('firstname', $custfirstname);
$this->context->smarty->assign('lastname', $custlastname);
$this->context->smarty->assign('customer_email', $custemail);
parent::initContent();
}
else
{
Tools::redirect('index.php?controller=authentication&back='.urlencode($this->context->link->getModuleLink('banditquote', 'customform')));
}
}
/* adds a new product for every quote */
private function addProduct($LastId)
{
$reference = 'CUST'.$LastId;
$name = $reference;
$product = new Product();
$languages=Language::getLanguages();
foreach($languages as $lang){
$product->name[$lang['id_lang']]=$name;
$product->link_rewrite[$lang['id_lang']]=$name;
$product->description[$lang['id_lang']]=$name;
}
$product->reference=$reference;
$product->active='1';
$product->available_for_order='1';
$product->is_virtual='1';
/* add product to category */
$product->id_category='2';
$product->id_category_default='2';
try{
$product->save();
} catch (PrestaShopException $e){
echo $e->displayMessage();
}
$product->addToCategories(array(2));
$product->save();
$prod_shopupdate = Db::getInstance()->Execute('
UPDATE `'.pSQL(_DB_PREFIX_).'product_shop`
SET `active` = "1",`available_for_order` = "1"
WHERE `id_product` = "'.((int)$product->id).'"');
return $product->id;
}
/* checking attachment */
private function checkImage()
{
$target_dir = '_THEME_PROD_PIC_DIR_';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 0;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$errors[] = $this->module->l('File is an image', 'customform');
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image";
$errors[] = "File is not an image";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$errors[] = $this->module->l('Sorry, file already exists', 'customform');
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$errors[] = $this->module->l('Sorry, your file is too large', 'customform');
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$errors[] = $this->module->l('Sorry, only JPG, JPEG, PNG & GIF files are allowed', 'customform');
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$errors[] = $this->module->l('Sorry, your file was not uploaded', 'customform');
// if everything is ok, try to upload file
}
else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
else {
$errors[] = $this->module->l('Sorry, there was an error uploading your file', 'customform');
}
}
return $uploadOk;
}
public function postProcess()
{
if (Tools::isSubmit('submit'))
{
$errors = array();
$failed = false;
$varUserId = (int)$this->context->customer->id;
$varRemarks = Tools::getValue('formRemarks');
$newRemarks = str_replace("'","''", $varRemarks);
$varCountry = Tools::getValue('formCountry');
$varContactEmail = Tools::getValue('formContactEmail');
$varCustomerName = Tools::getValue('formCustomerName');
$varPhone = Tools::getValue('formPhone');
$varUrgency = Tools::getValue('formUrgency');
if (empty($varRemarks))
{
$errors[] = $this->module->l('The message cannot be blank.', 'customform');
//d($errors);
}
else
{
$sql = "INSERT INTO `ps_quotes` (`quote_destin`,`quote_remarks`,`quote_email`,`quote_submitter_name`,`quote_phone`,`quote_urg`,`quote_user_id`)
VALUES('{$varCountry}','{$newRemarks}','{$varContactEmail}','{$varCustomerName}','{$varPhone}','{$varUrgency}','{$varUserId}');";
if (!Db::getInstance()->execute($sql))
{
die('Error creating Custom Order - Please contact admin#banditbirds.co.uk');
}
$quoteid = Db::getInstance()->Insert_ID();
$prod_id = $this->addProduct(Db::getInstance()->Insert_ID());
if ($prod_id == null )
{
die('Error creating Custom Product for Custom Order - Please contact admin#banditbirds.co.uk');
}
$updatesql = "UPDATE `ps_quotes` SET `quote_product_link` = $prod_id WHERE `quote_id` = $quoteid;";
Db::getInstance()->execute($updatesql);
//Check the uploaded attachment - if there
if ( $this->checkImage() )
{
// add ps_attachment
// link ps_attachment to product with ps_product_attachment
}
else
{
$this->context->smarty->assign('errors', $errors);
$failed = true;
d($errors);
}
//Mailing
$confirmation1 = '';
$template = 'banditquote';
$template_owner = 'banditquote_owner';
$template_vars = array(
'{banditquote_contactaddress}' => '',
'{banditquote_contacttown}' => '',
'{shop_url}' => Tools::getShopDomain(true),
/* in case we need to check ssl $this->ssl_enable ? Tools::getShopDomainSsl(true) : Tools::getShopDomain(true);*/
'{remarks}' => $varRemarks,
'{shipping_destination}' => $varCountry,
'{phone}' => $varPhone,
'{name_cust}' => $varCustomerName,
'{shipping_quantity}' => '',
'{paypal}' => '',
'{first_order}' => '',
'{urgency}' => $varUrgency,
'{language}' => (int)$this->context->language->id,
'{webmaster}' => 'admin#banditbirds.co.uk',
'{email}' => $varContactEmail,
'{shop_name}' => Configuration::get('PS_SHOP_NAME'),
'{owner_email}' => Configuration::get('PS_SHOP_EMAIL'));
$language = (int)$this->context->language->id;
$maildir = '/home/banditbi/public_html/modules/banditquote/mails/1.5/';
if ((Mail::Send($language, $template, Configuration::get('PS_SHOP_NAME'), $template_vars, $varContactEmail, null, null, null, null, null, $maildir,false,null)) &&
(Mail::Send($language, $template_owner, Configuration::get('PS_SHOP_NAME'), $template_vars, 'admin#banditbirds.co.uk', null, null, null, null, null, $maildir,false,null)))
$this->context->smarty->assign('confirmation1', 1);
else
{
if (is_null($confirmation1))
{
$this->_html .= '<div style="background:#F00; padding:5px; border:thin; border-color:#030; text-align:center">'.$this->l('CAPTCHA Error, please go back and try once more.').'</div><br />';
return $this->_html;
}
}
if( !$failed )
{
Tools::redirect('index.php');
}
}
$this->context->smarty->assign(array(
'id_customer' => (int)$this->context->customer->id,
'errors' => $errors,
'form_link' => $errors,
));
$this->setTemplate('customform.tpl');
}
}
}
?>

Make sure you are defining the array before attempting to store values into it.
$errors = array();
$errors[] = 'File is not an image';
Do not try to redefine the array after you add items to this array. Otherwise, you will reset the array effectively removing any items previously added.

Related

Why doesn't my file upload function work properly? PHP

Hi I have a file upload function. Controls file size and file type. If the file is in PDF format and is smaller than 10MB, everything works as it should.
If the file is not PDF, it should show me the message: "ERROR: You can just upload PDF files." but no message.
If the file size is larger than 10MB, it should show me the message: "ERROR: Max file size 10MB." but no message.
If the file is PDF but larger than 10MB, it shows me: "ERROR: All fields must be filled."
What is wrong with my code?
Function :
<?php
function file_create($file) {
if(isset($file)){
$errors = array();
$target_dir = "../files/";
$file_name = uniqid();
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_ext = strtolower(end(explode('.',$file['name'])));
if($file_type != "application/pdf") {
$error = "ERROR : You can upload just PDF files.";
array_push($errors, $error);
}
if($file_size > 1024*1024*10) {
$error = "ERROR : Max file size 10MB.";
array_push($errors, $error);
}
if(empty($errors) == true) {
move_uploaded_file($file_tmp,$target_dir.$file_name.".".$file_ext);
$errors['status'] = true;
$errors['patch'] = substr($target_dir.$file_name.".".$file_ext, 3);
} else {
$errors['status'] = false;
}
return $errors;
}
}
?>
Another File :
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$notice_title = secured_post("notice-title");
$notice_content = secured_post("notice-content");
// if there is empty field in form.
if (multi_empty($notice_title, $notice_content)) {
// if a file submitted.
if (isset($_FILES['notice-file'])) {
$notice_file = $_FILES['notice-file'];
// upload the file.
$upload = file_create($notice_file);
if ($upload['status'] == false) {
$size = count($upload);
for ($i=0; $i < $size; $i++) {
array_push($errors, $upload[$i]);
}
}
notice_create($conn, $notice_title, $notice_content, $upload['patch']);
} else {
notice_create($conn, $notice_title, $notice_content);
}
} else {
$error = "ERROR : All fields must be filled.";
array_push($errors, $error);
}
}
if ($errors) {
foreach ($errors as $error) {
echo "<div class='error'>".$error."</div></br>";
}
}
?>
Here's the problem. If your file is larger than 10MB then it can take some time to upload the file so you have to check if the $_FILES array is empty or not.
Try this:
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_FILES)) { //I've made changes to this line
$notice_title = secured_post("notice-title");
$notice_content = secured_post("notice-content");
// if there is empty field in form.
if (multi_empty($notice_title, $notice_content)) {
// if a file submitted.
if (isset($_FILES['notice-file'])) {
$notice_file = $_FILES['notice-file'];
// upload the file.
$upload = file_create($notice_file);
if ($upload['status'] == false) {
$size = count($upload);
for ($i=0; $i < $size; $i++) {
array_push($errors, $upload[$i]);
}
}
notice_create($conn, $notice_title, $notice_content, $upload['patch']);
} else {
notice_create($conn, $notice_title, $notice_content);
}
} else {
$error = "ERROR : All fields must be filled.";
array_push($errors, $error);
}
}
if ($errors) {
foreach ($errors as $error) {
echo "<div class='error'>".$error."</div></br>";
}
}
?>
And:
<?php
function file_create($file) {
if(!empty($file)){ //I've made changes to this line
$errors = array();
$target_dir = "../files/";
$file_name = uniqid();
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_ext = strtolower(end(explode('.',$file['name'])));
if($file_type != "application/pdf" || $file_ext != ".pdf") { //I've made changes to this line
$error = "ERROR : You can upload just PDF files.";
array_push($errors, $error);
}
if($file_size > (1024*1024*10)) {
$error = "ERROR : Max file size 10MB.";
array_push($errors, $error);
}
if(empty($errors) == true) {
move_uploaded_file($file_tmp,$target_dir.$file_name.".".$file_ext);
$errors['status'] = true;
$errors['patch'] = substr($target_dir.$file_name.".".$file_ext, 3);
} else {
$errors['status'] = false;
}
return $errors;
}
}
?>
Note: The $_FILES array can be set and empty at the same time so isset() can't help you here.

File name too long while uploading image in database

I have written a line of codes to upload an image in the database, however, trying to upload image gives me this error
File name too long
Following is my code to upload an image to database:
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
Is it because of permission issue or something else? If so, what is causing me this problem and how do I fix this?
this is how I upload the file into the server and save the file name + extension into the database.
<?php
include 'connection.php';
$id = $_POST['id'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$folder = 'images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt;
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '5MB'
if ($imgSize < 5000000) {
move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
$query = mysqli_query($con, "UPDATE `profile` SET `photo` = '$img' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Profile Updated'); window.location ='index.php?data=profile' </script>";
} else {
echo "<script>alert('Failed'); window.location ='index.php?data=profile' </script>";
}
?>
Hope this helps.
Cheers.

How to add user_id at the beginning of filename when upload to server

How to an add user_id ($_POST['pk']) at the beginning of the filename when I upload an image to server with the below function update_customer().
With this I can easily discover the correct files of a specific user.
Result should be:
filename = $_POST['pk'].'-'.$_POST['name']
function update_customer() {
if(isset($_POST['name']) && isset($_POST['pk'])) {
//print_r($_FILES['image']);exit;
$filename = '';
if(isset($_FILES['image']) && $_FILES['image']['tmp_name'] && $_FILES['image']['error'] == 0) {
$filename = $_FILES['image']['name'];
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/wp-content/uploads/agent_company_logos/';
$wp_filetype = wp_check_filetype_and_ext( $_FILES['image']['tmp_name'], $_FILES['image']['name'] );
if($wp_filetype['proper_filename'])
$_FILES['image']['name'] = $wp_filetype['proper_filename'];
if ( ( !$wp_filetype['type'] || !$wp_filetype['ext'] ) ) {
$arrErrors['file'] = __('File type not allowed', 'agent-plugin');
}
else {
move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir.$_FILES['image']['name']);
}
if(!empty($arrErrors) && count($arrErrors) == 0) {
die (json_encode(array('file' => agent_get_user_file_path($_FILES['image']['name']), 'caption' => '', 'status' => 1)));
}
//echo $_FILES['image']['name'];
}
$updated = $GLOBALS['wpdb']->update($GLOBALS['wpdb']->prefix.'agent_customer', array('company_logo' => $filename), array('user_id' => $_POST['pk']));
$dir = wp_upload_dir();
echo $dir['baseurl'] . '/agent_company_logos/'.$filename; exit(0);
}
echo 0;
die();
}
you can use
$basname = $_POST['pk'].basename($file);

File uploads fails when file name contains space

I have googled this question but did not find an answer. I am using the ng-file-upload Angular directive to upload images to my back-end. At the back-end I am using php to retrieve the image. It works fine if I select an image which contains no white space. But if I select an image which contains white space it throws an error. This is what I did
//app.js
Upload.upload({
url: "api/index.php/postNewFeedsWithPicture",
file: $scope.file,
method: "post"
}).then(function (response) {
$scope.isShowing = false;
if (response.data.error) {
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.error(response.data.message, {timeOut: 5000});
}
else {
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.success(response.data.message, {timeOut: 5000});
$scope.file = null;
}
}, function (reason) {
$scope.isShowing = false;
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.error('Message not posted! Network error', {timeOut: 5000});
});
in my html file i did this
<div role="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB">Upload</div>
in my php file I wrote a function that saves the image
function savePictureToDb($fileName, $dirName) {
$target_dir = "../image/" . $dirName . "/";
$target_file = $target_dir . basename($_FILES[$fileName]["name"]);
$uploadOk = 1;
$errorMsg = null;
$report = array();
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check file size. //20mb
if ($_FILES[$fileName]["size"] > 20000000) {
$uploadOk = 0;
$errorMsg = "File size is greater than 20 mega bytes";
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
$uploadOk = 0;
$errorMsg = "The file selected is not an image";
}
if ($uploadOk == 0) {
$report[ERROR] = TRUE;
$report[MESSAGE] = $errorMsg;
return $report;
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES[$fileName]["tmp_name"], $target_file)) {
rename($target_file, $target_dir . generateRandStr_md5(500) . "." . $imageFileType);
$response['path'] = basename($_FILES[$fileName]["name"]);
$report[ERROR] = FALSE;
$report[PATH] = $response['path'];
return $report;
} else {
$errorMsg = "Unexpected error";
$report[ERROR] = TRUE;
$report[MESSAGE] = $errorMsg;
return $report;
}
}
}
It works fine, but if the image contains white space this is the error i get when debugging
array (
'file' =>
array (
'name' => 'Age Declaration.jpg',
'type' => '',
'tmp_name' => '',
'error' => 1,
'size' => 0,
),
)
Rename the file name with random value
$filename1=explode(".", $file);
$extension=end($filename1);
$file=rand().time().".".$extension;
Or Use pathinfo() for extention
$ext = pathinfo($filename, PATHINFO_EXTENSION);

I can't upload multiple images using PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - Upload multiple images
I want to upload multiple images using PHP and I am stuck. I have the code but it uploads only 1 image.
<?php
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND (!empty($_POST['make'])) AND (!empty($_POST['model'])) AND (!empty($_POST['engine'])) AND (!empty($_POST['mileage'])) AND (!empty($_POST['exterior'])) AND (!empty($_POST['interior'])) AND (!empty($_POST['transmission'])) AND (!empty($_POST['body'])) AND (!empty($_POST['fuel'])) AND (!empty($_POST['drive'])) AND (!empty($_POST['doors'])) AND (!empty($_POST['description']))) {
$year = htmlspecialchars($_POST['year']);
$make = htmlspecialchars($_POST['make']);
$model = htmlspecialchars($_POST['model']);
$engine = htmlspecialchars($_POST['engine']);
$mileage = htmlspecialchars($_POST['mileage']);
$exterior = htmlspecialchars($_POST['exterior']);
$interior = htmlspecialchars($_POST['interior']);
$transmission = htmlspecialchars($_POST['transmission']);
$body = htmlspecialchars($_POST['body']);
$fuel = htmlspecialchars($_POST['fuel']);
$drive = htmlspecialchars($_POST['drive']);
$doors = htmlspecialchars($_POST['doors']);
$description = htmlspecialchars($_POST['description']);
$target = "images/default.jpg";
$msg = "";
if (!empty($_FILES['fisier']['name'])) {
$target = "images/";
$target = $target . basename($_FILES['fisier']['name']);
$file_size = $_FILES['fisier']['size'];
$file_type = $_FILES['fisier']['type'];
$ok = 1;
if ($file_size > 2048000) {
echo "Too large";
$ok = 0;
}
if ($file_type == "application/octet-stream") {
echo "no PHP";
$ok = 0;
}
if ($ok == 0) {
echo "No file saved";
} else {
if (!move_uploaded_file($_FILES['fisier']['tmp_name'],$target)) {
$target = "images/default.jpg";
$msg = "No file saved. ";
}
}
}
require_once("mysql_connect.php");
$sql = "INSERT INTO astonmartin VALUES('','$year','$make','$model','$engine','$mileage','$exterior','$interior','$transmission','$body','$fuel','$drive','$doors','$description','$target','$target2','$target3','$target4','$target5','$target6')";
mysql_query($sql) or die(mysql_error());
$msg .= "";
header("Location: add_user.php?msg=$msg");
} else {
$error = "Complete form";
}
}
?>
I think you need first this function assoc, here: multidimensional for loops in php
And continue;
<?php
$allowed_types = array(
'image/gif',
'image/jpeg',
// add your mime types more
);
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND ...
// that gives an associative array
// i think it's more handy in your case
$files = assoc($_FILES['fisier']);
// now you have a files like
// tmp_name => d:\tmp\abs123, name => cats.jpg, size => 128 ..
// tmp_name => d:\tmp\abs254, name => dogs.jpg, size => 211 ..
// ... more code here
// and here, remove this line
if (!empty($_FILES['fisier']['name'])) {
// put this. yes 6, cos you want 6 pics
if (count($files) == 6) {
// loop over files
foreach ($files as $i => $file) {
// create targets, securely
$targets[$i] =
'images/'. preg_replace('~[^\w\d\.]~i', '',
basename($file['name']));
// check some errors
if ($file['error'] == 0 && $file['size'] < 2048000
// check file type
&& in_array($file['type'], $allowed_types)) {
if (!move_uploaded_file(
$file['tmp_name'], 'images/'. $file['name'])) {
$targets[$i] = 'images/default.jpg';
// collect messages
$messages[] = $file['name'] . ' not saved!';
}
}
}
}
// and creating target 1 2 3 ...
$targets_string = '';
if (!empty($targets)) {
// this provides: '$target', '$target2', '$target3' ...
$targets_string = "'". join("', '", $targets) ."'";
}
// ... more code here
// and sql part
$sql = "INSERT INTO astonmartin VALUES('', '$year', '$make', ..."
// add target string
. "'$description', $targets_string";
// ... more code here
// msg part
$msg = empty($messages) ? '' : join('', $messages);
header("Location: add_user.php?msg=$msg");
?>

Categories