Curious problème with images upload in PHP from form - php

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?

Related

uploading video file not working

I want to upload video files in php for that i am using following code
PHP
$newUploadDir = "c://video";
$idx = "file";
if (isset($_FILES[$idx]) && is_array($_FILES[$idx])) {
echo "file set";
foreach ($_FILES[$idx]["error"] as $key => $error) {
echo "loop";
if ($error == UPLOAD_ERR_OK) {
echo "<br/>dd2";
$tmp_name = $_FILES[$idx]["tmp_name"][$key];
$name = $_FILES[$idx]["name"][$key];
$ext1 = explode(".", $name);
$extension = end($ext1);
$newfilename = "test".".".$extension;
$video_types = array('mp4', 'avi','webm');
if (in_array($extension, $video_types)) {
if (move_uploaded_file($tmp_name, $newUploadDir.$newfilename)) {
echo "uploaded to folder";
} else {
echo "Not uploaded to folder";
}
}
} else {
echo "not uploaded $error";
}
}
}
echo "ok";
HTML
<form action="http://localhost/fileupload/video.php" enctype="multipart/form-data" method="post">
<input id="file1" name="file[]" type="file"/>
<input name="userId" type="text" value="2"/>
<input id="Submit" name="submit" type="submit" value="Submit" />
</form>
Output
file setloopnot uploaded 1ok
Video file is not uploading. How to resolve this?
Actually, if you try to upload very large (video) files, probably the upload file size limit will not let you do that. Instead of regular file upload, there are other possibities. For the begining, look at this, this or this.
An other aproach would be to use third party services like Amazon S3, Microsoft Azure, etc.

how can uploaded multi images in this class [closed]

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">

Image - Upload not responding, no access to $_FILES

Here is my file-upload script, and i am getting the following error
Notice: Undefined index: fupload in C:\Users\Tuskar\Desktop\Projekt\htdocs\Project IT-Space\Profile\edit_profile_parse.php on line 8
But according there should not error, because i identified the index. It seems i don't have access to the $_FILES array, because before i got this error ive been getting other similar errors or the programm completely passes the if and goes directly to the else (file not chosen)
I know the script is primitive and includes almost no security, but i just want it to work first before i add other features like max file size or file restriction ... :(
Here is the code i am using.
Upload Picture
<form action="edit_profile_parse.php" method="get" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
Here is the php that handles the form
if (isset( $_GET['submit'] ))
{
if (isset($_FILES['fupload'] ))
{
echo "name: ".$_FILES['fupload']['name']." <br> ";
echo "size: ".$_FILES['fupload']['sizw']." <br> ";
echo "type: ".$_FILES['fupload']['type']." <br> ";
if ($_FILES['fupload']['type'] == "image/gif")
{
$source = $_FILES['fupload']['tmp_name'];
$target = "images/" .$_FILES['fupload']['name'];
move_uploaded_file($source, $target) or die ("Error: " .mysql_error());
$size = getImageSize($target);
$imgstr = "<img src=\" '".$target."' \">";
echo $imgstr;
}
else
{
echo "Problem uploading the file ... ";
}
}
else
{
echo "No file chosen !! ";
}
}
else
{
echo "Button not clicked ";
}
You should use form method to POST instead of get.
<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
Make sure your FORM tag has method="POST". GET requests do not support multipart/form-data uploads.
I hope this works:
the form:
<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
the php file:
<?php
if($_POST) {
$max_size = mysql_real_escape_string(strip_tags($_POST['MAX_FILE_SIZE']));
$file = $_FILES['fupload']['name'];
if(isset($max_size) && !empty($max_size) && !empty($file)) {
$file_type = $_FILES['fupload']['type'];
$tmp = $_FILES['fupload']['tmp_name'];
$file_size = $_FILES['fupload']['size'];
$allowed_type = array('image/png', 'image/jpg', 'image/jpeg', 'image/gif');
if(in_array($file_type, $allowed_type)) {
if($file_size < $max_size) {
$path = 'images/'.$file;
move_uploaded_file($tmp, $path);
//if you want to store the file in a db use the $path in the query
} else {
echo 'File size: '.$file_size.' is too big';
}
} else {
echo 'File type: '.$file_type.' is not allowed';
}
} else {
echo 'There are empty fields';
}
}
?>
Upload Picture
<form action="edit_profile_parse.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
PHP file
<?php
if (isset( $_POST['submit'] ))
{
if (isset($_FILES['fupload'] ))
{
echo "name: ".$_FILES['fupload']['name']." <br> ";
echo "size: ".$_FILES['fupload']['size']." <br> ";
echo "type: ".$_FILES['fupload']['type']." <br> ";
if ($_FILES['fupload']['type'] == "image/gif")
{
$source = $_FILES['fupload']['tmp_name'];
$target = "images/" .$_FILES['fupload']['name'];
move_uploaded_file($source, $target) or die ("Error: " .mysql_error());
$size = getImageSize($target);
$imgstr = "<img src=\" '".$target."' \">";
echo $imgstr;
}
else
{
echo "Problem uploading the file ... ";
}
}
else
{
echo "No file chosen !! ";
}
}
else
{
echo "Button not clicked ";
}
?>

php multiple image uploader

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++;
}
}
?>

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Categories