PHP File upload script getting in the way - php

I have this form
If the first radio button is clicked, the textfield below it is enabled and if the 2nd radio button is clicked, the file upload is enabled and the former is disabled,vice versa. It works fine if the file upload option is chosen but if the 1st radio button is chosen and the file upload is disabled, it doesn't insert data in the database. :/ What should be done to successfully send the form details even if the file upload is disabled/empty?
CODE:
<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" checked="checked">
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 type="text" name="contactno" 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>
PHP
<?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';
}
// pag walang 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 (date, Tracking, mode, ContactNo, totalsent, datesent, filename) VALUES (NOW(), '$transactionNo', '$rad', '$contactNo', '$totalSent', '$dateSent', '$file_name')") ;
header('Location: paymentform_success.php');
}else{
print_r($errors);
}
}
?>
Javascript for enable/disable
<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>

You should first check which radio is checked and then decide what to do. It's not working because the whole script is under the if(isset($_FILES['filename'])). If the file upload is disabled then $_FILES will not be set and nothing will be executed.

Related

Adding the row ID to the filename of the uploaded file

I want to add the ID number of the row to the uploaded file file name.
e.g. if the file name is stack.pdf before uploading, after uploading it should change to stack-ID#.pdf.
This is the PHP Codes that is use to upload
$sp=mysqli_connect("localhost","root","","ara");
if($sp->connect_errno){
echo "Error <br/>".$sp->error;
}
$path="pdf/";
if(isset($_POST['upload']))
{
$path=$path.$_FILES['file_upload']['name'];
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>";
echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>';
$img=$_FILES['file_upload']['name'];
$query="insert into library (path,CreatedTime) values('$img',now())";
if($sp->query($query)){
echo "<br/>Inserted to DB also";
}else{
echo "Error <br/>".$sp->error;
}
}
else
{
echo "There is an error,please retry or ckeck path";
}
}
And this is the form
<form action="accept-file.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Select File</td>
<td width="260"><label>
<input type="file" name="file_upload">
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="upload" value="Upload File">
</label></td>
<td> </td>
</tr>
</table>
</form>
I will really appreciate your help. Thanks.
Try this:
$uploadFileName = $_FILES['file_upload']['name'];
//get extention of upload file
$attachment_ext = explode('.', $uploadFileName);
$ext_pt = $attachment_ext[1];
//Give a new name for the file
$newName = '123'.$uploadFileName.".".$ext_pt;
$path = "YOURPATHHERE/";
$save_attchment = $path.$newName ; //setting the path
move_uploaded_file($_FILES['file_upload']['tmp_name'], $save_attchment);

How To Upload Multiple Images With Links To Them In mysql

