php multiple image uploader - php

For the sake of God can someone help me make the below script to upload multiple images(5). I'm stuck at this for days with no luck. I have no idea how to make it upload five images. Pleeeease help me. I tried putting five input file fields and giving them a name like name="file[]" but that doesn't seem to be working. While I upload a photo I see a error saying please select a photo even if there is a file.
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'Productpic/'; //with trailing slash
//Set max file size in bytes
$max_size = 2097152;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif', 'JPG');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif','image/JPG');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "<span class='isa_error2'>Invalid file Extension</span>";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "<span class='isa_error2'>Invalid file Type</span>";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "<span class='isa_error2'>File is too big</span>";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "<span class='isa_error2'>The file you trying to upload is not an Image, we only accept Images</span>";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "<span class='isa_error2'>The image you trying to upload already exists, please upload only once</span>";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "<span class='isa_error2'>Please select a photo</span>";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, false);
if (!is_array($file['error'])) {
$message = '';
$sub=1;
$message = "<span class='isa_success'>File uploaded successfully</span>";
echo $message;
}
}
?>
<html>
<head>
<style type="text/css" media="screen">
.isa_error2 {
border: 1px solid;
width:15%;
margin: 0px 0px;
padding:3px 20px 2px 50px;
background-repeat: no-repeat;
background-position: 10px center;-moz-border-radius:.5em;
-webkit-border-radius:.5em;
border-radius:.5em;
}
.isa_error2 {
color: #D8000C;
background-color: #FFBABA;
background-image: url('models/languages/error.png');
background-size: 28px 28px;
}
</style>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="horizontalmenu.css" type="text/css" media="screen" /><!-- Menu -->
</head>
<body id="wide">
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<?php
ini_set( "display_errors", 0);
if($sub==0)
{
?><br><br>
<input name="file[]" type="file" size="20" multiple="true" />//this was what did
<input name="file[]" type="file" size="20" multiple="true" />
<input name="file[]" type="file" size="20" multiple="true" />
<input name="file[]" type="file" size="20" multiple="true" />
<input name="file[]" type="file" size="20" multiple="true" />
<span><?php
if (isset($_POST['submit'])) {
ini_set( "display_errors", 0);
$file = uploadFile('file', true, false);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message = $msg;
}
}
echo $message;
}
?></span> <br><br><br>
<input name="submit" type="submit" value="Upload" />
<?php
}
?>
</form>

Somebody else might read this, so I'll explain about setting the input's name to name="file[]".
This means that you are creating an array containing the selected file names. For later on uploading them or saving the information to the database you have to loop trough the array:
foreach(file[] as $key){}
Another solution, messier code in my opinion, is giving each file input a different name like the person who asked the question solved his problem.
Please correct me if I'm wrong.

Hmmm I solved the problem my self.....I gave the input field different name like the below and it was simple. This shouldn't have taken me days!
<input name="file" type="file" size="20" multiple="true" />
<input name="file2" type="file" size="20" multiple="true" />
<span><?php
if (isset($_POST['submit'])) {
ini_set( "display_errors", 0);
$file = uploadFile('file', true, false);
$file = uploadFile('file2', true, false);//added this line.
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message = $msg;
}
}
echo $message;
}
?>
and finally for the success message part
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, false);
$file = uploadFile('file2', true, false);
if (!is_array($file['error'])) {
$message = '';
$sub=1;
$message = "<span class='isa_success'>File uploaded successfully</span>";
echo $message;
}
}
?>

I have created a solution for multiple images uploaded using a single textbox in php.
<form method="post" action="" enctype="multipart/form-data" id="frmImgUpload">
<input name="fileImage[]" type="file" multiple="true" />
<input name="btnSubmit" type="submit" value="Upload" />
</form>
<?php
$i=1;
if ($_POST)
{
foreach($_FILES['fileImage']['name'] as $key => $i)
{
$file_name = $_FILES['fileImage']['name'][$key];
$file_size =$_FILES['fileImage']['size'][$key];
$file_tmp =$_FILES['fileImage']['tmp_name'][$key];
$file_type=$_FILES['fileImage']['type'][$key];
move_uploaded_file($file_tmp,"uploaded_img/".$file_name);
$i++;
}
}
?>

Related

how do I display on my webpage an image file stored in my mysql database?

