I'm a PHP beginner and i managed to muscle up a code which has a person upload up to 4 documents to a designated folder on a server. I'm now having trouble writing code which takes these 4 document names and adds them to that person's column with the rest of input data. I believe the right approach is to go with a "foreach" loop which increments variable name every time it goes through uploaded file names. I've tried doing this with $documentname[$i] = $file_name; but it's not working.
This is what I have so far:
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
$i=1;
foreach ($_FILES['files']['tmp_name'] as $key => $value) {
$file_tmpname = $_FILES['files']['tmp_name'][$key];
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$documentname[$i] = $file_name;
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
echo "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
} else {
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
echo "Error uploading {$file_name} ";
echo "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
echo "No files selected.";
}}
And this is the sql code:
if (isset($_POST['signup'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$documentname1 = $_POST['documentname1'];
$documentname2 = $_POST['documentname2'];
$documentname3 = $_POST['documentname3'];
$documentname4 = $_POST['documentname4'];
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
So the question is: is it possible to iterate through the uploaded files name array and assign each file name a variable like #documentname1,#documentname2,... to write these names in the database?
Thank you in advance!
Change your code to look like this. And also use prepared statement - PDO
if (isset($_POST['signup'])) {
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countfiles = count($_FILES['files']['name']);
$doc_name = [];
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
for ($i=0;$i<$countfiles;$i++) {
$file_tmpname = $_FILES['files']['tmp_name'][$i];
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$doc_name[] += $_FILES['files']['name'][$i];
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
$error[] = "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
$success[] = "{$file_name} uspješno uploadan <br />";
} else {
$error[] = "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
$error[] = "Error uploading {$file_name} ";
$error[] = "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
$error[] = "No files selected.";
}}
if (!isset($error)) {
$documentname1 = $doc_name[0]
$documentname2 = $doc_name[1]
$documentname3 = $doc_name[2]
$documentname4 = $doc_name[3]
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
}
}
to show errors on your html
if(isset($error)){
foreach($error as $error){
echo '<div class="alert alert-danger" role="alert">
<button class="close" data-dismiss="alert"></button>' .$error.'<br /> </div>';
}
}
to show success
if(isset($success)){
foreach($success as $success){
echo '<div class="alert alert-success" role="alert">
<button class="close" data-dismiss="alert"></button>' .$success.'<br /> </div>';
}
}
Related
other queries working through the foreach loop.but file upload for 1st index of array.this is not multiple file upload.i wanna upload same file in different names for each users.
foreach($_POST['groupmem'] as $user){
//Some Queries
$filename2 = str_replace(" ", "_","{$user}.{$_FILES['proposal']['name']}");
$destination2 = '../img/proposal/' . $filename2;
$extension2 = pathinfo($filename2, PATHINFO_EXTENSION);
$file2 = $_FILES['proposal']['tmp_name'];
$size2 = $_FILES['proposal']['size'];
if (!in_array($extension2, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['proposal']['size'] > 200000000) { // file shouldn't be larger than 200Megabyte
echo "File too large!";
} else {
if (move_uploaded_file($file2, $destination2)) {
$sql = "UPDATE project SET proposal_name='$filename2' WHERE u_id='{$user}' ";
if (mysqli_query($conn, $sql)) {
echo "File uploaded successfully";
}
} else {
echo "Failed to upload file.";
}
}
}
you can not do move_uploaded_file inside the loop
$user1 = $_POST['groupmem'][0];
$filename1 = str_replace(" ", "_","{$user1}.{$_FILES['proposal']['name']}");
$destination1 = '../img/proposal/' . $filename1;
$extension1 = pathinfo($filename1, PATHINFO_EXTENSION);
$file1 = $_FILES['proposal']['tmp_name'];
$size1 = $_FILES['proposal']['size'];
if (!in_array($extension1, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['proposal']['size'] > 200000000) { // file shouldn't be larger than 200Megabyte
echo "File too large!";
} else {
if (move_uploaded_file($file1, $destination1)) {
foreach($_POST['groupmem'] as $user){
$filename2 = str_replace(" ", "_","{$user}.{$_FILES['proposal']['name']}");
$destination2 = '../img/proposal/' . $filename2;
if ($user <> $user1) {
if (!copy($destination1, $destination2)) echo "failed to copy $file...\n";
}
$sql = "UPDATE project SET proposal_name='$filename2' WHERE u_id='{$user}' ";
if (mysqli_query($conn, $sql)) {
echo "File uploaded successfully";
}
}
} else {
echo "Failed to upload file.";
}
}
is their any way to modify this code
<?php
$desired_dir= ($_SERVER['DOCUMENT_ROOT']).'/cert/uploads/';
if(isset($_FILES['files'])){
$cat_name='image/*';
if($cat_name==""){
echo "Category Required";
/*header('Refresh: 1;url=addfile.php');*/
}
else{
$count=0;
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$size =$_FILES['files']['size'][$key];
$file_f = $size / 1024;
$file_size =round($file_f);
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
$path="uploads/";
if($size==0){
echo "<h6 style='color:red'>$file_name Exeeds upload limit</h6>";
}
else{
if (file_exists("$desired_dir" . $file_name))
{
echo "<h6 style='color:red'>".$file_name . " already exists.</h6>";
}
else
{
$query="INSERT into tblphotos VALUES('','$file_name')";
if(mysqli_query($con, $query)){
move_uploaded_file($file_tmp,"$desired_dir".$file_name);
//echo "<p style='color:blue'>$file_name Uploaded</p";
$count=$count+1;
}
else{
echo "Error in adding Files";
}
}
}
}
echo "<h6 style='color:blue'>"."$count Files Uploaded<h6>";
/*header('Refresh: 2;url=addfile.php');*/
}
}
?>
to change the name of every image i upload. for example i have a $id = 1 in my scipt
i want the combination of the id and the arrays to be its name just like example below.
1_[0].jpg, 1_[1].jpg, 1_[2].jpg
Thank You
if you already have $id = 1
Then try this :
$file_name = $id.'['. $key.$_FILES['files']['name'][$key] . ']';
I am used to writing AJAX using the following structure, where I would end up sending variables to PHP
function requestToggle(type, user, elem) {
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "request_system.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText == "request_sent") {
_(elem).innerHTML = 'OK Request Sent';
} else if (ajax.responseText == "unrequest_ok") {
_(elem).innerHTML = '<button onclick="requestToggle(\'request\',\'<?php echo $u; ?>\',\'requestBtn\')">Request Number</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type=" + type + "&user=" + user);
}
The example that I want to work on is for a photo upload form and the PHP script is using the $_FILES array but I am unsure how I would go about passing this array to the PHP using AJAX.
Here is the PHP
<?php
$result = "";
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
$result = "That image has no dimensions";
echo $result;
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
$result = "Your image file was larger than 1mb";
echo $result;
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
$result = "Please only JPG, GIF or PNG images";
echo $result;
exit();
} else if ($fileErrorMsg == 1) {
$result = "An unknown error occurred";
echo $result;
exit();
}
$sql = "SELECT profilePicture FROM User WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
//delete old pic if set
if($avatar != ""){
$picurl = "users/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
//move file from temp folder to users folder
$moveResult = move_uploaded_file($fileTmpLoc, "users/$log_username/$db_file_name");
if ($moveResult != true) {
$result = "File upload failed";
echo $result;
exit();
}
include_once("image_resize.php");
//replace original file with resized version
$target_file = "users/$log_username/$db_file_name";
$resized_file = "users/$log_username/$db_file_name";
$wmax = 400;
$hmax = 600;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE User SET profilePicture='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
//header("location: user.php?u=$log_username");
$result = "upload_success";
echo $result;
exit();
}
?>
UPLOAD FORM
$avatar_form = '<div class="bhoechie-tab-content" id="uploadphoto">';
$avatar_form .= '<center>';
$avatar_form .= '<form id="avatar_form"" method="post" enctype="multipart/form-data">';
$avatar_form .= '<h1>Change avatar</h1>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '<p id="status"></p>';
$avatar_form .= '</form>';
$avatar_form .= '</center></div>';
You can easily enough pass an array eg ajax.send("type=" + type + "&user=" + user + "&files=" + files);
Having not seen the rest of your code I can't provide a full answer, but I'm assuming you're somehow creating a files array in js and want to pass that to the php? If so, the variable 'files' would then be using in PHP like:
$files= $_REQUEST['files'];
This is my code, and the image is uploaded where i want it to, but its named 0."file extension" everytime, but i want the image to have the same name as the id of the object im submitting with this form.
id: 3
img name: 3."file extension"
My php:
<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data and avoid sql injection
$product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
$product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
$product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
$product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
$product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
$query = "INSERT INTO products
(product_name, product_price, product_desc,
product_category, product_attribute)
VALUES ('{$product_name}', '{$product_price}',
'{$product_desc}', '{$product_category}',
'{$product_attribute}')";
$filename = $_FILES["product_img"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["product_img"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg','.gif');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
// Rename file
$pid = mysqli_insert_id($connection);
$newfilename = $pid . $file_ext;
if (file_exists("img/product_img/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
header("location:product_list.php"); //maskes sure item is not recreated on refresh
$result = mysqli_query($connection, $query);
if ($result) {
$message = "Produkt oprettet.";
} else {
$message = "Der skete en fejl";
$message .= "<br />" . mysqli_error($connection);
}
}
?>
My html form:
<form action="" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<h4>Produkt navn</h4>
<input type="text" name="product_name" class="form-control"> <br>
<h4>Produkt pris</h4>
<input type="text" placeholder="DKK" name="product_price" class="form-control" style="width:30%;"><br>
<h4>Produkt beskrivelse</h4>
<textarea type="text" name="product_desc" rows="3" class="form-control"></textarea> <br>
<h4>Produkt kategori</h4>
<select name="product_category" class="form-control">
<option></option>
<option>Gummi ænder</option>
<option>Påklædning</option>
<option>Accessories</option>
</select> <br>
<h4>Produkt attribut</h4>
<input type="text" name="product_attribute" class="form-control" value=""> <br>
<input type="file" name="product_img"><br>
<input type="submit" name="submit_newProduct" class="btn btn-warning pull-right" value="Tilføj produkt">
</div>
</form>
Since, Query is executing after mysqli_insert_id(); Thats why it is returning 0.
Place your query before mysqli_insert_id(), then only you will get inserted id.
I placed / edited your code in my way. You can change it accordingly.
<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data and avoid sql injection
$product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
$product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
$product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
$product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
$product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
$query = "INSERT INTO products (product_name, product_price, product_desc, product_category, product_attribute)
VALUES ('{$product_name}', '{$product_price}', '{$product_desc}', '{$product_category}', '{$product_attribute}')";
$result = mysqli_query($connection, $query);
if ($result) {
$filename = $_FILES["product_img"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["product_img"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg','.gif');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
// Rename file
$pid = mysqli_insert_id($connection);
$newfilename = $pid . $file_ext;
if (file_exists("img/product_img/" . $newfilename)){
// file already exists error
echo "You have already uploaded this file.";
} else {
move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename)){
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000){
// file size error
echo "The file you are trying to upload is too large.";
}
else{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
$message = "Produkt oprettet.";
}
else {
$message = "Der skete en fejl";
$message .= "<br />" . mysqli_error($connection);
}
header("location:product_list.php"); //maskes sure item is not recreated on refresh
}
?>
I am working on php upload and i have an issue on how to automatically rename a file it does exist already in file folder. Could you give me any road or tips about it? thanks
here is my full code - the code is for testing purpose only
$destination = 'C:/upload_test/';
$max=75200;
if (isset($_POST['upload'])) {
if (isset($_FILES['image']['tmp_name'])) {
$fileTaille= $_FILES['image']['size'];
if ($fileTaille==true) {
if ($fileTaille > $max) {
echo "Your file is too large, select a file smaller than". " ".$fileTaille;
exit(include 'form.php');
}
}
else {
echo "No file selected";
exit(include 'form.php');
}
}
$file_type=getimagesize($_FILES['image']['tmp_name']);
if ($file_type==true) {
echo "File is an image - " .$file_type["mime"]." ";
}
else{
echo "Could not get file type";
}
$fileType = exif_imagetype($_FILES['image']['tmp_name']);
$allowed = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
if (!in_array($fileType, $allowed)) {
echo "File type not accepted, Only JPEG file allowed";
exit(include 'form.php');
}
$sanitize_file = preg_replace("/[^A-Z0-9\.\_-]/i", " ", $_FILES["image"]["name"]);
$fileName = $recipient . basename($recipient);
if (file_exists($fileName)) {
echo "File already exist";
exit(include 'form.php');
}
}
if (isset($_FILES['image']['tmp_name'])) {
$result = move_uploaded_file($_FILES['image']['tmp_name'], $recipient . $sanitize_file);
if ($result == true) {
echo "file moved "." ";
}else
{
echo "Could not move filed";
}
$permission = chmod($$recipient . $sanitize_file, 0644);
if ($permission==false) {
echo "No permission to the file";
}
else
{
echo "permission given";
}
}