Currently I have a code which is working perfectly for one image upload. But i want to upload multiple images at a time with same Image Title, Image Description for image group being uploaded as these images will be used in photo slideshow(See Images below please)
My Current Code is as follows -
PHP Code -
$bsq->connect_db();
$fileName = $_FILES["image"]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image"]["tmp_name"];
// Path and file name
$pathAndName = "uploads_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$all_columns[]="image_subject";
$all_columns[]="image_name";
$all_columns[]="clinic";
$all_columns[]="image_link";
//Get All values to insert in to table
$all_values[]=addslashes($_POST["image_subject"]);
$all_values[]=addslashes($_POST["image_name"]);
$all_values[]=addslashes($_POST["clinic"]);
$all_values[]=addslashes($pathAndName );
//=====================
$qry=$bsq->webdreaminsert("sa_galleryuploads_by_admin",$all_columns,$all_values,'');
echo mysql_error();
header("location:upload_file_for_downloading_list.php");
///////////////////////////////////////////////////
}
And HTML Form For upload Image Is As follows -
<form action="" method="post" enctype="multipart/form-data" name="addtwebinar1" id="addtwebinar1" onsubmit="javascript:return validateimage1();" >
<input type="hidden" value="add" name="action" />
<table width="90%" align="center" border="0" cellpadding="0" cellspacing="0" class="ListTable1">
<tr class="HeadBr">
<td colspan="4"><div align="center"><strong>Add Images For Photo Gallery</strong></div></td>
</tr>
<tr >
<td>Image Title*</td>
<td><input name="image_name" id="image_name" type="text" size="40" value="" /></td>
</tr>
<tr>
<td>Image Description In Short*</td>
<td><input name="image_subject" id="image_subject" type="text" size="40" value="" /></td>
</tr>
<tr >
<td>Clinic Name*</td>
<td>
<select name="clinic" id="message" >
<option value="">Select Clinic</option>
<option value="arogya">1. Arogyawardhini Ayurved Clinic</option>
<option value="smruti">2. Smruti Ayurved Clinic</option>
<option value="tarpan">3. Tarpan Ayurved Clinic</option>
<option value="vishwa">4. Vishwawardhini Ayurved Clinic</option>
</select>
</td>
</tr>
<tr >
<td>Your Image For Upload* </td>
<td><label for="image">File To Upload: </label><br>
<input type="file" size="40" name="image" id="image" /><br />
</td>
</tr>
<tr>
<td></td>
<td><button >Upload</button></td>
</tr>
</table>
</form>
Current Look of My Active Image upload Form -
And I Want Like Below (Created Graphically)
You can use a for loop.
For the form, do something like this:
for($i = 1; $i <= 4; $i++) {
echo "<input type=\"file\" size=\"40\" name=\"image{$i}\" id=\"image{$i}\" /><br />";
}
And for the processing, just put all of that in a for loop as well.
for($i = 1; $i <= 4; $i++) {
$fileName = $_FILES["image".$i]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image".$i]["tmp_name"];
// Path and file name
$pathAndName = "uploads_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$image_name = mysql_real_escape_string($_POST['image_name']);
$image_subject = mysql_real_escape_string($_POST['image_subject']);
$clinic = mysql_real_escape_string($_POST['clinic']);
$image_link = "http://".$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), "\\/")."/".$pathAndName;
//=====================
mysql_query("INSERT INTO `sa_galleryuploads_by_admin` VALUES ('', '{$image_name}', '{$image_subject}', '{$clinic}', '{$image_link}' )") or die(mysql_error());
if(!mysql_error()) {
echo "success";
}
}
You can edit the number that the loop goes up to, to match the number of fields/images you want to show. Good luck!
edit: You also need to sanitize validate your inputs. At the very least, use mysql_real_escape_string().
Also, mysql_* functions are deprecated. You should switch to using either mysqli or pdo. I'd suggest mysqli to start off, because it also offers a procedural approach, whereas pdo is completely object oriented.

Image upload via php and adding details to mysql