Can someone please help as I am at a loss. How can I get an image from MYSQL database onto my webpage. anyname.html
Database name is: upload
Table name is: images
id Primary int(11) AUTO_INCREMENT
name varchar(100)
size int(11)
type varchar(20)
content mediumblob
The upload works great but just cant get it to show the image of be able to use it in a html page. When I upload the image I get as a return: for number 11 image stored but I don't see an image: Here is my code, so please, please someone help as I have been at this for ages with no result.
my upload.php code:
<?php
// Check for post data.
if ($_POST && !empty($_FILES)) {
$formOk = true;
//Assign Variables
$path = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
$formOk = false;
echo "Error: Error in uploading file. Please try again.";
}
//check file extension
if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/jpg', 'image/gif'))) {
$formOk = false;
echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
}
// check for file size.
if ($formOk && filesize($path) > 500000) {
$formOk = false;
echo "Error: File size must be less than 500 KB.";
}
if ($formOk) {
// read file contents
$content = file_get_contents($path);
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'root', '', 'upload')) {
$content = mysqli_real_escape_string($conn, $content);
$sql = "insert into images (name, size, type, content) values ('{$name}', '{$size}', '{$type}', '{$content}')";
if (mysqli_query($conn, $sql)) {
$uploadOk = true;
$imageId = mysqli_insert_id($conn);
} else {
echo "Error: Could not save the data to mysql database. Please try again.";
}
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
}
}
?>
<html>
<head>
<title>Upload image to mysql database.</title>
<style type="text/css">
img{
margin: .2em;
border: 1px solid #555;
padding: .2em;
vertical-align: top;
}
</style>
</head>
<body>
<?php if (!empty($uploadOk)): ?>
<div>
<h3>Your Image has been Uploaded:</h3>
</div>
<div>
<img src="image.php?id=<?=$imageId ?>" width="300px" height="300px"></img>
<strong><br /><br />Embed</strong>: <input size="30" value='<img src="image.php?id=<?=$imageId ?>">'>
</div>
<hr>
<?php endif; ?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>IMAGE SELECT<br /></label>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<br /><br />
<input name="submit" type="submit" value="Upload Image">
</div>
</form>
</body>
</html>
It seems to be a duplicate from the issue there PHP display image BLOB from MySQL
Hope it helps.
If you store the image data in database, use the next image.php:
<?php
$id = $_GET['id'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('upload');
$sql = "SELECT content FROM images WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['content'];
?>

How to upload the audio file using php

i wanted to upload the mp3 file to the related folder name /uploads/ inside my project folder. But something not working correctly in php. Image file are uploading without any error but when i tried to upload the mp3 file its not working.
Here is my html form
<form action="act_songs.php" method="post" enctype="multipart/form-data">
<?php
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
<p>
<label>Song Title</label>
<input type="text" name="sng-title">
</p>
<p>
<label>Song Name</label>
<input type="file" name="mp3" accept="audio/*" runat="server">
</p>
<p>
<input type="submit" name="add-song" value="ADD">
</p>
</form>
And here is my php code
if (isset($_POST['add-song'])) {
$title = $_POST['sng-title'];
$audio = $_FILES['mp3']['name'];
$audio_type = $_FILES['mp3']['type'];
$audio_size = $_FILES['mp3']['size'];
$tmp_location = $_FILES['mp3']['tmp_name'];
$audio_url = "../uploads/".$audio;
if ($type == '.mp3' || $type == '.wav') {
if ($size <= 5000) {
move_uploaded_file($tmp_location, $audio_url);
}
}
if (!empty($title)) {
$sql = "insert into `tbl_songs` (`title`,`songs`) values ('$title','$audio_url')";
$sql_run = mysql_query($sql);
if ($sql_run) {
$_SESSION['msg'] = "<div class='alert'>Record Saved</div>";
header('location:songs.php');
}
else{
$_SESSION['msg'] = "<div class='alert'>Record Cannot Saved</div>";
header('location:add-songs.php?invalid');
}
}
else{
$_SESSION['msg'] = "<div class='alert'>Title Must be requiired.</div>";
header('location:add-songs.php?invalid');
}
}
What is the problem i am unable to debug the problem. If anybody have solution then place your answer

PHP Upload with file type and size check

I need a upload form which other people can use, to hand me in their documents.
HTML:
<form method="post" action="upload.php" enctype="multipart/form-data" id="form">
<table>
<tr><td><p>your name:</p></td></tr>
<tr><td><input name="name" type="text" size="50" style="height: 30px;"></td></tr>
<tr><td><p>your mail-adress:</p></td></tr>
<tr><td><input name="mail" type="text" size="50" style="height: 30px;"></td></tr>
<tr><td><p>your document:</p></td></tr>
<tr><td><input type="file" name="file" value="" /><br /><h6 style="margin-top: 5px; margin-bottom: 2px;">max. filesize: 2 MB<br />allowed filetypes: .doc, .docx, .pdf, .rtf, .odt</h6></td></tr>
</table>
<br />
<input type="submit" value="Send">
</form>
PHP:
<?php
$fehler = "";
$name = $_POST['name'];
$mail = $_POST['mail'];
$file = $_POST['file'];
$maxsize = "2097152"; /* 2MB in Bytes */
$allowedext = array('doc','docx' ,'pdf', 'rtf', 'odt');
if (empty($name)) {
$fehler .= "<p>• no name given!</p>" ;
}
if (empty($mail)) {
$error .= "<p>• no e-mail adress given</p>" ;
}
if (empty($file)) {
$error .= "<p>• choose a file!</p>" ;
}
if (empty($error)) {
if (!in_array(filetype($file), $allowedext) { /* check filetype */
$error .= "<p>• filetype is not allowed</p>" ;
}
if (empty($error)) {
if (filesize($file) > $maxsize) { /* check filesize */
$error .= "<p>• file is too big</p>" ;
}
if (empty($error)) {
/* send data via mail */
echo("your document has been send.");
}
}
}
echo($error);
echo ('<p>back</p>');
?>
I want to check the file type and the size before uploading it. When I upload the upload.php file to my server i just get a white screen without any errors, if i try to use this form.
Change your $_POST['file'] to $_FILES['file']
and try:
// check maximum size
if($_FILES['file']['size'] > $maxsize)
die('The file is too large');
// check file format
elseif( !in_array(pathinfo(strtolower($_FILES['files']['name']), PATHINFO_EXTENSION),$allowedex))
die($_FILES['files']['name'].' is not a valid format.');
This answer provides the solution to check size before uploading to data to the server. This makes sense. If you do a client check, you can eliminate unnecessary posts to your server. A sanity check on the server remains necessary, JavaScript code on the client can be altered. The other answers provide explanation on how to improve your server side code.
var mimeTypes = [
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", //docx
"application/pdf", //pdf
"application/msword", //doc
"rtf;application/rtf", //rtf
"rtf;application/x-rtf",
"rtf;text/richtext",
"application/vnd.oasis.opendocument.text" //odt
]
function readFiles(files)
{
var iMax = files.length;
var sum = "";
var max = 2097152;
for (var i = 0; i < iMax; i++)
{
var fileType = files[i].type;
var fileSize = files[i].size;
sum += parseInt(fileSize);
if (mimeTypes.indexOf(files[i].type) == -1)
{
alert("Invalid file selected");
return false;
}
}
if (sum > max)
{
alert("Total file size exceeds maximum upload size.");
return false;
}
return true;
}
document.getElementById("form").querySelector("input[type='file']").addEventListener("change", readFiles, false);
readFiles fires whenever a change event is fired on the file input. In browsers supporting HTML5 input elements you can read out the file type and file size property. They are inherited from the Blob object. You can even pass the file to a FileReader object allowing you to read the contents of the file.
Bug in IE 10, 11. On IE10 and 11 there is a bug present that returns an empty string on file-type when used on images. You can work around this by checking the extension.
interesting....i prefer less lines of code...
<form method="post" action="upload.php" enctype="multipart/form-data" id="form">
<table>
<tr><td><p>your name:</p></td></tr>
<tr><td><input required="required" name="name" type="text" size="50" style="height: 30px;"></td></tr>
<tr><td><p>your mail-adress:</p></td></tr>
<tr><td><input required="required" name="mail" type="text" size="50" style="height: 30px;"></td></tr>
<tr><td><p>your document:</p></td></tr>
<tr><td><input required="required" type="file" name="file" value="" /><br /><h6 style="margin-top: 5px; margin-bottom: 2px;">max. filesize: 2 MB<br />allowed filetypes: .doc, .docx, .pdf, .rtf, .odt</h6></td></tr>
</table>
<br />
<input type="submit" value="Send">
</form>
php :
<?php
define('MB', 1048576);
$name = $_POST['name'];
$mail = $_POST['mail'];
$file = $_FILES['file'];
$allowedext = array('doc','docx' ,'pdf', 'rtf', 'odt');
$filename = $file['tmp_name'];
$ext=explode(".",$filename);
if( empty($name) || empty($mail) || empty($file) || $_FILES['file']['size'] > 2*MB || !in_array($ext[1],$allowedext) )
{
echo "check file extension or check whether all fields are filled correctly!";
exit;
}
else
{
move_uploaded_file(name, name);
echo "File has been uploaded successfully!";
}
?>

Image uploader with preview didn't work

I have a single file named test.php. In this file, I written below codes to upload a picture (.PNG and .JPG). I also add some code to make a preview of pictures before being uploaded...
Nothing seems to be wrong but when I press the SUBMIT button, nothing happens...
Why? Where is my problem?
Update: I make changes and now I get this warning:
Warning: Invalid argument supplied for foreach() in...
test.php:
<script type="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<body>
<?php
if ( isset( $_POST[ 'submit' ] ) ) {
define ("UPLOAD_DIR" , "uploaded/pic/");
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
$info = getimagesize($_FILES["images"]["tmp_name"][$key]);
$image_type = $info[2];
$type = $_FILES['images']['type'][$key];
// if the image is .JPG or .PNG
if ( ($image_type == 3) || ($image_type == 2) ){
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $name);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["images"]["tmp_name"][$key], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
echo "<h2>Successfully Uploaded Images</h2>";
}
else{
echo "<h2>format not supported... </h2>";
}
}
}
}
?>
<div id="upload_form">
<form id="frm1" name="frm1" method="post" action="test.php" enctype="multipart/form-data">
<p>
<label for="images">insert your image</label>
<input type="file" name="images" id="images" tabindex="80"/>
</p>
<img id="pic" name="pic" src="#" />
<button type="submit" id="submit" name="submit">Upload Files!</button>
</form>
<script type="text/javascript" language="javascript">
// Preview the picture before Uploading on the server!
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#images").change(function(){
readURL(this);
});
</script>
</div>
You need to put your name="images as an array using []
Like this:
<input type="file" name="images[]" id="images" tabindex="80"/>

Curious problème with images upload in PHP from form

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?

Categories