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.
}
Related
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}
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
}
Hi I can't seem to pinpoint what's wrong. I have a form with elements. Could you check the script? I just know it lacks something but a noob like me just doesn't know. Basically when the Smart Money radio button is selected, the BPI is disabled,and vice versa. It should insert the data inputs in the db. It works fine if the selected radio btn is BPI but if Smart money was selected and the user inputs data and BPI/file upload disabled, it doesn't insert anything in the db. Can you please show me what to do I think the scripts are kinda placed wrong, because the query is below the file upload script. I think it doesn't insert anything when there is nothing to upload/that option is disabled. The file upload script interferes I guess.
PHP:
if(isset($_FILES['filename'])){
$errors = array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// if no error...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
$servername = "localhost";
$username = "root";
$password = " ";
$dbname = "admin";
// create new record in the database
include ("dbinfo.php");
mysql_query("INSERT INTO payment_form (Tracking, date, mode, ContactNo, totalsent, datesent, filename) VALUES ('$transactionNo', NOW(), '$rad', '$contactNo', '$totalSent', '$dateSent', '$file_name')") ;
header('Location: paymentform_success.php');
}else{
print_r($errors);
}
}
Form:
<form name="form" method="POST" enctype="multipart/form-data">
<table width="416" height="245" border="1" align="center">
<tr>
<td colspan="2">Transaction No: <input type="text" name="transaction_no" id="transaction_no" /> </td>
</tr>
<tr>
<td colspan="2" align="center">Please select the mode of payment</td>
</tr>
<tr>
<td width="183" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="Smart Money">
Smart Money</td>
<td width="201" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="BPI"> BPI Bank Deposit</td>
</tr>
<tr>
<td align="center"><input name="contactno" type="text" disabled="disabled" id="contactno"></td>
<td align="center"><input name="filename" type="file" id="filename" disabled="disabled"/></td>
</tr>
<tr>
<td>Total amount sent:</td>
<td> <input type="text" name="totalsent" id="totalsent" /></td>
</tr>
<tr>
<td>Date sent:</td>
<td> <input type="text" name="datesent" id="datesent" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input name="submit" type="submit" id="submit" value="Submit" /></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form" />
</form>
JS for disable/enable
<script type="text/javascript">
function enableField(obj){
var form=obj.form;
var txtNames=['contactno','filename'], f;
var rads=document.getElementsByName(obj.name), r, i=0;
while(r=rads[i++]){
f=form[txtNames[i-1]];
if(r.checked){
f.removeAttribute('disabled');
f.focus();
}
else{
f.value='';
f.setAttribute('disabled','disabled')
}
}
}
</script>
Do the INSERT outside the if(isset($_FILES['filename'])) block.
if (isset($_POST['submit'])) {
$errors = array();
if (isset($_FILES['filename'])) {
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// if no error...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
}else{
print_r($errors);
}
} else {
$file_name = '';
}
if (empty($errors)) {
$servername = "localhost";
$username = "root";
$password = " ";
$dbname = "admin";
// create new record in the database
include ("dbinfo.php");
$transactionNo = $_POST['transaction_no'];
$rad = $_POST['rad'];
$contactNo = $_POST['contactno'];
$totalSent = $_POST['totalsent'];
$dateSent = $_POST['datesent'];
mysql_query("INSERT INTO payment_form (Tracking, date, mode, ContactNo, totalsent, datesent, filename) VALUES ('$transactionNo', NOW(), '$rad', '$contactNo', '$totalSent', '$dateSent', '$file_name')") ;
header('Location: paymentform_success.php');
}
}
I have created a form and everything is working fine so far. The only thing I have left is to reset the fields when the form is submitted. This seems like an easy task but after looking around and trying some things nothing seems to do the trick :( What I have now was taken from another post but my submit event was different from theirs which is why I think its not working. Any help is much appreciated.
php part
/////////////////////////////////upload image
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","500");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
$newname="storeImages/".$filename;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}
//If no errors registred, print the success message
if(isset($_POST['submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully!</h1>";
}
//direct to same page but refresh
//header('Location: storeListForm.php');
?>
The form
<body>
<script type="text/javascript">
function onFormSubmit ()
{
document.storeList.reset();
return true; // allow form submission to continue
}
</script>
<div id="signUp">
<?php
//if the validation falls back to php, then print the validation error
if (isset($error_message)) echo $error_message;
?>
<form method="post" action="" id="storeList" name="storeList" enctype="multipart/form- data">
<table>
<tr>
<td><label for="name">Name</label></td>
<td><input type="text" name="name" id="name" value="<?php if (isset($_POST['name'])) echo $_POST['name'];?>"/></td>
</tr>
<tr>
<td> <label for="storeLocation">Location</label></td>
<td><input type="text" name="storeLocation" id="storeLocation" value="<?php if (isset($_POST['storeLocation'])) echo $_POST['storeLocation'];?>"/></td>
</tr>
<tr>
<td><label for="featured_items">Featured Items</label></td>
<td><input type="text" name="featured_items" id="featured_items" value="<?php if (isset($_POST['featured_items'])) echo $_POST['featured_items'];?>"/></td>
</tr>
<tr>
<td><label for="keywords">Keywords</label></td>
<td><input type="text" name="keywords" id="keywords" value="<?php if (isset($_POST['featured_items'])) echo $_POST['keywords'];?>"/></td>
</tr>
<tr>
<td><label for="fileImage">Image</lable></td>
<td><input type="file" name="image"></td>
</tr>
<td>Description</td>
<td> <textarea for="description"></textarea type="text area" name="description" id="description" value="><?php if (isset($_POST['description'])) echo $_POST['description'];?>"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" id="submit" value="Add Store" onsubmit="this.submit(); this.reset(); return false;"></td>
</tr>
</table>
</form>
</div>
</body>
Perhaps you're looking for this?
onClick="this.form.reset()"
(Yours is only this.reset()).
I initialize the variables, use move_uploaded_file function and then I write a basic form user will use to upload their photo. I am trying to print at lease an error_msg or a sucess_msg showing wether they had sucess in loading the file or not. nothings is showwing up. Help!
$error_msg = "";
$success_msg = "";
$name2 = "";
if ($_POST['parse_var'] == "pic"){
if (!$_FILES['fileField']['tmp_name']) {
$error_msg = '<font color="#FF0000">ERROR: Please browse for an image before you press submit.</font>';
} else {
$maxfilesize = 51200; // 51200 bytes equals 50kb
if($_FILES['fileField']['size'] > $maxfilesize ) {
$error_msg = '<font color="#FF0000">ERROR: Your image was too large, please try again.</font>';
unlink($_FILES['fileField']['tmp_name']);
} else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['fileField']['name'] ) ) {
$error_msg = '<font color="#FF0000">ERROR: Your image was not one of the accepted formats, please try again.</font>';
unlink($_FILES['fileField']['tmp_name']);
} else {
$newname = $id'.jpg';
$place_file = move_uploaded_file( $_FILES['fileField']['tmp_name'], "images/$id/".$newname);
$success_msg = '<font color="#009900">Your image has been updated, it may take a few minutes for the changes to show... please be patient.</font>';
}
} // close else that checks file exists
}
<table width="709" align="center" cellpadding="5">
<form action="edit_profile.php" enctype="multipart/form-data" method="post" name="pic1_form" id="pic1_form">
<!-- <tr>
<td width="125" class="style7"><div align="center"><strong>Please Do First →</strong></div></td>
</tr>-->
<tr>
<td width="16%"><?php print "$user_pic"; ?></td>
<td width="74%">
<input name="fileField" type="file" class="formFields" id="fileField" size="42" />
50 kb max
</td>
<td width="10%">
<input name="parse_var" type="hidden" value="pic" />
<input type="submit" name="button" id="button" value="Submit" />
</td>
</tr>
</form></table>
You're going about checking if an upload was performed the wrong way:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... we're in a post situation, so check if a file was uploaded ...
if ($_FILES['fileField']['error'] !== UPLOAD_ERR_OK) {
$error_msg = "File upload failed with error code " . $_FILES['fileField']['error'];
} else {
... a file was successfully uploaded ...
... process it ...
if (!move_uploaded_file( ... )) {
$error_msg = "Failed to move file";
}
}
}
Checking for the presence of a form field is a poor way to check if a POST was performed. you may forget to put that field into the form, the name could change, etc... Checking the REQUEST_METHOD is guaranteed to work, as that is set regardless of what kind of request is being performed, and will always be the type of the request (get, post, head, etc...).
As well, don't use the user-provided file name to verify that they uploaded an image. That name can be trivially forged by simply renaming some OTHER kind of file to "whatever.jpg". Use server-side means to check if it's an image, such as FileInfo or getimagesize()
I think the error you're looking for is this one:
$newname = $id'.jpg';
You forgot a dot, and the whole script just crash:
$newname = $id.'.jpg';
I don't see anywhere in that code where you are echoing the error or success message.