Below is a php function of my post method. I am not receiving any errors but however it is not uploading into the folder I have assigned to.
I am using a localhost and there are no errors regarding the database!
<div id="box">
<form method='post' enctype="multipart/form-data">
<?php
if(isset($_FILES['video'])){
$name = $_FILES['video']['name'];
$type = explode('.', $name);
$type = end($type);
$size = $_FILES['video']['name'];
$random_name = rand();
$tmp = $_FILES['video']['tmp_name'];
if($type != 'mp4' && $type != 'mp4' && $type != 'flv'){
$message = "Video Format Not Supported!";
}
else {
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$type);
mysql_query("INSERT INTO videos VALUES('.' '$name'; 'videos/$random_name.$type')");
$message = "Successfully Uploaded!";
}
echo "$message";
}
?>
Select Video : <br/>
<input type='file' name="video" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
Related
This question already has answers here:
Styling an input type="file" button
(46 answers)
Closed 6 years ago.
I am making a Mail Compose Page.
I want to give the user an option to attach a file.
I also want to make the attachment button as an image which I already have.
I have made an image button but the image is acting like a submit button.
But I want it to be an Browse button.
My form is:
<form method="post" action="" enctype="multipart/form-data">
To: <span class="error">* <?php $receiverIdErr ?></span>
<select id="receiverId" name="receiverId">
<?php
$conn = connect();
$receiverIdQuery = "SELECT Email FROM Users";
$receiverIdResult = $conn->query($receiverIdQuery);
if($receiverIdResult->num_rows > 0) {
while($row = $receiverIdResult->fetch_assoc()) {
$Email = $row["Email"];
echo "<option value=\"$Email\">" . $row["Email"] . "</option>";
}
}
?>
</select>
<br /><br />
Subject: <input type="text" name="Subject" required>
<br /><br />
Body: <span class="error">* <?php $BodyErr ?></span>
<textarea name="Body" rows="10" cols="100" maxlength="300" required>
</textarea>
<br /><br />
Attachment:
<input type="image" src="paperclip4_black.png" width="20" height="20" name="myFile" id="myFile">
<br /><br />
<input type="submit" name="Send" value="Send">
</form>
And my PHP is:
<?php
$BodyErr = $receiverIdErr = "";
$Body = $Subject = $receiverId = $filePath = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$Subject = test_input($_POST["Subject"]);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Body"]))
$BodyErr = "Body is required";
else
$Body = test_input($_POST["Body"]);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["receiverId"]))
$receiverIdErr = "Choose a receiver";
else
$receiverId = test_input($_POST["receiverId"]);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_FILES["myFile"]["name"])) {
$target_dir = "asset/attachments/" . time();
$target_file = $target_dir . basename($_FILES["myFile"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if ($uploadOk == 0) {
$message = "Sorry, your file was not uploaded.<br />";
}
else {
if (move_uploaded_file($_FILES["myFile"]["tmp_name"], $target_file)) {
$filePath = $target_file;
}
else {
$filePath = $target_file;
}
}
}
}
?>
Might be you are looking for this :
<input type="file" name="fileToUpload" id="fileToUpload">
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i want to upload multi images in my database just url images the code is work fine but i can upload just one image i need to upload 3 images i have in database table e_img - e_img2 - e_img3 how can upload images url in 3 columns
this my class upload :
<?php
class Upload {
private $allowedExts = array('doc','docx','pdf','txt','jpg','png');
private $maxSize;
private $file;
private $uploadsDirecotry;
private $fileUrl;
private $filenames = array();
function __construct($file,$allowedExts,$uploadsDirecotry,$maxSize){
if(is_array($allowedExts) AND is_int($maxSize)){
$this->file = $file;
$this->allowedExts = $allowedExts;
$this->maxSize = $maxSize;
$this->uploadsDirecotry = $uploadsDirecotry;
}else{
throw new Exception("File extension must be in an array and max size value must be intger value.");
}
}
function uploadFiles(){
$file = $this->file;
$allowedExts = $this->allowedExts;
$maxsize = $this->maxSize;
$uploadsDir = $this->uploadsDirecotry;
for($i = 0; $i < count($file['name']); $i++){
$errors = array();
// print_r($_FILES);
$filename = $file['name'][$i];
$fileext = strtolower(end(explode('.',$filename)));
$filesize = $file['size'][$i];
$filetmpname = $file['tmp_name'][$i];
if(in_array($fileext, $allowedExts) === FALSE){
$errors[] = "Extension in sot allowed";
}
if($filesize > $maxsize){
$errors[] = "File size must be less than {$maxsize} KB !";
}
if(empty($errors)){
$random = rand(0,199);
$this->fileUrl = $random . "_" . date("d-m-Y") . "_" . $filename;
$destination = $uploadsDir. $random."_".date("d-m-Y") . "_" . $filename;
move_uploaded_file($filetmpname, $destination);
$this->filenames[] = $this->fileUrl;
}else{
foreach($errors as $error){
throw new Exception($error);
}
}
} // end for
return TRUE;
}
function getFileUrl()
{
return $this->fileUrl;
}
function getFilesNames()
{
return $this->filenames;
}
}
?>
and this html php file
<?php include 'header.php';
if(isset($_POST['add']))
{
$e_title = $_POST['e_title'];
$e_user = $userRow['user_name'];
try{
include 'models/Upload.php';
$file = $_FILES['e_img'];
$allowedExts = array('jpg','png','gif','jpeg');
$uploadsDirectory = "imgupload/";
$maxSize = 4000000;
$upload = new Upload($file, $allowedExts, $uploadsDirectory, $maxSize);
$upload->uploadFiles();
$e_img = $uploadsDirectory.$upload->getFileUrl();
}catch(Exception $exc){
echo'<div class="alert alert-block alert-danger">fail image uploaded</div>';
exit;}
$insert = $user->insert($e_title,$e_img,$e_user);
echo"<div class='alert alert-block alert-success'>Save success</div>";
exit;
}
?>
<form action='newads.php' method="POST" enctype="multipart/form-data">
<p>إضافة صور </p>
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="submit" name='add' class='btn btn-primary' value='add' />
</form>
<?php include 'footer.php'; ?>
i try this but But it did not succeed
<form action='newads.php' method="POST" enctype="multipart/form-data">
<p>إضافة صور </p>
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img2[]' id="exampleInputFile">
<input type="file" name='e_img3[]' id="exampleInputFile">
<input type="submit" name='add' class='btn btn-primary' value='add' />
</form>
You do not need to increment the field names in your file fields. That will break the array when PHP receives it. Change to this: (they should all be e_img[]
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img[]' id="exampleInputFile">
i have a problem in multiple image upload, when i upload, there's only 1 image which go to the targeted directory and database. i need two images to go directory and database...any help please?
this is my form
<form action="test.php" method="post" enctype="multipart/form-data">
Keywords: <input style="margin-left:35px;" type="text" name="keyword" /><br />
Name: <input style="margin-left:60px;" type="text" name="name" /><br />
Name2: <input style="margin-left:60px;" type="text" name="name2" /><br />
Categorie: <input style="margin-left:40px;" type="text" name="categorie" /><br />
Lieu: <input style="margin-left:70px;" type="text" name="lieu" /><br /><br />
<input type="file" name="file[]" multiple="multiple" /><input type="file" name="file_2[]" multiple="multiple"/><input type="submit" name="submit" value="Upload" />
</form>
<?php
$connect = mysql_connect("localhost", "root", "");
$select_db = mysql_select_db("yakatrouver_test", $connect);
if(#$_POST['submit']){
$keywords = $_POST['keyword'];
$name = $_POST['name'];
$name2 = $_POST['name2'];
$categorie = $_POST['categorie'];
$lieu = $_POST['lieu'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_type = $file['type'];
$file_size = $file['size'];
$file_path = $file['tmp_name'];
$file_2 = $FILES['file_2'];
$file_name_2 = $file['name'];
$file_type_2 = $file['type'];
$file_size_2 = $file['size'];
$file_path_2 = $file['tmp_name'];
if($file_name!="" && ($file_type="image/jpeg"||$file_type="image/png"||$file_type="image/gif") && $file_size<=2000000)
if(move_uploaded_file ($file_path, 'pictures_uploaded/' .$file_name))
$query = mysql_query("INSERT INTO `user_input`(keyword, name, categorie, lieu) VALUES ('$keywords', '$name', '$categorie', ' $lieu')");
$query = mysql_query("UPDATE `user_input` set image='pictures_uploaded/$file_name' WHERE `name`='$name'");
if($query == true)
{
echo "file Uploaded";
}
}
$result = mysql_query("SELECT * FROM `user_input` WHERE `image`=''") or die(mysql_error());
while($row = mysql_fetch_array($result))
?>
Try:-
HTML:
<input type="file" name="file[]"/>
<input type="file" name="file[]"/>
<input type="file" name="file[]"/>
PHP:
$file_count = count($_FILES['file']['name']);
for($i=0;$i<$file_count;$i++) {
$file_name = $_FILES['file']['name'][$i];
$file_type = $_FILES['file']['type'][$i];
$file_size = $_FILES['file']['size'][$i];
$file_path = $_FILES['file']['path'][$i];
if($file_name!="" && ($file_type="image/jpeg"||$file_type="image/png"||$file_type="image/gif") && $file_size<=2000000)
if(move_uploaded_file ($file_path, 'pictures_uploaded/' .$file_name))
$query = mysql_query("INSERT INTO `user_input`(keyword, name, categorie, lieu) VALUES ('$keywords', '$name', '$categorie', ' $lieu')");
$query = mysql_query("UPDATE `user_input` set image='pictures_uploaded/$file_name' WHERE `name`='$name'");
if($query == true)
{
echo "file Uploaded";
}
}
} //close the braces accordingly, some seem to be missing in your code
I think it's self-explanatory. It's just looping through your file input array, fetching each file information and processing one at at time.
I try to upload pictures from a form in PHP.
I've got a strange problem regarding my images upload:
My form:
<form id="booking-step" method="post" action="add.php" class="booking" autocomplete="off" enctype="multipart/form-data">
<input type="file" id="AddPhotos1" name="AddPhotos[]" />
<input type="file" id="AddPhotos2" name="AddPhotos[]" />
<input type="file" id="AddPhotos3" name="AddPhotos[]" />
<input type="file" id="AddPhotos4" name="AddPhotos[]" />
<input type="file" id="AddPhotos5" name="AddPhotos[]" />
</form>
My PHP:
if($_FILES['AddPhotos']){
$errorAddPhotos = "";
$validAddPhotos = "";
for($x=0;$x<sizeof($_FILES["AddPhotos"]["name"]);$x++){
$fichier = basename($_FILES['AddPhotos']['name'][$x]);
$taille_maxi = 3000;
$taille = filesize($_FILES['AddPhotos']['tmp_name'][$x]);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['AddPhotos']['name'][$x], '.');
if(!in_array($extension, $extensions))
{
$errorAddPhotos .= "Wrong extension.<br />";
}
if($taille>$taille_maxi)
{
$errorAddPhotos .= "Wrong size.<br />";
}
if((in_array($extension, $extensions)) && ($taille<$taille_maxi))
{
$fichier = strtr($fichier,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier);
if(move_uploaded_file($_FILES['AddPhotos']['tmp_name'][$x], $destin . $fichier))
{
$validAddPhotos = 'Success!';
}
else
{
$errorAddPhotos = 'Wrong';
}
}
}
}
echo $validAddPhotos;
echo $errorAddPhotos
My code looks good, but I cant upload my files...
Error: my files stay in condition "if(!in_array($extension, $extensions))".
Could you please help ?
Thanks.
I think you should use this logic is more perform than yours with testing image type and file size. Also, you can custom it with what you want like you did name of the file :)
multiple upload image function php?
Hi there I want to make a function for me to able upload a multiple image in one submission below are my code structure:
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>Image1 :<input name="image1" type="file" /></p>
<p>Image2 :<input name="image2" type="file" /></p>
<p>Image3 :<input name="image3" type="file" /></p>
<input type="submit" value="Submit" />
</form>
include('configdb.php');
$uploadDir = 'upload/';
if(isset($_POST['submit']))
{
$fileName = $_FILES['image1']['name'];
$tmpName = $_FILES['image1']['tmp_name'];
$fileSize = $_FILES['image1']['size'];
$fileType = $_FILES['image1']['type'];
$image1path = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, "$image1path");
if (!$result) {
echo "Error uploading";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$image1 = addslashes($image1path);
}
$sql="INSERT INTO picture (image1, image2, image3) VALUES ('$image1','$image2', $image3)";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
}
Basically my code above does one image upload, How can I make a function to be able upload 3 images.
Here is the code to multiple upload image. You can upload more than 3 images.
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>Image1 :<input name="image[]" type="file" /></p>
<p>Image2 :<input name="image[]" type="file" /></p>
<p>Image3 :<input name="image[]" type="file" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include('configdb.php');
$uploadDir = 'upload/';
if(isset($_POST['submit'])) {
$image = array();
foreach($_FILES['image']['name'] as $index => $name) {
if($_FILES['image']['error'][$index] == 4) {
continue;
}
if($_FILES['image']['error'][$index] == 0) {
$fileName = $_FILES['image']['name'][$index];
$tmpName = $_FILES['image']['tmp_name'][$index];
$fileSize = $_FILES['image']['size'][$index];
$fileType = $_FILES['image']['type'][$index];
if(($fileType == "image/gif" ||
$fileType == "image/jpeg" ||
$fileType == "image/pjpeg" ||
$fileType == "image/png" ||
$fileType == "image/x-png") &&
$fileSize < 500000) {
$imagePath = $uploadDir . $fileName;
$result = #move_uploaded_file($tmpName, $imagePath);
if (!$result) {
echo "Error uploading";
exit;
}
$image[] = $imagePath;
}
}
}
// Save images to database
$nbImage = count($image);
if($nbImage) {
$sql = "INSERT INTO picture (image1, image2, image3) VALUES (";
for($i=0; $i<$nbImage; $i++) {
if($i) $sql .= ",";
$sql .= "\"".$image[$i]."\"";
}
$sql .= ")";
#mysql_query($sql);
}
}
?>
Note: you should test the type and the size of image before upload it because of the security.
Try something like this:
...
$images = array();
foreach (array('image1', 'image2', 'image3') as $name) {
$images[$name] = new stdClass();
$images[$name]->fileName = $_FILES[$name]['name'];
$images[$name]->tmpName = $_FILES[$name]['tmp_name'];
$images[$name]->fileSize = $_FILES[$name]['size'];
$images[$name]->fileType = $_FILES[$name]['type'];
$images[$name]->path = $uploadDir . $images[$name]->fileName;
$result = move_uploaded_file($images[$name]->tmpName, $images[$name]->path);
if (!$result) {
echo "Error uploading";
exit;
}
$images[$name]->sql = mysql_real_escape_string($images[$name]->path);
}
$sql="INSERT INTO picture (image1, image2, image3) VALUES ({$images['image1']},{$images['image2']},{$images['image3']})";
...