PHP upload form won't upload more than 16 files - php

The files are relatively small XMLs that are far below the max upload limit, and I've adjusted my max_file_upload value in php.ini to 30. All of the files can be uploaded in any combination up to 16 of them. What's more, the form will not actually "POST." It will action over to the next page, but I've put in some code to display text if the form has been submitted, which it won't if more than 16 files are selected. I'm at a loss for this one, not much help around the web either.
<form method="post" enctype="multipart/form-data" name="uploadForm" id="uploadForm" action="?pa=uxf">
<table border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr>
<td valign="top"><label for="fileField"><strong>Upload XML Files to Repository:</strong></label><br /><?php
if(isset($_POST['upload'])) {
$fileCount = count($_FILES['fileToUpload']['tmp_name']);
echo '<br /><br />File Count: '.$fileCount.'<br />';
for ($i = 0; $i < $fileCount; $i++) {
echo '<br />';
$target_dir = 'uploads/';
$target_file = $target_dir.basename($_FILES['fileToUpload']['name'][$i]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = filesize($_FILES['fileToUpload']['tmp_name'][$i]);
if($check !== false) {
echo '<span style="color: #00AA00">File is an xml.</span><br />'.$check['mime'];
$uploadOk = 1;
} else {
echo '<span style="color: #FF0000">File is not an xml.</span><br />';
$uploadOk = 0;
}
if (file_exists($target_file)) {
echo '<span style="color: #FF0000">Sorry, <strong>'.$target_file.'</strong> already exists.</span><br />';
$uploadOk = 0;
}
if ($_FILES['fileToUpload']['size'][$i] > 50000000) {
echo '<span style="color: #FF0000">Sorry, your file is too large. Must be less than 50MG.</span><br />';
$uploadOk = 0;
}
if($fileType != 'xml') {
echo '<span style="color: #FF0000">Sorry, only XML files are allowed.</span><br />';
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo '<span style="color: #FF0000">Sorry, your file was not uploaded.</span><br />';
} else {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'][$i], $target_file)) {
echo '<span style="color: #00AA00">The file '.basename($_FILES['fileToUpload']['name'][$i]).' has been uploaded.</span><br />';
} else {
echo '<span style="color: #FF0000">Sorry, there was an error uploading your file.</span><br />';
}
}
}
} ?>
<table width="100%" border="0" cellspacing="5" cellpadding="5">
<tbody>
<tr valign="top">
<td><input type="file" name="fileToUpload[]" id="fileToUpload[]" multiple></td>
</tr>
<tr valign="top">
<td><input type="submit" name="upload" id="upload" value="Upload XML"></td>
</tr>
</tbody>
</table></td>
<td valign="top"><strong>Uploaded Files List:</strong><br><?php
$int = 1;
foreach (new DirectoryIterator($directory) as $fileInfo) {
if($fileInfo->isDot()) continue;
$file = $fileInfo->getFilename();
echo $int.'. '.$file.'<br />';
$int++;
} ?></td>
</tr>
</tbody>
</table>
</form>

In addition to max_file_upload, there are two other ini settings that concern file uploads that may be relevant.
upload_max_filesize (default 2 MB) limits the per-file upload size, and post_max_size (default 8 MB) limits the total size of POST content, including file uploads.
If you are running afoul of either limit, that can result in the behavior you are seeing.
As both of these are relevant before php code beings executing, you'll need to look at your php.ini (and/or .htaccess settings, as the case may be) and ensure that they are set to a level that will allow for all of your POST content to be accepted.

Related

This is simple php code which displays image chosen from directory, but when I run it, It shows torn image and doesn't display the actual image

