I'm creating a simple mail system in PHP. And I'm stuck in this situation. I want to add a feature where my system can also do a file uploading and transferring. But I don't know how to add the file into mysql database. Any tips would be appreciated
compose.php
<form class="form-horizontal" method="post" action="" id="someForm" enctype="multipart/form-data">
<fieldset>
<!-- Form Name -->
<legend>Compose Mail</legend>
<!-- Text input-->
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="sendto">Send To: </label>
<div class="controls">
<input id="sendto" name="sendto" placeholder="Send To" class="input-xlarge cmps" type="text">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="title">Title: </label>
<div class="controls">
<input id="title" name="title" placeholder="Title/Subject" class="input-xlarge cmps" type="text">
</div>
</div>
<!-- Textarea -->
<div class="control-group">
<label class="control-label" for="body">Message: </label>
<div class="controls">
<textarea id="body" name="body" class="cmps"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="file">File: </label>
<div class="controls">
<input id="file" name="file" type="file">
</div>
</div>
<button type="submit" id="button" class="btn btn-success" onclick="askForSubmit()">Send!</button>
<button type="submit" id="button" class="btn-danger btn" onclick="askForSave()">Save to drafts</button>
</fieldset>
</form>
<script>
form=document.getElementById("someForm");
function askForSave() {
form.action="http://rsantiago.mbchosting.ph/email/save.php";
form.submit();
}
function askForSubmit() {
form.action="http://rsantiago.mbchosting.ph/email/send.php";
form.submit();
}
</script>
the upload_file.php
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 30000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 30000) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
I just wanna know how to store the file into the database so when the user sends it to another user, it can be downloaded
Related
When I try to submit my form, it can't be submitted and shows an "invalid file format" error, no matter if any data is input or not. The file format code was collected from StackOverflow.
if(isset($_POST['submit']))
{
$type=2;
$fname = #$_POST['f_name'];
$eml = #$_POST['email_id'];
$mo_num = #$_POST['mn'];
$message = #$_POST['message'];
$uploaded_file_a= #$_FILES['file_a']['name'];
$uploaded_file_b= #$_FILES['file']['name'];
// in a Array > all Supported Document Formats are Stored //
$allowedExts = array("pdf", "doc", "docx", "ppt", "pptx","jpeg","jpg","png","x-png");
// In a Temporary Array > The File Name + File Extension is Stored //
$temp = explode(".", $_FILES["file"]["name"]);
// Getting the Extension //
$extension = end($temp);
// Checking File // PDF | DOC | DOCX | XLS | XLSX | PPT | PPTX
if ((
(#$_FILES['file']['type'] == "image/jpeg")
|| (#$_FILES['file']['type'] == "image/jpg")
|| (#$_FILES['file']['type'] == "image/png")
|| (#$_FILES['file']['type'] == "image/x-png")
|| (#$_FILES["file"]["type"] == "application/pdf")
|| (#$_FILES["file"]["type"] == "application/msword")
|| (#$_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| (#$_FILES["file"]["type"] == "application/vnd.ms-excel")
|| (#$_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|| (#$_FILES["file"]["type"] == "application/application/vnd.ms-powerpoint")
|| (#$_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.presentationml.presentation"))
&&
(#$_FILES['file']['error'] == 0)
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts))
{
$fileName_a = date("YmdHis") . "_" . $_FILES['file_a']['name'];
$fileName = date("YmdHis") . "_" . $_FILES['file']['name'];
$valToBind = array(
':F_NM' => $fname,
':EM' => $eml,
':MOB' => $mo_num,
':TY' => $type,
':MS' => $message,
':PILEA'=> #$fileName_a,
':PILE'=> #$fileName
);
$query = $conn1->prepare("
INSERT INTO `testimonials` (`user_name`,`email`,`phone`,`testimonial_type`,`testimonial_message`,`photo_file`,`image_file`) VALUES
(:F_NM,:EM,:MOB,:TY,:MS,:PILEA,:PILE);
");
$query->execute($valToBind);
$rowNumber = $query->rowCount();
$lastInsertId = $conn1->lastInsertId();
if($lastInsertId > 0)
{
{ move_uploaded_file(
$_FILES['file_a']['tmp_name'], "admin/upload/testimonials/". $fileName_a
);}
{ move_uploaded_file(
$_FILES['file']['tmp_name'], "admin/upload/testimonials/". $fileName
);}
echo '<div class="alert alert-success " >
Your Testimonials has been sent to us.
</div>';
}
}
else
{
echo'<div class="alert alert-success " > Invalid File Format </div>';
}
}
?>
<form class="row contact_form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<div class="col-md-12 col-sm-6">
<input type="text" class="form-control" name="f_name" placeholder="Full Name">
</div>
<div class="col-md-12 col-sm-6">
<input type="email" class="form-control" name="email_id" placeholder="Email">
</div>
<div class="col-md-12 col-sm-6">
<input type="text" class="form-control" name="mn" placeholder="Mobile Number">
</div>
<div class="col-md-12 col-sm-6">
<label> Your Photo</label><br>
<input type="file" name="file_a" class="form-control" >
</div>
<div class="col-md-12 col-sm-6">
<label> Testimonial in msword, pdf or Image (if scanned)</label><br>
<input type="file" name="file" class="form-control" >
</div>
<div class="col-md-12 col-sm-6">
<textarea name="message" class="form-control" placeholder="Testimonial Message (if written)"></textarea>
</div>
<div class="col-md-12 col-sm-6">
<input type="submit" name="submit" value="Submit Resume" class="btn btn-primary btn-block" >
</div>
</form>
i have modified you code to handle if no file is submitted.
if(isset($_POST['submit']))
{
$type=2;
$fname = #$_POST['f_name'];
$eml = #$_POST['email_id'];
$mo_num = #$_POST['mn'];
$message = #$_POST['message'];
$uploaded_file_a= #$_FILES['file_a']['name'];
$uploaded_file_b= #$_FILES['file']['name'];
// in a Array > all Supported Document Formats are Stored //
$allowedExts = array("pdf", "doc", "docx", "ppt", "pptx","jpeg","jpg","png","x-png");
// In a Temporary Array > The File Name + File Extension is Stored //
$temp = explode(".", $_FILES["file"]["name"]);
// Getting the Extension //
$extension = end($temp);
// Checking File // PDF | DOC | DOCX | XLS | XLSX | PPT | PPTX
if ((
(#$_FILES['file']['type'] == "image/jpeg")
|| (#$_FILES['file']['type'] == "image/jpg")
|| (#$_FILES['file']['type'] == "image/png")
|| (#$_FILES['file']['type'] == "image/x-png")
|| (#$_FILES["file"]["type"] == "application/pdf")
|| (#$_FILES["file"]["type"] == "application/msword")
|| (#$_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| (#$_FILES["file"]["type"] == "application/vnd.ms-excel")
|| (#$_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|| (#$_FILES["file"]["type"] == "application/application/vnd.ms-powerpoint")
|| (#$_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.presentationml.presentation"))
&&
(#$_FILES['file']['error'] == 0)
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts) && $_FILES['file']['tmp_name'] != '')
{
$fileName_a = date("YmdHis") . "_" . $_FILES['file_a']['name'];
$fileName = date("YmdHis") . "_" . $_FILES['file']['name'];
$valToBind = array(
':F_NM' => $fname,
':EM' => $eml,
':MOB' => $mo_num,
':TY' => $type,
':MS' => $message,
':PILEA'=> #$fileName_a,
':PILE'=> #$fileName
);
$query = $conn1->prepare("
INSERT INTO `testimonials` (`user_name`,`email`,`phone`,`testimonial_type`,`testimonial_message`,`photo_file`,`image_file`) VALUES
(:F_NM,:EM,:MOB,:TY,:MS,:PILEA,:PILE);
");
$query->execute($valToBind);
$rowNumber = $query->rowCount();
$lastInsertId = $conn1->lastInsertId();
if($lastInsertId > 0)
{
{ move_uploaded_file(
$_FILES['file_a']['tmp_name'], "admin/upload/testimonials/". $fileName_a
);}
{ move_uploaded_file(
$_FILES['file']['tmp_name'], "admin/upload/testimonials/". $fileName
);}
echo '<div class="alert alert-success " >
Your Testimonials has been sent to us.
</div>';
}
}
else
{
echo'<div class="alert alert-success " > Invalid File Format </div>';
}
}
?>
<form class="row contact_form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<div class="col-md-12 col-sm-6">
<input type="text" class="form-control" name="f_name" placeholder="Full Name">
</div>
<div class="col-md-12 col-sm-6">
<input type="email" class="form-control" name="email_id" placeholder="Email">
</div>
<div class="col-md-12 col-sm-6">
<input type="text" class="form-control" name="mn" placeholder="Mobile Number">
</div>
<div class="col-md-12 col-sm-6">
<label> Your Photo</label><br>
<input type="file" name="file_a" class="form-control" >
</div>
<div class="col-md-12 col-sm-6">
<label> Testimonial in msword, pdf or Image (if scanned)</label><br>
<input type="file" name="file" class="form-control" >
</div>
<div class="col-md-12 col-sm-6">
<textarea name="message" class="form-control" placeholder="Testimonial Message (if written)"></textarea>
</div>
<div class="col-md-12 col-sm-6">
<input type="submit" name="submit" value="Submit Resume" class="btn btn-primary btn-block" >
</div>
</form>
Thanks
Amit
I'm developing a back end for my blog but the code to upload images isn't working as expected.
When i submit it uploads the image and moves it to the designated folder but in the database there is no record inserted. Here is the php for uploading
<?php
session_start();
include('Connections/conn.php');
if (!isset($_SESSION['userid'])) {
header("location:index.php");
}
$suc=" ";
$writer=$_SESSION['my_username'];
if(isset($_POST['submit']))
{
error_reporting(E_ALL ^ E_NOTICE);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$title=$_POST['title'];
$intro=$_POST['intro'];
$body=$_POST['body'];
$keywords=$_POST['keywords'];
$date=$_POST['date'];
$fileToUpload=$_POST['fileToUpload'];
$sql2="Insert into articles(title,intro,body,keywords,date,writer,fileToUpload)VALUES('$title','$intro','$body','$keywords','$date','$writer','$target_file')"or die(mysqli_error());
$result2 = mysqli_query($db_conn, $sql2);
$suc=" <div class='alert alert-success'>
<span><b>Success</b>: New article posted successfully!</span>
</div>";
}
?>
And here is the form
<form method="POST" action"<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<div class="form-group">
<label>Title</label>
<input type="text" id="title" name="title" class="form-control" required/>
</div>
<div class="form-group">
<label>Intro</label>
<textarea id="intro" name="intro" class="form-control" required></textarea>
</div>
<div class="form-group">
<label>Enter keyword tags</label><br/>
<div>
<input type="text" id="keywords" name="keywords" class="tagsinput" required/>
</div>
</div>
<div class="form-group">
<label>Date</label><br/>
<div>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-calendar"></span></span>
<input type="text" id="date" name="date" class="form-control datepicker" placeholder="Select Date" required>
</div>
<span class="help-block">Click on input field to select date</span>
</div>
<div class="form-group">
<div>
<label>Picture</label>
<input type="file" multiple class="file" data-preview-file-type="any" name="fileToUpload" id="fileToUpload"/>
</div>
</div>
<div>
<div class="block">
<p>Type the content below, note that you can extend the height of the editor by dragging the bottom border.</p>
<textarea class="summernote" id="body" name="body" placeholder="Enter the body text" required>
</textarea>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-danger btn-block" type="reset">Reset</button>
</div>
<div class="col-md-6">
<button class="btn btn-info btn-block" type="submit" name="submit" value="submit">Publish Article</button>
</div>
</div>
</form>
Replace
$fileToUpload=$_POST['fileToUpload'];
with
$fileToUpload=$_FILES['fileToUpload']['name'];
Try this
$sql2="INSERT INTO articles(title,intro,body,keywords,date,writer,fileToUpload)VALUES('$title','$intro','$body','$keywords','$date','$writer','$target_file')");
if (!mysqli_query($db_conn, sql2))
{
echo("Error description: " . mysqli_error($db_conn));
}
else{
echo "Inserted";
}
and my opinion is add the insert code after move_uploaded_file get success
i am inserting data into mysql using php it's work partialy it's inserting everything but not single quotes(') ex. principle's message. and when i insert it like principle"s message. it's inserting in database but it's only displaying principle in text box after inserting. and my file is save.php is here.
<?php session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['user'])) {
if($_GET['catId'] == '' || $_GET['catId'] == null)
header('location:../user/logout.php');
$inc = -1;
if($_POST['title'] == '' || $_POST['title'] == null) {
$inc++;$_SESSION['error'][$inc] = "TITLE IS REQUIRED";
}
$selectImg=mysql_query("SELECT pri_img FROM aboutus_tbl WHERE id=4");
if ($_GET['catId']==4) {
if($_FILES["file"]["name"]) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 5242880)
&& in_array($extension, $allowedExts))
$imageNewName = md5(date("l, F d, Y h:i" ,time()) . (microtime())) . "." . $extension;
else {
$inc++;$_SESSION['error'][$inc] = "IVALID IMAGE";
}
}
else {
$inc++;$_SESSION['error'][$inc] = "IMAGE IS REQUIRED";
}
}
function inputValues() {
$_SESSION['values']['title'] = $_POST['title'];
$_SESSION['values']['sub_title1'] = $_POST['sub_title1'];
$_SESSION['values']['desc1'] = $_POST['desc1'];
$_SESSION['values']['sub_title2'] = $_POST['sub_title2'];
$_SESSION['values']['desc2'] = $_POST['desc2'];
$_SESSION['values']['sub_title3'] = $_POST['sub_title3'];
$_SESSION['values']['desc3'] = $_POST['desc3'];
header("location:../../views/aboutus_content/list.php?catId=".$_GET['catId']);
}
if($inc > -1)
inputValues();
else {
require_once('../../includes/connect.php');
if($_GET['catId']==4 && isset($_FILES["file"]["name"])) {
$update="UPDATE aboutus_tbl SET title='".$_POST['title']."',sub_title1='".$_POST['sub_title1']."',desc1='".$_POST['desc1']."',sub_title2='".$_POST['sub_title2']."',desc2='".$_POST['desc2']."',sub_title3='".$_POST['sub_title3']."',desc3='".$_POST['desc3']."',pri_img='".$imageNewName."' WHERE id='".$_GET['catId']."'";
}
else{
$update="UPDATE aboutus_tbl SET title='".$_POST['title']."',sub_title1='".$_POST['sub_title1']."',desc1='".$_POST['desc1']."',sub_title2='".$_POST['sub_title2']."',desc2='".$_POST['desc2']."',sub_title3='".$_POST['sub_title3']."',desc3='".$_POST['desc3']."' WHERE id='".$_GET['catId']."'";
}
if(mysql_query($update)) {
if($_GET['catId']==4 && isset($_FILES["file"]["name"])) {
move_uploaded_file($_FILES["file"]["tmp_name"],"../../public/img/principal/".$imageNewName);
unlink("../../public/img/principal/".mysql_result($selectImg, 0, "pri_img"));
}
$_SESSION['message'] = $_POST['title']." SUCESSFULLY UPDATED";
header('location:../../views/aboutus_content/list.php?catId='.$_GET['catId']);
} else {
$_SESSION['error'] = "ERROR : '".mysql_error()."' CODE : ".mysql_errno();
inputValues();
}
}
} else
header('location:../user/logout.php')
?>
and designing file is here list.php
<?php
ob_start();
include '../../includes/header.php';
if(!isset($_GET['catId']) || $_GET['catId']=='')
header('location:../error');
$contactResult = mysql_query("SELECT * FROM aboutus_tbl WHERE id='".$_GET['catId']."'");
if(mysql_num_rows($contactResult) != 1)
header('location:../error');
else {
?>
<div class="mainbar">
<div class="page-head">
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<h2><i class="fa fa-desktop"></i> <?php echo mysql_result($contactResult, 0, "title");?> Content</h2>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="container">
<?php
if(isset($_SESSION['error'])) {
echo"<div class='alert alert-danger'>";
for($i=0;$i<sizeof($_SESSION['error']);$i++)
echo "<p><b>".$_SESSION['error'][$i]."</b></p>";
echo"</div>";
unset($_SESSION['error']);
}
if(isset($_SESSION['message'])) {
echo"<div class='alert alert-success'><p><b>".$_SESSION['message']."</b></p></div>";
unset($_SESSION['message']);
}
?>
<div class="hide alert alert-danger" id="errorContainer"></div>
<div class="row">
<div class="col-lg-12">
<form action="../../controllers/aboutus_content/save.php?catId=<?php echo $_GET['catId'];?>" method="post" class="contactForms" role="form" enctype="multipart/form-data">
<div class="col-lg-6">
<div class="form-group">
<label for="title"><span class="text-danger">* </span>Title</label>
<input name="title" id="title" data-validation-allowing="'" class="form-control" placeholder="Enter Title" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['title']; echo mysql_result($contactResult, 0, "title");?>" />
</div>
<div class="form-group">
<label for="sub_title1"><span class="text-danger">* </span>Sub Title 1</label>
<input name="sub_title1" id="sub_title1" data-validation-allowing="'" class="form-control" placeholder="Enter Sub Title 1" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['sub_title1']; else echo mysql_result($contactResult, 0, "sub_title1");?>" />
</div>
<div class="form-group">
<label for="desc1"><span class="text-danger">* </span>Description 1</label>
<textarea name="desc1" id="desc1" data-validation-allowing="'" class="form-control" placeholder="Enter Description 1"><?php if(isset($_SESSION['values'])) echo $_SESSION['values']['desc1']; else echo mysql_result($contactResult, 0, "desc1");?></textarea>
</div>
<div class="form-group">
<label for="sub_title2"><span class="text-danger">* </span>Sub Title 2</label>
<input name="sub_title2" id="sub_title2" data-validation-allowing="'" class="form-control" placeholder="Enter Sub Title 2" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['sub_title2']; else echo mysql_result($contactResult, 0, "sub_title2");?>" />
</div>
<div class="form-group">
<label for="desc2"><span class="text-danger">* </span>Description 2</label>
<textarea name="desc2" id="desc2" data-validation-allowing="'" class="form-control" placeholder="Enter Description 2"><?php if(isset($_SESSION['values'])) echo $_SESSION['values']['desc2']; else echo mysql_result($contactResult, 0, "desc2");?></textarea>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="sub_title3"><span class="text-danger">* </span>Sub Title 3</label>
<input name="sub_title3" id="sub_title3" data-validation-allowing="'" class="form-control" placeholder="Enter Sub Title 3" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['sub_title3']; else echo mysql_result($contactResult, 0, "sub_title3");?>" />
</div>
<div class="form-group">
<label for="desc3"><span class="text-danger">* </span>Description 3</label>
<textarea name="desc3" id="desc3" data-validation-allowing="'" class="form-control" placeholder="Enter Description 3"><?php if(isset($_SESSION['values'])) echo $_SESSION['values']['desc3']; else echo mysql_result($contactResult, 0, "desc3");?></textarea>
</div>
<div class="form-group">
<label for="pri_img"><span class="text-danger">* </span>Principle Image(Only For Principal's Message)</label>
<input type="file" name="file" id="file" class="form-control">
</div>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-info" value="Save" />
Reset
</div>
</form>
</div>
</div>
</div>
</div>
<?php
}
?>
<script type="text/javascript">
window.onload = function() {
$(document).ready(function() {
$('.aboutus_content').addClass('current');
$('.aboutus_content').addClass('open');
$(".courImgItm<?php echo $_GET['catId']?>").addClass('active');
});
}
</script>
<?php
include '../../includes/footer.php';
if(isset($_SESSION['values']))
unset($_SESSION['values']);
ob_flush();
?>
please help me.
Run your string through this first:
mysql_real_escape_string($string);
It'll fix it for ya
try using this way
in your sql query---
$m1=$_REQUEST['message'];
$msg='".str_replace("\"",""",str_replace("'","''",$m1))."';
hope this will help
I have a form through which a user can upload images to a server folder, and the path gets saved in the database.
Currently the code that I have works fine when the user has to input only one image; however, I want to do something like the following with the form, so that user can upload more than one image:
<form class="form-horizontal" role="form" action="insertimage.php?id=<?php echo $_GET['id']; ?>" enctype="multipart/form-data" method="post">
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 1</label>
<div class="col-lg-6">
<input type="file" name="file" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 2</label>
<div class="col-lg-6">
<input type="file" name="file1" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 3</label>
<div class="col-lg-6">
<input type="file" name="file2" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save Changes" type="submit" name="submit">
</div>
</div>
</div>
</form>
The PHP code at back end for uploading one image is insertimage.php:
<?php
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$upload_exts = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($upload_exts, $file_exts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
// Enter your path to upload file here
if (file_exists("uploads/" .$_FILES["file"]["name"]))
{
echo "<div class='error'>"."(".$_FILES["file"]["name"].")"." already exists. "."</div>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/" . $_FILES["file"]["name"]);
echo "<div class='sucess'>"."Stored in: " . "uploads/" . $_FILES["file"]["name"]."</div>";
` }
}
}
else
{
echo "<div class='error'>Invalid file</div>";
}
?>
Can anyone please tell me how I can support uploading 3 images with help of the above code?
With this you are able to select multiple image with use of ctrl
<input type="file" name="file[]" id="fileToUpload" multiple />
On Server side use loop
for ($1=0;i<count($dataFile);$i++){
//your upload code ;
$_FILES["file"]["name"][$i];//go for each and every i position for all
}
You can use file array for multiple images at a time with multiple attribute in the html line like:
<input type="file" name="file[]" id="fileToUpload" multiple />
This will give you the array of files which you can debug by
print_r($_FILES);
And you also have to change the code that saves the data as there is error that it can only have one file at a time try for loop my debugging with
$_FILES
I am not sure what is wrong with this code, so I was hoping for some helpful input.
The Problem
It will not get the name of the file that I have uploaded nor is it actually uploading it into the defined directory.
The PHP Code
<? include("header.php");
include("sidebar.php");
?>
<h2>Add Raffle</h2>
<?
$name = asql($_POST['name']);
$type = asql($_POST['prize']);
$min_points = asql($_POST['minp']);
$min_cash = asql($_POST['maxu']);
$cons = strtotime($_POST['cons']);
$cone = strtotime($_POST['cone']);
if($_POST['subm'])
{
if ($name == NULL OR $type == NULL OR $min_points == NULL OR $min_cash == NULL) {
print"Please Fill Out All Of The Required Fields<br /><a href='rafadd.php'><img src='img/green_arrow_left.png' alt='Go Back' /></a>"; include"footer.php";
exit();
}
if (!in_array($file['type'], array("image/gif", "image/jpeg", "image/png"))
|| $file['size'] > 20000)
{
if ($_FILES["file"]["error"] > 0)
{
echo "There was an error";
}
else
{
echo "";
$filename = $_FILES["file"]["name"];
if (file_exists("../images/rewards/" . $_FILES["file"]["name"]))
{
unlink("../images/raffles/" . $_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"],
"../images/raffles/" . $_FILES["file"]["name"]);
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../images/raffles/" . $_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
$updatecontests = mysql_query("INSERT INTO raffles (`id`, `raffle_name`, `raffle_prize`, `buy_in`, `max_entry`, `prize_image`, `start`, `end`) VALUES ('','$name','$type','$min_points','$min_cash','images/raffles/".$filename."','$cons','$cone')") or die(mysql_error());
if($updatecontests){
$create = mysql_query("CREATE TABLE IF NOT EXISTS `".$name."` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` text NOT NULL,
`entries` int(11) NOT NULL,
PRIMARY KEY (`username`(30)),
KEY `id` (`id`)
)");
}
print "You Have Successfully Added this Raffle<br /><br />
<a href='rafadd.php'><img src='img/green_arrow_left.png' alt='Go Back' /></a>";
}
else
{
print"<div class='form'>
<form action='' method='post'><input type=hidden name=subm value=1>";
?>
<div class="element">
<label for="name">Raffle Name: <span class="red">(required)</span></label>
<input id="name" name="name" size="50" />
</div>
<div class="element">
<label for="prize">Raffle Prize: <span class="red">(required)</span></label>
<input id="prize" name="prize" size="50" />
</div>
<div class='element'>
<label for='file'>Prize Image:</label>
<input type='file' name='file' id='file' />
</div>
<div class="element">
<label for="cons">Start Date: <span class="red">(required)</span></label>
<input id="cons" name="cons" size="50" /><img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date">
</div>
<div class="element">
<label for="cone">End Date: <span class="red">(required)</span></label>
<input id="cone" name="cone" size="50" /><img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date">
</div>
<div class="element">
<label for="minp">Cost Per Ticket: <span class="red">(required)</span></label>
<input id="minp" name="minp" size="50" />
</div>
<div class="element">
<label for="maxu">Maximum Entries per User: <span class="red">(required 0 for unlimited)</span></label>
<input id="maxu" name="maxu" size="50" />
</div>
<?php
print" <dl class='submit'>
<input type='submit' name='subm' id='subm' value='Submit' />
</dl>
</form>
</div> ";
}
?>
</div><!-- end of right content-->
</div> <!--end of center content -->
<div class="clear"></div>
</div> <!--end of main content-->
<div class="footer">
<div class="left_footer">IN ADMIN PANEL | Powered by INDEZINER</div>
<div class="right_footer"><img src="images/indeziner_logo.gif" alt="" title="" border="0" /></div>
</div>
</div>
</body>
</html>
I have used the file upload snippet in another script and it uploads perfectly so I am not sure why it is not working here.
in the form tag add enctype="multipart/form-data"
<form action='' method='post'enctype="multipart/form-data">
<form action='' method='post'>
is wrong, needs to be:
<form action='' method='post' enctype='multipart/form-data'>
Also, use <?php instead of <?
PS I miss the point where $file is set.
It doesn't look like file is being instantiated anywhere. Did you mean:
if (!in_array($_FILES['file']['type'], array("image/gif", "image/jpeg", "image/png"))
|| $_FILES['file']['size'] > 20000)