So I have searched everywhere and i cannot figure this out at all. I am trying to upload POST info and the image name to SQL and also upload the image to the uploads directory. SQL will update all info except the image line nor will it actually upload the image. Ill post code below
EDIT: I got it to add the file name into the SQL table but still it wont upload file.
FORM info
<table width="100%" border="0">
<tr><form action="specialadd.php" method="post">
<td>Name of Special</td>
<td>Special Price</td>
</tr>
<tr>
<td valign="top">
<input type="text" name="name"></td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td>Description #1</td>
<td>Description #2</td>
</tr>
<tr>
<td><textarea name="desc1" rows="6" cols="50"></textarea></td>
<td><textarea name="desc2" rows="6" cols="50"></textarea></td>
</tr>
<tr>
<td>Upload Photo</td>
<td> </td>
</tr>
<tr>
<td><input type="file" name="image"></td>
<td><input type="submit" value="Save Your Special"></form></td>
</tr>
</table>
PHP Info
<?php
//This is the directory where images will be saved
$target = "/public_html/uploads";
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$desc1=$_POST['desc1'];
$desc2=$_POST['desc2'];
$price=$_POST['price'];
$image=($_FILES['image']['name']);
// Connects to your Database
include "process/connect.php";
//Writes the information to the database
mysql_query("UPDATE specials
SET name='$name', desc1='$desc1', desc2='$desc2', price='$price', image='$image'") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
I figured it out also thanks on the enctype i completely forgot about that. It works perfectly.
You need to add
enctype="multipart/form-data"
in the form so your form should be
<form action="specialadd.php" method="post" enctype="multipart/form-data">

UPDATE mysql database and the id and the image in relation to the id?

I have this php file which will update a table in mysql database.
it works to a certain. it will update the name of the product (product_name) and it will update the (date_added) too. but it is not updating the id and as a result the image that was uploaded with that id is not showing!!
here is the code:
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {
$product_name = mysql_real_escape_string($_POST['product_name']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT id FROM tomProduct WHERE product_name='$product_name' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
$sql = mysql_query("UPDATE tomProduct SET product_name='$product_name', date_added=now()") or die (mysql_error());
$pid = mysql_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../tom/$newname");
header("location: verify_members.php");
exit();
}
?>
and here is the form:
<form action="verify_members.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Product Name</td>
<td width="80%"><label>
<input name="product_name" type="text" id="product_name" size="64" />
</label></td>
</tr>
<tr>
<td align="right">Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Item Now" />
</label></td>
</tr>
</table>
</form>
anyone knows why this is happening?
Thanks
mysql_insert_id() returns the last INSERT record, not UPDATE.

move_uploaded_file is giving a error

this is my form
<form action="test.php" method="post" name="myform">
<table width="500" border="0">
<tr>
<td width="369" colspan="3">Admin's Area </td>
<td width="121"><?php echo $_SESSION['name'];?></td>
</tr>
<tr>
<td colspan="3">sponseres list </td>
<td>+Add new Sponser</td>
</tr>
<tr>
<td colspan="3"><?php echo $sponsere_list; ?></td>
<td> </td>
</tr>
<tr>
<td align="center" colspan="4"> <a name="sponserForm" id="sponserForm"></a> Add New Sponser Form</td>
</tr>
<tr>
<td align="left">Sponser name</td>
<td align="left"><input type="text" name="spname" id="spname" tabindex="1" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="left">Image</td>
<td align="left"><input type="file" name="fileToUpload" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="left">Add this</td>
<td align="left"><input type="submit" name="sumit" id="sumit" value="Submit" tabindex="3" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="center" colspan="4"> </td>
</tr>
</table>
</form>
and this is the php code to retrive it
<?php
if(isset($_POST['spname'])){
$spname=mysql_real_escape_string($_POST['spname']);
$user_query = "INSERT INTO `sponsers` (`spname`)
VALUES ('{$spname}')
";
$sql=mysql_query($user_query)or die (mysql_error());
$spic= mysql_insert_id();
$newname="$spic.jpg";
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],"../sponsers/$newname")or die (mysql_error());
}
?>
when i try to upload a image it gives me this warning message
Notice: Undefined index: fileToUpload in J:\xampp\htdocs\srimag\admin\test.php on line 3
so i tried to echo the fileToUpload value by using $_POST['fileToUpload'] it show the values without errors so can't figure out the error.
so please help me on this :-(
Thanks.
Your main problem is you are missing the appropriate enctype attribute on your form
<form ... enctype="multipart/form-data">
Make sure you read this section of the manual carefully - http://php.net/manual/en/features.file-upload.php
Your issue is mentioned on the first page
Note:
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
You need enctype="multipart/form-data" in your form to upload images, also it would be a good idea to check if user even uploads an image and specificity naming a file .jpg will not work, images will be treated as corrupt when outputting if ther not jpegs, not to mention people uploading php files.
You also need to make some other checks on validity, upload security is not something that should be overlooked, else you have one of thos awful phone home / botnet malware scripts injecting code into all your scripts:
<?php
if(isset($_POST['spname'])){
$spname=mysql_real_escape_string($_POST['spname']);
$user_query = "INSERT INTO `sponsers` (`spname`)
VALUES ('{$spname}')";
$sql=mysql_query($user_query)or die (mysql_error());
$spic= mysql_insert_id();
if(isset($_FILES["fileToUpload"]["tmp_name"]) && $_FILES["fileToUpload"]["error"] ==0){
$name = basename($_FILES["fileToUpload"]['name']);
$ext = end(explode('.', $name));
$newname = $spic.".".$ext;
$info = getimagesize($_FILES["fileToUpload"]['tmp_name']);
$allowed = array('image/png','image/jpg','image/gif');
if($info[0]>0 && $info[1] > 0 && in_array($info['mime'],$allowed)){
move_uploaded_file($_FILES["fileToUpload"]['tmp_name'], "../sponsers/$newname");
//done upload
}else{
//Not allowed, perhap notify user
}
}
}
?>
include this in form tag
enctype="multipart/form-data"
You should add this in your form
<form action="test.php" method="post" name="myform" enctype="multipart/form-data">

Categories