This is simple php code which displays image chosen from directory, but when I run it, It shows torn image and doesn't display the actual image..
This is the output that I am getting
Does anyone know why is this happening?
I have tried to run this in all browsers, and it is still showing
This is the code:
<html>
<head>
<title>PHP File Upload example</title>
</head>
<body style="background-color:cyan;">
<style>
p
{
background-color: yellow;
border: 3px solid black;
text-align: center;
}
#grad
{
background-image: linear-gradient(indigo,violet,cyan);
text-align: center;
}
</style>
<div id = "grad">
<b>
<form action="p10a.php" enctype="multipart/form-data" method="post">
Select image from dir :
<input type="file" name="file"><br/><br>
<input type="submit" value="Upload" name="Submit1"> <br/>
</b>
</form><p>
<?php
if(isset($_POST['Submit1']))
{
$target_dir = "C:/xampp/htdocs/LAMP LAB";
$target_file1 = basename($_FILES["file"]["name"]);
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";?><br><?php
$file = $target_file1;
$filesize = filesize($file); // bytes
$filesize = round($filesize / 1024, 2); // kilobytes with two digits
echo "The size of your file is $filesize KB.";?><br><?php
echo "Content last changed: ".date("F d Y H:i:s.", filemtime($file));?></p>
<br><br><br><br><b><?php
echo "<img src='C:/xampp/htdocs/LAMP LAB".$imageFileType."' width='200'> "; //display image
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
</body>
</html>
[This is the output that I am getting]
https://i.stack.imgur.com/mQNdX.png
Use the following code.
<html>
<head>
<title>PHP File Upload example</title>
</head>
<body style="background-color:cyan;">
<style>
p
{
background-color: yellow;
border: 3px solid black;
text-align: center;
}
#grad
{
background-image: linear-gradient(indigo,violet,cyan);
text-align: center;
}
</style>
<div id = "grad">
<b>
<form action="" enctype="multipart/form-data" method="post">
Select image from dir :
<input type="file" name="file"><br/><br>
<input type="submit" value="Upload" name="Submit1"> <br/>
</b>
</form><p>
<?php
if(isset($_POST['Submit1']))
{
$target_dir = "LAMP LAB/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["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;
}
// 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;
}
echo $target_file;
// 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["file"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["file"]["name"])). " has been uploaded.";
echo "Content last changed: ".date("F d Y H:i:s.", filemtime($target_file));?></p>
<br><br><br><br><b><?php
echo "<img src='".$target_file."' width='200'> "; //display image
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
</body>
</html>

Input mp3 file returns 0

When I try to input an mp3 file the $_FILES returns null.
Controller:
$audio = $_FILES['muziek']['tmp_name'];
if ($audio != ''){
$audioContent = file_get_contents($audio);
$this->load->model('muziek_model');
$this->muziek_model->insertMuziek($audioContent);
}
var_dump($audio);
var_dump($audioContent);
View:
<?php echo form_open_multipart('Muziek/uploadMuziek');?>
<table>
<tr>
<td><?php echo form_label('MP3 Bestand:', 'muziek'); ?></td>
<td><input type="file" name="muziek" id="muziek" accept=".mp3" style="margin-left: 10px; padding-bottom: 35px; color: black" class="btn btn-login form-control login-formcontrol bg-white"/></td>
</tr>
<tr>
<td></td>
<td>
<?php echo form_submit('knop', 'Uploaden', 'class = "btn btn-login login-formcontrol"'); ?>
</td>
</tr>
</table>
<?php echo form_close();?>
When I select an mp3 file audio should not be null
File uploads can fail for a variety of reasons. https://www.php.net/manual/en/features.file-upload.errors.php
Your's is failing because it is too big:
Value: 1; The uploaded file exceeds the upload_max_filesize directive
in php.ini.
If you have access to php.ini you can change this variable to make it accept larger files.
Even if you do this with success, I would suggest checking for upload errors if(!isset($_FILES['muziek']['tmp_name']) || $_FILES['muziek']['error'] !== 0) { echo 'error'; } before trying to perform actions on a file that may or may not exist.
I personally use: https://github.com/verot/class.upload.php
but Codeigniter has an in-built upload library.

Only allow image & PDF types in image uploader PHP script

