"Invalid File Format" error when trying to submit form - php

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

Related

single quotes and double quotes not inserting in datadase using php

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

Error in Uploading File

I have problem with the Uploading in my Project
This is my Code Of 'User' class
<?php
class User{
public function uploadAvatar() {
$alowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["avatar"]["name"]);
$extention = end($temp);
if(($_FILES["avatar"]["type"] == "image/gif")
|| ($_FILES["avatar"]["type"] == "image/jpeg")
|| ($_FILES["avatar"]["type"] == "image/jpg")
|| ($_FILES["avatar"]["type"] == "image/pjpeg")
|| ($_FILES["avatar"]["type"] == "image/x-png")
|| ($_FILES["avatar"]["type"] == "image/png")
&& ($_FILES["avatar"]["size"] > 50000)
&& in_array($extention, $alowedExts)) {
if($_FILES["avatar"]["error"] > 0) {
redirect('register.php', $_FILES['avatar']['error'],'error');
} else {
if (file_exists("/images/avatars/" . $_FILES["avatar"]["name"])) {
redirect('register.php', 'File Already Exists', 'error');
} else{
move_uploaded_file($_FILES["avatar"]["tmp_name"],
"images/avatars/" . $_FILES["avatar"]["name"]);
return true;
}
}
} else {
redirect('register.php','invalid file type','error');
}
}
}?>
and here is my Register
<?php
//create User Object
$user = new User;
if(isset($_POST['register'])){
//create Data Array
$data = Array();
$data['name'] = $_POST['name'];
$data['email'] = $_POST['email'];
$data['username'] = $_POST['username'];
$data['password'] = md5($_POST['password']);
$data['password2'] = md5($_POST['password2']);
$data['about'] = $_POST['about'];
$data['last_activity'] = date("Y-m-d h:i:s");
if($user->uploadAvatar){
$data['avatar'] = $_FILES['avatar']['name'];
} else {
$data['avatar'] = 'noimage.png';
}
} ?>
This is my Form:
<form role="form" enctype="multipart/form-data" method="post" action="register.php">
<div class="form-group">
<label>Name*</label>
<input type="text" class="form-control" name="name" placeholder="Enter Name"/>
</div>
<div class="form-group">
<label>Email Address*</label>
<input type="email" class="form-control" name="email" placeholder="Enter Your Email Address"/>
</div>
<div class="form-group">
<label>Choose UserName*</label>
<input type="text" class="form-control" name="username" placeholder="Create Username"/>
</div>
<div class="form-group">
<label>Password*</label>
<input type="password" class="form-control" name="password" placeholder="Enter A Password"/>
</div>
<div class="form-group">
<label>Confirm Password*</label>
<input type="password" class="form-control" name="password2" placeholder="Enter Password Again"/>
</div>
<div class="form-group">
<label>Upload Avatar</label>
<input type="file" name="avatar" />
<p class="help-block"></p>
</div>
<div class="form-group">
<label>About Me</label>
<textarea id="about" rows="6" cols="80" class="form-control" name="about" placeholder="Tell Us About Yourself (Optional)"></textarea>
</div>
<input name="register" type="submit" class="btn btn-default" value="Register" />
</form>
But now when I run the registration it hass Error
Notice: Undefined property: User::$uploadAvatar in C:\xampp\htdocs\talkingspace\register.php on line 22
any help for this Error?
You try to access uploadAvatar as if it was a property but it's a method.
So you need to change this line:
if($user->uploadAvatar){
to this:
if($user->uploadAvatar()){

file upload form doesn't work

my file upload script would no longer work after I have added the tag enctype="multipart/form-data" in the form.
This is the complete form:
echo '
<form action="/group/'.$_GET['id'].'/add_content" method="POST" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<legend>Beitrag hinzufügen</legend>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Inhalt</label>
<div class="col-lg-10">
<div class="well">
<textarea class="form-control" required="required" name="content_content" placeholder="Schreibe den Inhalt deines Beitrages hier hin..." rows="15"></textarea>
</div>
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Bilder</label>
<div class="col-lg-10">
<div style="margin-top: 6px;"><b>Anhänge sind Freiwillig. Für diese Anhänge gelten besondere Bestimmungen, diese kannst du in den Nutzungsbestimmungen nachlesen!</b><br>
<b>Es sind folgende Dateiendungen erlaubt: PNG, GIF, JPG, BMP</b><br><br></div>
<!-- <input type="file" name="content_pictures[0]" accept="image/*" /><br>
<input type="file" name="content_pictures[1]" accept="image/*" /> -->
<input readonly="" class="form-control floating-label" placeholder="Durchsuchen..." type="text">
<input id="inputFile" name="content_pictures[0]" accept="image/*" type="file">
<input readonly="" class="form-control floating-label" placeholder="Durchsuchen..." type="text">
<input id="inputFile" name="content_pictures[1]" accept="image/*" type="file">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Video</label>
<div class="col-lg-10">
<div style="margin-top: 6px;"><b>Anhänge sind Freiwillig. Für diese Anhänge gelten besondere Bestimmungen, diese kannst du in den Nutzungsbestimmungen nachlesen!</b><br>
<b>Es sind folgende Dateiendungen erlaubt: AVI, MP4, WMV, FLV</b><br><br></div>
<!-- <input type="file" name="content_video[0]" accept="video/*" /> -->
<input readonly="" class="form-control floating-label" placeholder="Durchsuchen..." type="text">
<input id="inputFile" name="content_video[0]" accept="video/*" type="file">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<a class="btn btn-danger" href="/group/'.$_GET['id'].'/members">Abbrechen</a>
<input type="submit" name="submitt" value="Beitrag hinzufügen" class="btn btn-success" style="background-color: #00CC66;">
</div>
</div>
</fieldset>
</form>
';
And here is the corresponding PHP script:
if(isset($_POST['submitt'])) {
$content = $_POST['content_content'];
$group_id = $_GET['id'];
$user_id = $aaa['id'];
$user_name = $aaa['username'];
$query = "INSERT INTO groups_content (group_id, autor_id, autor_name, content, date) VALUES (:group_id, :autor_id, :autor_name, :content, :date)";
$smt = $db->prepare($query);
$smt->execute(array(':group_id' => $group_id, ':autor_id' => $user_id, ':autor_name' => $user_name, ':content' => $content, ':date' => time()));
$query = "SELECT LAST_INSERT_ID(id) AS id FROM groups_content WHERE autor_id = :autor_id ORDER BY id DESC";
$smt2 = $db->prepare($query);
$smt2->execute(array(':autor_id' => $user_id));
$lastid = $smt2->fetch(PDO::FETCH_ASSOC);
foreach ($_FILES["content_pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["content_pictures"]["tmp_name"][$key];
$name = $_FILES["content_pictures"]["name"][$key];
$file_namerev = strrev($name);
$parts = explode(".",$file_namerev);
$endung = strrev($parts[0]);
if($endung == "png" || $endung == "gif" || $endung == "jpg" || $endung == "bmp" || $endung == "PNG" || $endung == "GIF" || $endung == "JPG" || $endung == "BMP") {
$file = "$randomstring.$endung";
$query = "INSERT INTO groups_content_media (content_id, media_art, media_file) VALUES (:id, `1`, :file)";
$smt3 = $db->prepare($query);
$smt3->execute(array(':id' => $lastid['id'], ':file' => $file));
move_uploaded_file($tmp_name, "upload_group_content_media_image/$randomstring.$endung");
} else {
echo '<div class="alert alert-danger">Die Bilder wurden aufgrund einer unerlaubten Dateiendung nicht hochgeladen! Der Rest wurde gespeichert!</div>';
}
}
}
foreach ($_FILES["content_video"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["content_video"]["tmp_name"][$key];
$name = $_FILES["content_video"]["name"][$key];
$file_namerev = strrev($name);
$parts = explode(".",$file_namerev);
$endung = strrev($parts[0]);
if($endung == "avi" || $endung == "mp4" || $endung == "wmv" || $endung == "flv" || $endung == "AVI" || $endung == "MP4" || $endung == "WMV" || $endung == "FLV") {
$file = "$randomstring.$endung";
$query = "INSERT INTO groups_content_media (content_id, media_art, media_file) VALUES (:id, `2`, :file)";
$smt4 = $db->prepare($query);
$smt4->execute(array(':id' => $lastid, ':file' => $file));
move_uploaded_file($tmp_name, "upload_group_content_media_image/$randomstring.$endung");
} else {
echo '<div class="alert alert-danger">Das Video wurde aufgrund einer unerlaubten Dateiendung nicht hochgeladen! Der Rest wurde gespeichert!</div>';
}
}
}
echo '<div class="alert alert-success">Ihr Beitrag wurde erfolgreich gespeichert. Sie werden in 3 Sekunden weitergeleitet.</div>';
echo '<meta http-equiv="refresh" content="3; url=/group/'.$_GET['id'].'/home">';
}

Upload more than one image to a server folder

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

File uploading, transfer and storage

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

Categories