HTML form to select multiple images.
Upload images to the server using PHP.
HTML:
<div style="margin-left:15%; margin-top:10%">
<form action="image-post-process.php" method="post" enctype="multipart/form-data" />
<table width="500px" align="center" bgcolor="blueskay">
<tr align="center">
<td colspan="2"><h2>Update Your Account</h2></td>
</tr>
<tr>
<td align="right">Customer Image:</td>
<td><input type="file" name="image[]" multiple /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="update" value="Update Account"/></td>
<td></td>
</tr>
</table>
</form>
</div>
File upload in PHP is the most used functionality for the web application. A single file or multiple files can be easily uploaded using PHP. PHP provides a quick and simple way to implement server-side file upload functionality. Generally, in the web application, the file is uploaded to the server and the file name is stored in the database. Later the files are retrieved from the server based on the file name stored in the database.
PHP:
#image-post-process.php
function imageFunction($imageName, $imageSize, $imageTmp)
{
$ext = pathinfo($imageName, PATHINFO_EXTENSION);
$allwoed_extention = array('pdf', 'png', 'jpg','JPEG','PNG','GIF','jpeg','JPG','PDF','docx');
if(in_array($ext, $allwoed_extention)){
if ($imageSize < 10485760) {
$newfilename = round(microtime(true)) ."_".$imageSize."_".$imageName;
move_uploaded_file($imageTmp, "image/".$newfilename);
return $newfilename;
}else{
echo "File Size Not Match";
}
}else{
echo "Extension Not Match";
}
}
$count = count($_FILES['image']['name']);
for ($i=0; $i < $count; $i++)
{
$imageName = $_FILES['image']['name'][$i];
$imageSize = $_FILES['image']['size'][$i];
$imageTmp = $_FILES['image']['tmp_name'][$i];
imageFunction($imageName, $imageSize, $imageTmp);
}
From my experience, I think you need to make every image think it is part of a group. so after declaring your function, you can include a "foreach"
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {// more code goes in here}
Related
I want to upload multiple files in 1 go. I have successfully tested the code on a single file upload (removed the for each loop) then its all working. File is uploading and checking file size/file type. But when I tried to put in a for loop to be able to do multiple files, its return "This file extension is not allowed, please upload a JPEG or PNG file"
HTML Code:
<form action="fileUpload.php" method="POST" enctype="multipart/form-data">
<table>
<tr><td>File 1</td> <td><input name="file_upload[]" type="file" class="multi"/> </td></tr>
<tr><td>File 2</td> <td><input name="file_upload[]" type="file" class="multi"/> </td></tr>
<tr><td></td> <td> <input type="submit" name="upload" value="Upload"><input type="reset"> </td> </tr>
</table>
</form>
PHP code:
foreach ($_FILES['file_upload']['tmp_name'] as $key => $tmp_name)
{
$rootDir = getcwd(); // get current working directory
$uploadDirectory = "/uploads/";
$fileExtensions = ['jpeg','jpg','png', 'pdf', 'docx',]; // Get all the file extensions
$fileType = $_FILES['file_upload']['type'][$key];
// $fileExtension = strtolower(end(explode('.',$fileName)));
$fileExtension = pathinfo($_FILES["file_upload"]["tmp_name"][$key]);
$uploadPath = $rootDir . $uploadDirectory . basename($fileName);
// echo $uploadPath;
}
?>
Change :
$fileExtension = pathinfo($_FILES["file_upload"]["tmp_name"][$key]);
to :
$fileExtension = pathinfo($_FILES["file_upload"]["name"][$key]);
$fileExtension = $fileExtension['extension'];
Previously your code checks for the temporary files extension.
I have a problem with 1 part of upload section, how to make the code continue the process if the upload section is empty? I already make the code, but everytime i skip the file button, it show echo 'ERROR: Ekstensi file tidak di izinkan!'
Here is my code:
insert_form
<form name="pegawai" action="insert-proses.php" method="post" enctype="multipart/form-data">
<table width="700px" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>NOKOM</b></td>
<td><b>:</b></td>
<td><input type="text" name="nokom" size="40" required /></td>
</tr>
<tr>
<td><b>NIP</b></td>
<td><b>:</b></td>
<td><input type="text" name="nip" size="40" required /></td>
</tr>
<tr>
<td><b>Nama</b></td>
<td><b>:</b></td>
<td><input type="text" name="nama" size="40" required /></td>
</tr>
<tr>
<td><b>Foto</b></td>
<td><b>:</b></td>
<td><input name="file" type="file" id="file" /></td>
</tr>
<tr>
<td></td>
<td></td>
<td><hr/><input type="submit" name="upload" value="Upload" /></td>
</tr>
</table>
</form>
insert-proses
<?php session_start();
include "config.php";
if(ISSET($_SESSION['superadmin'])) {
if($_POST['upload']) {
$nokom = $_POST['nokom'];
$nip = $_POST['nip'];
$nama = $_POST['nama'];
// Proses upload file
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['file']['name']; // Nama File
$file_ext = strtolower(end(explode('.', $file_name))); // Merubah nama file
$file_size = $_FILES['file']['size']; // Size File
$file_tmp = $_FILES['file']['tmp_name']; // Temp File
// Proses pengecekan upload file
if(in_array($file_ext, $allowed_ext) === true) {
if($file_size < 5220350) // Max upload file 5 MB / 1MB = 1044070 {
$lokasi = 'files/'.$nama.'.'.$file_ext;
move_uploaded_file($file_tmp, $lokasi);
$sql = "INSERT INTO pegawai (nokom,nip,nama,fileext,filegambar)
VALUES('$nokom','$nip','$nama','$file_ext','$lokasi')";
if (mysqli_query($conn, $sql)) {
echo "<script>alert('Insert data berhasil! Klik ok untuk melanjutkan');location.replace('pegawai-list.php')</script>";
}
else {
echo "Error updating record: " . mysqli_error($conn);
}
} else
{
echo '<div class="error">ERROR: Besar ukuran file (file size) maksimal 1 Mb!</div>';
}
} else
{
echo '<div class="error">ERROR: Ekstensi file tidak di izinkan!</div>';
}
}
} else
{
echo '<script>alert("Anda bukan Superadmin! Silahkan login menjadi Superadminterlebih dahulu");location.replace("index.php")</script>';
}
?>
Any help will be so thankful. Thanks
Jump over the complete upload part if there is no file uploaded, or better, run the upload part in your script only IF a file is uploaded:
if(isset($_FILES['file']) && is_array($_FILES['file'])) {
// your code to upload and check the file
}
I have a HTML form which is taking two entries and an image. I'm trying to upload the image to a "target" folder and then put a hyperlink to the image in my SQL database for retrieval in future, whilst also adding my other 2 entries form the form. I've followed a number of tutorials and I still can't seem to get this to work. At the moment the mySQL is working for the date and entry. Nothing is being entered into the table for picture, nor is the picture being uploaded to the target.
HTML code
<table border="0" cellpadding="3" cellspacing="1">
<form enctype="multipart/form-data" action="mob_create.php" method="post">
<tr>
<td width="150">Date:</td></tr><tr>
<td><input type="date" name="inputDate" value="" /> </td>
</tr>
<tr>
<td>Entry:</td></tr><tr>
<td width="300"><input size="34" type="text" name="inputEntry" value="" /></td>
</tr>
<tr>
<td width="150">Add an image (Optional):</td></tr><tr>
<td><input type="file" name="inputPic" accept="image/*" /></td></tr>
<tr>
<td><input type="submit" name="submit" /></td>
</tr>
</form>
</table>
PHP code
session_start();
include 'includes/Connect.php';
$target = "http://www.aam.prettypottery.ie/upload/";
$target = $target . basename( $_FILES['inputPic']['name']);
$date = $_POST['inputDate'];
$entry = $_POST['inputEntry'];
$picture = ($_FILES['inputPic']['name']);
$username=$_SESSION['myusername'];
if(!$_POST['submit']) {
echo "Please complete all entries of the form";
} else {
mysql_query("INSERT INTO `$username` (`Date`,`Entry`,`Picture`) VALUES('$date','$entry','$picture')") or die(mysql_error());
if(move_uploaded_file($_FILES['inputPic']['tmp_name'], $target)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
}
?>
The path for the target needed to be local.
Also ensure that the folder in the target is writeable.
session_start();
include 'includes/Connect.php';
$target = "upload/";
$target = $target . basename( $_FILES['inputPic']['name']);
$date = $_POST['inputDate'];
$entry = $_POST['inputEntry'];
$picture = ($_FILES['inputPic']['name']);
$username=$_SESSION['myusername'];
if(!$_POST['submit']) {
echo "Please complete all entries of the form";
} else {
mysql_query("INSERT INTO `$username` (`Date`,`Entry`,`Picture`) VALUES('$date','$entry','$picture')") or die(mysql_error());
if(move_uploaded_file($_FILES['inputPic']['tmp_name'], $target)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
}
?>
I have been trying for like 2 days now and its been frustrating! so hopefully i will learn something new today :)
Right, i have a php page where i can upload up to 3 images, the code is in a table (shrinked down to show only image inputs)
<tr>
<td align="right">1st Image</td>
<td><label>
<input type="file" name="fileField1" id="fileField1"/>
</label></td>
</tr>
<tr>
<td align="right">2nd Image</td>
<td><label>
<input type="file" name="fileField2" id="fileField2" />
</label></td>
</tr>
<tr>
<td align="right">3rd Image</td>
<td><label>
<input type="file" name="fileField3" id="fileField3" />
</label></td>
the feilds are then stored in a upload slot via php -
if (isset($_FILES['fileField1'])) {
$errors = array();
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['fileField1']['name'];
$global_file_name1 .= $file_name;
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['fileField1']['size'];
$file_tmp = $_FILES['fileField1']['tmp_name'];
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Extention not alowed';
}
if ($file_size > 2097152) {
$errors[] = 'File must be under 2MB';
}
if (empty($errors)) {
move_uploaded_file($file_tmp, 'upload/'.$file_name);
} else {
foreach ($errors as $error) {
echo $error, '<br />';
}
}
Code is same for all 3
My problem is on the edit pages where you can change the other feilds (like name, details etc) when you then press submit the name is then changed to nothing as after a submit it submits what it has got which is nothing as the image hasnt been changed and was left.
My question is can i find a way of stopping the image if statement from going if nothing has been selected?
Thanks in advance!
You can check the file size:
if ($_FILES['fileField1']['size']>0) {
// new file has been submitted. Process it.
} else {
// an empty field has been submitted. Do nothing.
}
I am trying to Upload an image and store it in the database. I have mentioned the code, but it is not working for me. I'm not able to find the bug. Please see if anybody can find the bug.
The code is:
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
if($_REQUEST['submit'])
{
if(($_FILES['file']['type']=="image/jpeg" or $_FILES['file']['type']=="image/pjpeg" or $_FILES['file']['type']=="image/gif") and ($_FILES['file']['size']<300000))
{
if($_FILES['file']['error']>0)
{
$err=" ERROR :: ".$_FILES['file']['error'];
}
else
{
echo "Upload :".$_FILES['file']['name']."<br/>";
echo "Type: ".$_FILES['file']['type']."<br/>";
echo "Size: ".($_FILES['file']['size']/1024)."Kb<br/>";
echo "Stored in: ".$_FILES['file']['tmp_name']."<br/>";
move_uploaded_file($_FILES['file']['tmp_name'],"upload/".$_FILES['file']['name']);
echo $_FILES['file']['name'];
echo $_FILES['file']['tmp_name']."qwerty";
$n=3000;
$fo=fopen("upload/".$_FILES['file']['name'],"r");
$fr=fread($fo,$n);
mysql_query("update user set pic='$fr' where id='$id'");
}
}
else
{
$err=" ERROR :: Invalid Image";
}
mysql_query("update user set name='$name' where id='$id'");
mysql_query("update user set email='$email' where id='$id'");
}
$sql="select * from user where id='$id'";
$con=mysql_query($sql);
list($idR,$nameR,$emailR,$pwdR,$dateR,$picR)=mysql_fetch_array($con);
?>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td colspan="2"><?php echo $err; ?></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name" value="<?php echo $nameR ?>" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" value="<?php echo $emailR ?>" /></td>
</tr>
<tr>
<td><label for="file">Upload or Change Pic:</label></td>
<td><input type="file" name="file" id="file" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Save"/></td>
</tr>
</table>
</form>
</body>
My code is not even able to upload the file. When I tried to echo the following, I found them empty:
echo "Name:".$_FILES['file']['name']."<br/>";
echo "Type: ".$_FILES['file']['type']."<br/>";
echo "Size: ".($_FILES['file']['size']/1024)."Kb<br/>";
echo "Stored in: ".$_FILES['file']['tmp_name'];
All the above fields are empty.
I don't know how this work but it didn't worked. I guess the problem is somewhere in my HTML code because the $_FILES values are none/empty. It is not retrieving the value from the form tag please check if my answer is incorrect to solve the problem or correct to how to solved this hard problem from science or other subject in computers and it form to been error or successfully.
Try this!
<?php
if(isset($_POST['submit']) && $_FILES['file']['size'] > 0)
{
// Data
$file_name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
// Check
$type = array(
'image/jpeg',
'image/gif',
'image/png',
);
$size = 300000;
if(in_array($file_type, $type) AND $file_size > $size)
{
echo 'Ooops! File type must be JPG, GIF or PNG. Or file size too big';
exit();
}
// Is error?
if ($_FILES["file"]["error"] > 0)
{
echo 'Upload Error';
exit();
}
else
{
echo 'File Name : '.$file_name.'<br />';
echo 'File Size : '.($file_size / 1024).' Kb<br />';
echo 'File Type : '.$file_type;
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Save"/>
</form>
If $_POST and $_FILES are both empty then you've exceeded the maximum post size ini ('post_max_size')
There are several settings in php.ini, including the maximum for an individual file ('upload_max_filesize'), and the maximum for all uploads ('post_max_size'). Make sure those ini settings are set correctly
Be careful of syntax if you hve edited it, it's picky when handling M, K or G (not KB, MB or GB), and don't exceed the bit size of your server, i.e. don't go above 4billion bytes on a 32 bit server.
Other causes of $_FILES being empty, but not $_POST. You don't have enough free space to upload your files, or you don't have permissions ot write to the temp directory. Check /tmp has enough space, and that you can write to it as apache/php user.
It worked when I moved my code on an independent .php file. And when I needed to upload I gave the link to that page in which independent uploading code was written. I don't know the reason behind this but this is how I solved it.
hmm....
try to change this line
if($_REQUEST['submit'])
to be
if(isset($_REQUEST['submit']))
and i think, this code
if(($_FILES['file']['type']=="image/jpeg" or $_FILES['file']['type']=="image/pjpeg" or $_FILES['file']['type']=="image/gif") and ($_FILES['file']['size']<300000))
can be simplified into
if(ereg("jpeg|pjpeg|jpg|gif|png", $_FILES['file']['type']) AND $_FILES['file']['size']<300000)
Good luck...