I have a script that allows only 1 image to be uploaded which works fine.
But right now it allows any and all types to uploaded.
How do I only allow jpg, jpeg, gif, png & PDF files to be the only ones allowed to upload?
Here is part of my code.
<?php
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.form.php';
// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.success.php';
// name of the fieldname used for the file in the HTML form
$fieldname = 'file';
//echo'<pre>';print_r($_FILES);exit;
// Now let's deal with the uploaded files
// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');
// check the upload form was actually submitted else print form
isset($_POST['submit'])
or error('the upload form is needed', $uploadForm);
// check if any files were uploaded and if
// so store the active $_FILES array keys
$active_keys = array();
foreach($_FILES[$fieldname]['name'] as $key => $filename)
{
if(!empty($filename))
{
$active_keys[] = $key;
}
}
// check at least one file was uploaded
if (count($active_keys) < 1)
{ echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>You must upload one file.</b>
<br><br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\"> "; }
//count($active_keys)
//or error('No files were uploaded', $uploadForm);
// check for standard uploading errors
foreach($active_keys as $key)
{
($_FILES[$fieldname]['error'][$key] == 0)
or error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
}
// check that the file we are working on really was an HTTP upload
foreach($active_keys as $key)
{
#is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an HTTP upload', $uploadForm);
}
// make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
foreach($active_keys as $key)
{
$now = time();
while(file_exists($uploadFilename[$key] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'][$key]))
{
$now++;
}
}
// now let's move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{
#move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
or error('receiving directory insuffiecient permission', $uploadForm);
}
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to the success page.
if($_FILES['file']['error'] === UPLOAD_ERR_INI_SIZE) {
// Handle the error
echo 'Your file is too large.';
die();
}
// make an error handler which will be used if the upload fails
function error($error, $location, $seconds = 5)
{
echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<!--<b>Your proof is not a supported filetype.<br>
Please upload an image (jpg, gif, png, bmp file) or PDF file.
<br>
<br>
or</b>
<br>
<br>-->
<b>Your File Size is bigger then the maximum allowed - 2 MB.<br>
Please upload a smaller file.</b>
<br><br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\">";
}
/*
{
header("Refresh: $seconds; URL=\"$location\"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
'<html lang="en">'."\n".
'<head>'."\n".
'<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
'<link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
'<title>Upload error</title>'."\n\n".
'</head>'."\n\n".
'<body>'."\n\n".
'<div id="Upload">'."\n\n".
'<h1>Upload failure</h1>'."\n\n".
'<p>An error has occured: '."\n\n".
'<span class="red">' . $error . '...</span>'."\n\n".
' The upload form is reloading</p>'."\n\n".
' </div>'."\n\n".
'</html>';
exit;
} // end error handler
*/
// < input id="file1" name="file[]" type="file" style="border: 1px solid white;">
//$fi= $_POST['file[]'];
//$fi = "(0)";
$fi = array($_FILES['file']['name']['0'],$_FILES['file']['name']['1'],$_FILES['file']['name']['2']);
====EDIT====
I was able to get it to ONLY allow images, but now how to I allow PDF's to be uploaded also?
I added this code to my script.
foreach($active_keys as $key)
{
#getimagesize($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
}
Just attached the following line in your code. its will checks upload file is image or pdf before it move to directory.
$allowedExts = array("gif", "jpeg", "jpg", "png", "pdf");
$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"]["type"] == "application/pdf")
&& in_array($extension, $allowedExts)) {
// put the upload code here
} else {
// put error message here
}
I was able to achieve this with the code below.
$thefilename = $_FILES["file"]["name"][0];
/* first, check for suffix
(jpg, gif, png, bmp file) or PDF file */
$thefilesuffix = substr($thefilename, -3);
// echo "<p>".$thefilesuffix."</p><hr />";
switch($thefilesuffix)
{
case "pdf": case "PDF":
/* don't need to do anything special,
but notice the capitalized versions */
break;
case "jpg": case "gif": case "png": case "bmp":
case "JPG": case "GIF": case "PNG": case "BMP":
//ALLOWS ONLY IMAGES TO BE UPLOADED
foreach($active_keys as $key)
{
#getimagesize($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
}
//ALLOWS ONLY IMAGES TO BE UPLOADED
break;
default:
echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>Your proof must be an an image (jpg, gif, png, bmp file) or PDF file.<br>
Please upload a different file.</b>
<br>
<br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\">"; exit;
break;
}

Save file path in MySQL database when uploading file to server

