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] . ']';
Related
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 want a logged in user to add a profile picture. if the user havent added a picture, the default image should display.
here is the code I tried. The default image is not showing and it is displaying the amount of users in the database. I know I should use prepared statements, but dont know how to with adding a file.
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'pt');
if(isset($_POST['upload_submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$filesError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.',$_FILES['file']['name']);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','pdf');
if(in_array($fileActualExt,$allowed)){
if($_FILES['file']['error'] === 0){
if($_FILES['file']['size'] < 1000000){
$fileNameNew =
"profile".$_SESSION['username'].".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($_FILES['file']
['tmp_name'],$fileDestination);
$sql = "UPDATE users SET status = 0 WHERE
username='$_SESSION[username]';";
$result = mysqli_query($db, $sql);
header("Location: pic.php");
}else{
echo "Your file is too big!";
}
}else{
echo "You have an error uploading your file!";
}
}else{
echo "You cannot upload files of this type!";
}
}
?>
<?php
$sql = "SELECT * from users";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result)> 0){
while ($row = mysqli_fetch_assoc($result)){
$sqlimg = "SELECT * FROM users WHERE
username='$_SESSION[username]'";
$resultimg=mysqli_query($db,$sqlimg);
while($rowimg = mysqli_fetch_assoc($resultimg)){
echo "<div class=container>";
if($rowimg['status'] == 0){
echo "<img src=
'uploads/profile".$_SESSION['username'].".jpg'>";
}else{
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$_SESSION['username']."</p>";
echo "</div>";
}
}
}else{
echo "There are no users yet!";
}
if(isset($_SESSION['username'])){
echo "<form action='pic.php'
method='POST'enctype='mutlipart/form-
data'>
<input type='file' name='file'>
<button type='submit' name='upload_submit'>Upload</button>
</form>";
}else {
echo "You are not logged in!";
}
?>
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";
}
}
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';
}
}
?>