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";
}
}
Related
Is there any way to check if there will be an error on file uploading? Like putting a variable to know if there's an error on every else statement so that before it will prevent running the query. Because what's happening is even there's an error on moving/copying/deleting a file, it still runs the query.
$dir = './uploads/images/';
if ($_FILES['thumbnail']['size'] == 0 && $_FILES['thumbnail']['error'] > 0){
$new_path = $dir;
$new_file = $new_path . $exist_tn;
$move = rename($cur_file,$new_file);
if ($move) {
$thumbnail = $exist_tn;
} else {
echo "Error Moving File.";
}
}else{
$thumbnail = $thumb;
$deletefile = unlink($cur_file);
if($deletefile){
$targetPath = $dir.$thumbnail;
$sourcePath = $_FILES['thumbnail']['tmp_name'];
$movefile = move_uploaded_file($sourcePath,$targetPath);
if ($movefile) {
echo "File upload successfully.";
}else{
echo "Upload File Failed.";
}
}else{
echo "Delete File failed.";
}
}
$query = '
UPDATE
`mytbl`
SET
`title` = "'.$title.'",
`thumbnail` ="'.$thumbnail.'",
`date` = "'.$date.'",
`part` = "'.$part.'",
`tags`= "'.$tags.'"
WHERE
`id` = "'.$id.'"
';
$update = mysqli_query(db(),$query);
//Check if there's an error first then run query
if (checkCondition) {
if($update === TRUE){
echo "sql_update";
}else{
echo "sql_error";
}
} else {
echo "Error Found";
}
Use exit after echo if you don't want the query to run
e.g
$dir = './uploads/images/';
if ($_FILES['thumbnail']['size'] == 0 && $_FILES['thumbnail']['error'] > 0){
$new_path = $dir;
$new_file = $new_path . $exist_tn;
$move = rename($cur_file,$new_file);
if ($move) {
$thumbnail = $exist_tn;
} else {
echo "Error Moving File.";
exit();
}
}else{
$thumbnail = $thumb;
$deletefile = unlink($cur_file);
if($deletefile){
$targetPath = $dir.$thumbnail;
$sourcePath = $_FILES['thumbnail']['tmp_name'];
$movefile = move_uploaded_file($sourcePath,$targetPath);
if ($movefile) {
echo "File upload successfully.";
}else{
echo "Upload File Failed.";
exit();
}
}else{
echo "Delete File failed.";
exit();
}
}
$query = '
UPDATE
`mytbl`
SET
`title` = "'.$title.'",
`thumbnail` ="'.$thumbnail.'",
`date` = "'.$date.'",
`part` = "'.$part.'",
`tags`= "'.$tags.'"
WHERE
`id` = "'.$id.'"
';
$update = mysqli_query(db(),$query);
//Check if there's an error first then run query
if (checkCondition) {
if($update === TRUE){
echo "sql_update";
}else{
echo "sql_error";
}
} else {
echo "Error Found";
}
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>';
}
}
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.";
}
}
I have 3 file inputs that I've been trying to secure, but I haven't had success.
I need these file inputs to only take jpeg, jpg, png, and gif. I know the mime type is not reliable to use, therefore, I would like to no longer use it. And if there is a cleaner or faster way to do this in PHP procedure way than IF statements, would be better.
HTML code
<input type="file" name="index_desl_Cfile1" class="upload-image" />
<input type="file" name="index_desl_Cfile2" class="upload-image" />
<input type="file" name="index_desl_Cfile3" class="upload-image" />
PHP code
$target_dir = "../site_images/";
$index_deslC1 = $target_dir . basename($_FILES["index_desl_Cfile1"]["name"]);
$index_deslC2 = $target_dir . basename($_FILES["index_desl_Cfile2"]["name"]);
$index_deslC3 = $target_dir . basename($_FILES["index_desl_Cfile3"]["name"]);
// Check if file already exists
$src1 = 'http://localhost//397/admin/site_images/'.$index_deslC1;
$src2 = 'http://localhost/397/admin/site_images/'.$index_deslC2;
$src3 = 'http://localhost/397/admin/site_images/'.$index_deslC3;
if (#getimagesize($src1)) {
echo "Sorry, file already exists 1. ";
$uploadOk = 0;
}
else if (#getimagesize($src2)) {
echo "Sorry, file already exists 2. ";
$uploadOk = 0;
}
else if (#getimagesize($src3)) {
echo "Sorry, file already exists 3. ";
$uploadOk = 0;
}
$imageFileTypeC1 = $_FILES["index_desl_Cfile1"]["type"];
$imageFileTypeC2 = $_FILES["index_desl_Cfile2"]["type"];
$imageFileTypeC3 = $_FILES["index_desl_Cfile3"]["type"];
$allowed_types = array('image/jpg','image/png','image/jpeg','image/gif');
if (!in_array($imageFileTypeC1, $allowed_types)) {
echo "ILLEGAL FILE TYPE 1";
$uploadOk = 0;
}
else if (!in_array($imageFileTypeC2, $allowed_types)) {
echo "ILLEGAL FILE TYPE 2";
$uploadOk = 0;
}
else if (!in_array($imageFileTypeC3, $allowed_types)) {
echo "ILLEGAL FILE TYPE 3";
$uploadOk = 0;
}
else {
$uploadOk = 1;
}
if ($uploadOk == 0) {
echo " Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["index_desl_Cfile1"]["tmp_name"], $index_deslC1)) {
echo "The file ". basename( $_FILES["index_desl_Cfile1"]["name"]). " has been uploaded.";
}
else if (move_uploaded_file($_FILES["index_desl_Cfile2"]["tmp_name"], $index_deslC2)) {
echo "The file ". basename( $_FILES["index_desl_Cfile2"]["name"]). " has been uploaded.";
}
else if (move_uploaded_file($_FILES["index_desl_Cfile3"]["tmp_name"], $index_deslC3)) {
echo "The file ". basename( $_FILES["index_desl_Cfile3"]["name"]). " has been uploaded.";
}
It will have more than 3 file inputs.
I finally figured it out. Instead of using the if statements where I check the file types, I used the switch statement and it worked like a charm!
Here is all the code...
$target_dir = "../site_images/";
$index_deslC1 = $target_dir . basename($_FILES["index_desl_Cfile1"]["name"]);
$index_deslC2 = $target_dir . basename($_FILES["index_desl_Cfile2"]["name"]);
$index_deslC3 = $target_dir . basename($_FILES["index_desl_Cfile3"]["name"]);
// Check if file already exists
$src1 = 'http://localhost//397/admin/site_images/'.$index_deslC1;
$src2 = 'http://localhost/397/admin/site_images/'.$index_deslC2;
$src3 = 'http://localhost/397/admin/site_images/'.$index_deslC3;
if (#getimagesize($src1)) {
echo "Sorry, file already exists 1. ";
$uploadOk = 0;
}
else if (#getimagesize($src2)) {
echo "Sorry, file already exists 2. ";
$uploadOk = 0;
}
else if (#getimagesize($src3)) {
echo "Sorry, file already exists 3. ";
$uploadOk = 0;
}
$imageFileTypeC1 = $_FILES["index_desl_Cfile1"]["type"];
$imageFileTypeC2 = $_FILES["index_desl_Cfile2"]["type"];
$imageFileTypeC3 = $_FILES["index_desl_Cfile3"]["type"];
$allowed_types = array('image/jpg','image/png','image/jpeg','image/gif');
switch ($allowed_types) {
case in_array($imageFileTypeC1, $allowed_types):
echo "GOOD 1!";
$uploadOk = 1;
break;
case in_array($imageFileTypeC2, $allowed_types):
echo "GOOD 2!";
$uploadOk = 1;
break;
default:
echo "ILLEGAL FILE TYPE";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo " Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["index_desl_Cfile1"]["tmp_name"], $index_deslC1)) {
echo "The file ". basename( $_FILES["index_desl_Cfile1"]["name"]). " has been uploaded.";
}
else if (move_uploaded_file($_FILES["index_desl_Cfile2"]["tmp_name"], $index_deslC2)) {
echo "The file ". basename( $_FILES["index_desl_Cfile2"]["name"]). " has been uploaded.";
}
else if (move_uploaded_file($_FILES["index_desl_Cfile3"]["tmp_name"], $index_deslC3)) {
echo "The file ". basename( $_FILES["index_desl_Cfile3"]["name"]). " has been uploaded.";
}
I am trying to upload 2 files in a folder and save their name and image path in database, here is my html code:
<input class="field2" type="file" name="file[]" multiple="multiple" />
and my php code is :
$i=0;
$count=0;
foreach ($_FILES['file']['name'] as $filename)
{
if(file_exists('upload/'.$filename))
{
echo "That File Already Exisit";
break;
}
else
{
$target='upload/';//folder path
$tmp=$_FILES['file']['tmp_name'][$count];
$count=$count + 1;
$i=$i+1;
$target=$target.basename($filename);
move_uploaded_file($tmp,$target);
$sql = "UPDATE `fleet` SET `image$i`='$target',`image_name$i`='$filename' WHERE id='$id' ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}
the issue is image is not getting stored in a folder, i have create a folder named upload, but nothing works foe me
You can try this code:
<?php
$i=0;
$count=0;
foreach ($_FILES['file']['name'] as $filename)
{
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if(file_exists($upload_dir.$filename))
{
echo "That File Already Exist";
break;
}
else
{
$tmp = $_FILES['file']['tmp_name'][$count];
$count++;
$i++;
$target = $upload_dir.basename($filename);
if (is_dir($upload_dir) && is_writable($upload_dir)) {
move_uploaded_file($tmp,$target);
$sql = "UPDATE `fleet` SET `image$i`='$target',`image_name$i`='$filename' WHERE id='$id' ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
} else {
echo 'Upload directory is not writable, or does not exist.';
}
}
If you have:
Upload directory is not writable, or does not exist.
You should to a chmod or/and a chown command to give the permissions to write on the upload_dir.
instead of storing name in data base i am storing it in txt file(as per requirement)
<?php
if (isset($_FILES["uploaded_file"]["name"])) {
$imagename=$_POST['imagename'];
$name = $_FILES["uploaded_file"]["name"];
$tmp_name = $_FILES['uploaded_file']['tmp_name'];
$error = $_FILES['uploaded_file']['error'];
if (!empty($name)) {
$location = './uploads/';
if ( ! is_dir($location)) {
mkdir($location);
}
if (move_uploaded_file($tmp_name, $location.$name)){
echo 'Uploaded';
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","a+");
fwrite($fp,$imagename);
fclose($fp);
}
} else {
echo 'please choose a file';
}
}
?>