I am newbie in PHP.
I compiled below PHP codes to re-size images in two size and it works great.
My Question
I need to save the uploaded image paths in MySQL database.
Paths
1) path to small image
2) path to big image
This is the codes
<?php
error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","400");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=150;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=50;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$filename = "profile.pic/profile/big" .date('Y-m-d_His - '). $_FILES['file']['name'];
$filename1 = "profile.pic/header/small".date('Y-m-d_His - '). $_FILES['file']['name'];
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors)
{
// mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
$change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
}
?>
This is the Form
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta content="en-us" http-equiv="Content-Language">
<title>picture demo</title>
<link href="file:///C|/Users/Rameen/Downloads/.css" media="screen, projection" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<style type="text/css">
.help
{
font-size:11px; color:#006600;
}
body {
color: #000000;
background-color:#999999 ;
background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
}
.msgdiv{
width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF;}</style>
</head><body>
<div align="center" id="err">
<?php echo $change; ?> </div>
<div id="space"></div>
<div id="container" >
<div id="con">
<table width="502" cellpadding="0" cellspacing="0" id="main">
<tbody>
<tr>
<td width="500" height="238" valign="top" id="main_right">
<div id="posts">
<img src="<?php echo $filename; ?>" /> <img src="<?php echo $filename1; ?>" />
<form method="post" action="" enctype="multipart/form-data" name="form1">
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
<tr><Td style="height:25px"> </Td></tr>
<tr>
<td width="150"><div align="right" class="titles">Picture
: </div></td>
<td width="350" align="left">
<div align="left">
<input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
</div></td>
</tr>
<tr><Td></Td>
<Td valign="top" height="35px" class="help">Image maximum size <b>400 </b>kb</span></Td>
</tr>
<tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr>
<tr>
<td width="200"> </td>
<td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="200" align="center"><div align="left"></div></td>
<td width="100"> </td>
</tr>
</table></td>
</tr>
</table>
</form>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body></html>
Any help will be appreciated.
You should try move_uploaded_file function for both the images. Create two sepearte directories in your server and loop through both files and use the move_uploaded_file.
Also create two fields in your database for storing both paths. and dump both parts in it.
$path='upload/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'] , $path);
mysql_query("insert into tablename (filepath) values('$path')");
Question: I need to save the uploaded image paths in MySQL database
And you have directories already so I think to will need to write a database query for this.
$yourDir = "path to your directory";
$completePathtoYourFile = $yourDir . "/" . $imageName . ".jpg"; //do not append .jpg if already.
Find how to connect to a mysql database. DB CONNECTION
$insert = "INSERT INTO table_name (field1, field2) VALUES ('$completePathtoYourFile', .......) ";
$result = mysqli_query($connectionVariable, $insert);
if(!$result){
echo "Not Inserted..";
}
else{
echo "Saved..";
}
As mentioned by other people you need to move the uploaded file from the temporary storage to a dir who's path is your $yourDir.

php image upload

How to make a basic PHP uploader? I want my images to save in my htdocs/myfolder/
Here is my code:
<form enctype="multipart/form-data" method="post" action="img_uploader.php">
<input type="file" name="fileToUpload" /><br />
<input type="submit" value="Upload File" />
</form>
the code below is a simple example touching all the aspects of image or file upload take a look at it and understand it
<?php
/* to do large file uploads open the php.ini file and set "post_max_size = 150M" or the
size you wish and also set "upload_max_filesize = 120M" post_max_size must be greater than upload_max_filesize in oder
to work, also set the "max_input_time" and "max_execution_time" to 300 (5 minutes specified in seconds)
or more if you wish finally set them in your php script as below, also set "memory_limit = 1024M" or what you wish
by default "memory_limit = 128M" Note in Wamp this should be done in C:\wamp64\bin\apache\apache2.4.23\bin\php.ini and
in C:\wamp64\bin\php\php5.6.25\php.ini or C:\wamp64\bin\php\php7.0.10\php.ini depending on the php version you are using
the values must all be the same in all scripts */
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '50M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
ini_set('memory_limit','500M');
//set errors array
function output_errors($errors){
$output = array();
foreach($errors as $error){
$output[] = '<li>' . $error . '</li>';
}
return '<ul class="errors">' . implode('', $output) . '</ul>';
}
//set validation array
function output_valids($no_errors){
$output = array();
foreach($no_errors as $no_error){
$output[] = '<li>' . $no_error . '</li>';
}
return '<ul class="valid">' . implode('', $output) . '</ul>';
}
$no_errors = array();
$errors = array();
if (isset($_FILES['image']) AND $_FILES['image']['error']== 0){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$only_extentios = array('jpg', 'jpeg', 'gif','png');
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
array_push($no_errors,"File is an image - " . $check["mime"] . ".");
$uploadOk = 1;
} else {
array_push($errors,"File is not an image.");
$uploadOk = 0;
}
}
// check for correct image extention and size
if (!in_array($imageFileType,$only_extentios)){
array_push($errors,"Sorry, only jpg, jpeg, png & gif files are allowed.");
$uploadOk = 0;
}elseif ($_FILES["image"]["size"] > 10000000){
array_push($errors,"Sorry, your file is too large.");
$uploadOk = 0;
}
// Check if file already exists, if uploadok is set to one ant try to upload image
if (file_exists($target_file)) {
array_push($errors,"Sorry, file already exists.");
$uploadOk = 0;
}
if($uploadOk == 1){
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
}else{
array_push($errors,"Sorry, your file was not uploaded.") ;
}
if (file_exists($target_file)){
array_push($no_errors,"The file ". basename( $_FILES["image"]["name"]). " has/had been uploaded.");
} else {
array_push($errors,"Sorry, there was an error uploading your image.");
}
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8"/>
<title > image upload </title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="author" content="image uploader"/>
<style type="text/css" >
*,{
margin: 0px;
padding: 0px;
font-family: 'Oswald', sans-serif;
}
header,section,footer,aside,nav,article,hgroup {
display: block;
}
body{
width:100%; color:black;
display:-webkit-box;
-webkit-box-pack: center;
-webkit-box-orient:vertical;
-webkit-box-flex: 1;
background: rgba(204,204,255,0.9);
background-repeat:repeat;
}
.errors{
width:97%;
height:auto;
float:left;
margin-left:3%;
padding:10px;
}
.errors li{
text-align:left;
color:red;
font-size:15px;
list-style:;
}
.valid{
width:97%;
height:auto;
float:left;
margin-left:3%;
padding:10px;
}
.valid li{
text-align:left;
color:green;
font-size:15px;
list-style:;
}
</style>
</head>
<body>
<p><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" >
<?php
echo output_valids($no_errors);
?>
Sélectionnez une photo:
<label class="custom-file-upload" style=" margin:0px auto;"> <input type="file" name="image" /> choix </label>
<input type="submit" value="Envoyer " name="submit"/>
<?php
echo output_errors($errors);
?>
</form></p>
</body>
</html>
Here is a quick tutorial I found for doing a file upload:
http://www.tizag.com/phpT/fileupload.php
I read through it pretty quick, but it gives you the basic idea with some safety stuff to boot
specify your directory path here
$target_path = "uploads/";
replace the name of file input with uploadedfile and rest code will work fine
`
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}`
As Your Code below is working example:
first create a folder with name "myfolder" in your htdocs folder
[img_uploader.php]
<?php
$target_path = "myfolder/";
$target_path = $target_path . basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
In the working directory is fine work upload but, uploading in the database at the same time is note working any one solve this problem? kindly.
function doInsert(){
if(isset($_POST['save'])){
if ( $_POST['BRANCHNAME'] == "" || $_POST['BRANCHLOCATION'] == "" || $_POST['BRANCHCONTACTNO'] == "" ) {
$messageStats = false;
message("All field is required!","error");
redirect('index.php?view=add');
}else{
$branch = New Branch();
$branch->BRANCHNAME = $_POST['BRANCHNAME'];
$branch->BRANCHLOCATION = $_POST['BRANCHLOCATION'];
$branch->BRANCHCONTACTNO = $_POST['BRANCHCONTACTNO'];
$branch->BRANCHLEVEL = $_POST['BRANCHLEVEL'];
$branch->BRANCHSTATUS = $_POST['BRANCHSTATUS'];
$branch->BRANCHMANAGER = $_POST['BRANCHMANAGER'];
$branch->BRANCHDESCRIPTION = $_POST['BRANCHDESCRIPTION'];
//$branch->PICLOCATION = $_POST['PICLOCATION'];
$branch->_FILES = $_POST['PICLOCATION'];
$file =$_FILES['PICLOCATION'];
$filename = $file['name'];
$filepath = $file['tmp_name'];
$fileerror = $file['error'];
if ($fileerror == 0) {
$destfile = 'photos/'.$filename;
move_uploaded_file($filepath, $destfile);
$branch->LATITUDE = $_POST["LATITUDE"];
$branch->LONGITUDE = $_POST["LONGITUDE"];
$branch->create();
message("New Branch created successfully!", "success");
redirect("index.php");
}
}
}
}

Categories