Problems when uploading two times using same function php - php

I'm having problems with a file upload script for my site. I've copied a simple upload script, and I'm setting it up so that I can upload multiple files. I have to do this by first making one form for one file, then a copy of the form for the next one and so one. (I first set the page up with the "multiple" tag in the form, but then i discovered that the IE at work is version 8, and no flash. So I have to do it this way)
The scripts uploads ok. The problem is that the second file is called file1.jpgfile2.jpg, the third one file1.jpgfile2.jpgfile3.jpg and so on.
this is my form, followed by the code with form #2 File #2 and on goes through the same form:
<form method="post" enctype="multipart/form-data" action="rediger.php?choice=addpicturetoproc">
<input type="hidden" name="uploadpath" value="<? echo "Prosedyrer/$hovedkategori/$underkategori/$navn/$mappe_navn/" ?>">
Bildefil: <input type="file" name="fileup" value=""><br>
<input type="submit" name="submit" value="Upload">
</form>
<br>
<?
}
elseif ($choice=="addpicturetoproc")
{
$max_size = 2000; // maximum file size, in KiloBytes
$alwidth = 1900; // maximum allowed width, in pixels
$alheight = 1800; // maximum allowed height, in pixels
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png'); // allowed extensions
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']); // gets the file name
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext); // gets extension
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = ''; // to store the errors
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
echo '<h1>Filen: <b>'. basename( $_FILES['fileup']['name']). '</b> ble lastet opp!</h1>';
}
else echo '<b>Feil ved opplastning.</b>';
}
else echo $err;
}
?><p>Do you need another upload?</p>
<form method="post" enctype="multipart/form-data" action="rediger.php?choice=addpicturetoproc">
<input type="hidden" name="uploadpath" value="<? echo $uploadpath; ?>">
Bildefil: <input type="file" name="fileup" value="Sett inn bildefilen her"><br>
<input type="submit" name="submit" value="Last opp bildefil">
</form>
<br>
<form method="post" enctype="multipart/form-data" action="rediger.php?choice=menu">
<input type="submit" name="submit" value="Nei, jeg er ferdig">
</form>
I have tried using unset($fileup); before the second run, but still filename1.jpgfilename2.jpg.
Any obvious solutions?

I believe this is because you're appending to the $uploadpath
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
So the first file will be file1.jpg then the second file will be file1.jpgfile2.jpg and so on.
I would suggest setting the base upload path to a different variable and trying something like
$uploadpath = $baseuploadpath . basename( $_FILES['fileup']['name']);

Related

Unique file name when uploading using uniqid()

I am trying to upload images from a cell phone and display them on a gallery page. I need each file name to be unique or images will overwrite themselves. I have the following code where $new_image_name is suggested from this topic but I can't seem to get it to work:
if ($_FILES["image"]["error"] > 0) {
//Bad Output for form results red text
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
} else {
$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
$file="images/".$new_image_name);
$image_title = addslashes($_REQUEST['image_title']);
$sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
//Good Output for form results green text
echo '
<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<div style="padding:10px;">
<h2 style="font-size: 28px;">Success!</h2>
<p style="font-size: 18px;">Your file has been successfully uploaded!</p>
</div>
</form>';
}
mysql_close();
This was my code prior to adding uniqid() which worked fine except the images overwrote each other
} else {
move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
$file="images/".$_FILES["image"]["name"];
$image_title = addslashes($_REQUEST['image_title']);
$sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
//Good Output for form results green text
echo '
<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<div style="padding:10px;">
<h2 style="font-size: 28px;">Success!</h2>
<p style="font-size: 18px;">Your file has been successfully uploaded!</p>
</div>
</form>';
}
mysql_close();
You should really get into the habit of using error checking. As your code sits right now I can upload ANYTHING and your code will save it as a jpg image.
Start by checking to see if the user even selected a file for upload.
Then compare the file type to a predetermined list of allowed file types.
Then save it as the file type that was uploaded. Which may not always be a jpg. As your code sits right now, if I upload a gif or png file... it will save it as a jpg. Thereby rendering the image useless because it is not a jpg.
Your upload process with error checking...
<?php
$FormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$FormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if(isset($_POST["upload"]) && $_POST["upload"] == 'changer') {
// set some basic variables
$fileName = $_FILES["image"]["name"]; // The file name
$fileTempLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$type = strtolower(substr(strrchr($fileName,"."),1));
if($type == 'jpeg' || $type == 'jpe') { $type = 'jprg'; } // make a jpeg or jpe file a jpg file
if (!$fileTempLoc) { // if no file selected
die ('<div align="center" style="color:#ff0000;"><br /><h3>ERROR: Please select an image before clicking the upload button.<br /><br />Try again</h3></div>');
} else {
// This is the allowed list (images only)
$acceptable = array(
'image/jpeg',
'image/jpg',
'image/jpe',
'image/gif',
'image/png'
);
// check to see if the file being uploaded is in our allowed list
if(!in_array($_FILES['image']['type'], $acceptable) && !empty($_FILES["image"]["type"])) { // Is file type in the allowed list
die ('<div align="center" style="color:#ff0000;"><br /><h3>Invalid file type. Only JPEG, JPG, JPE, GIF and PNG types are allowed.<br /><br />Try again</h3></div>');
} else {
if ($_FILES["image"]["error"] > 0) {
//Bad Output for form results red text
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
} else {
$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.'.$type;
move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
$file="images/".$new_image_name;
$image_title = addslashes($_REQUEST['image_title']);
$sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
//Good Output for form results green text
echo '
<div style="padding:10px;">
<h2 style="font-size: 28px;">Success!</h2>
<p style="font-size: 18px;">Your file has been successfully uploaded!</p>
</div>';
mysql_close();
} // end if no errors
} // end if in allowed list
} // end if no file selected
} // end if form submitted
?>
The form...
<form enctype="multipart/form-data" action="<?php echo $FormAction ?>" method="post" name="changer">
<input type="file" name="image" id="image" />
<input name="submit" type="submit" value="Upload">
<input type="hidden" name="upload" id="upload" value="changer" />
</form>
One final note... Do yourself a favor and stop using mysql. Start using pdo_mysql instead. mysql was deprecated in PHP version 5.5 and totally removed in PHP version 7. If you're using mysql code, your code will soon stop functioning completely.
I am assuming your posted working code, then maybe because of bellow line,
$file="images/".$new_image_name);
You added extra ')' remove that line, it may work fine.
$file="images/".$new_image_name;
Let me know issue is resolved.

HTML form for PHP Image Upload Script

Can anyone give me the html code for this php image upload script. I really need it please if anyone can help me on this I will be grateful to you.
Here is php code:
if(isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg','.jpeg','.png','.gif');
$max_filesize = 10485760;
$upload_path = 'uploads/';
$description = $_POST['imgdesc'];
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
$query = "INSERT INTO uploads (name, description) VALUES ($filename, $description)";
mysql_query($query);
echo 'Your file upload was successful!';
} else {
echo 'There was an error during the file upload. Please try again.';
}
}
I came across this exact code a while back
Here you go for html
<form action="/script.php" method="post" enctype="multipart/form-data">
<input type="file" name="userfile"/>
<input type="text" name="imgdec">
<button name="upload" type="submit" value="Submit">
</form>
<form name="myFrm" id="myFrm" action="uraction" method="post" enctype="multipart/form-data" >
<label for="upload" >Select Image</label><input type="file" id="upload" name="upload" accept="image/*">
<p/>
<input type="submit" value="Go" >
</form>
Bare minimum form to work for you
You can add
<input type="hidden" name="MAX_FILE_SIZE" value="10485760"/>
before the file input field. This form element set the maximum file size of the file input field and it is measured in bytes. This MAX_FILE_SIZE is applied to the file inputs that come after it. Remember, this does not indicate the total size of all the input files. See the following example:
<input type="hidden" name="MAX_FILE_SIZE" value="10000"/>
<!--for these two consecutive input fields, maximum file size is 10000 bytes -->
<input type="file" name="userfile1"/>
<input type="file" name="userfile2"/>
<input type="hidden" name="MAX_FILE_SIZE" value="50000"/>
<!--for this input field, maximum file size is 50000 bytes -->
<input type="file" name="userfile3"/>
Save below as index.php and create a folder in the same directory called images. Remember to chmod the images folder to 777 once on the server.
<?php
if(isset($_GET['do']) && $_GET['do'] == 'upload2') {
// Start
$allowed_filetypes = array('.jpg','.jpeg','.png','.gif');
$max_filesize = 10485760;
$upload_path = 'images/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
// $query = "INSERT INTO uploads (name, description) VALUES ($filename, $description)";
// mysql_query($query);
echo 'Your file upload was successful!';
} else {
echo 'There was an error during the file upload. Please try again.';
}
// Finish
} elseif(isset($_GET['do']) && $_GET['do'] == 'upload1') {
echo '
<form action="index.php?do=upload2" method="post" enctype="multipart/form-data">
<input type="file" name="userfile"/>
<button name="upload" type="submit" value="Submit">
</form>
';
} else {
echo 'Link';
}
?>

Photo upload not uploading files bigger than 2MB

I have a php file upload in place in which the forms target is an iframe.
It uploads files less than 2mb fine. But anything larger it will not upload. I cant see any reason behind this in the code.
<div id="upload_wrapper">
<img src="../images/logo.png" alt="logo5" width="" height="" style="padding:0px;" />
<h3>Profile picture upload</h3>
<form id="upload" name="upload" enctype="multipart/form-data" method="post" action="index.php" target="upload_target">
<input name="folder" type="hidden" value="<?php echo $folder ?>" />
<input name="filename" type="hidden" value="<?php echo $filename ?>" />
<input name="uploaded_file" type="file" size="5120" id="uploaded_file" />
<input id="sent" name="sent" type="submit" value="Upload" />
</form>
</div>
<div id="loading" style="background:url(ajax-loader.gif) no-repeat left; height:50px; width:370px; display:none;">
<p style="margin-left:40px; padding-top:15px;">Uploading File... Please wait</p>
</div>
<div id="image_wrapper" style="display:none;"><p id="preview"></p></div>
<iframe id="upload_target" name="upload_target" style="width:10px; height:10px; display:none"></iframe>
</div>
And heres the php upload code
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targetFolder = $_POST['folder'] . "/";
$filename2 = $_POST['filename'];
if (!is_dir($targetFolder))
{
mkdir($targetFolder, 0777);
}
$tempFile = $_FILES['uploaded_file']['tmp_name'];
$targetPath = dirname(__FILE__) . '/' . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['uploaded_file']['name'];
// Validate the file type
$fileTypes = array('jpg'); // File extensions
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if (in_array($fileParts['extension'],$fileTypes))
{
$uploadfile = $targetFolder. basename($filename2 .".".$fileParts['extension']);
move_uploaded_file($tempFile,$uploadfile);
$fileName = $uploadfile;
}
echo "<div id='filename'>$fileName</div>";
}
Maybe changing your php server's configuration would help (example for 10MB):
ini_set('upload_max_filesize', '10M');
make sure your php.ini configuration support large files. upload_max_filesize and post_max_size also you can change the configuration temporary using ini_set before you handle the upload process.
try this may be it would work put it in your code and then try
define ("MAX_SIZE","1000"); // put your max size value
$size=filesize($_FILES['uploaded_file']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
or else you have to edit in php.ini found in document root/php/php.ini
You can change your server setting. Look for the php.ini file and search "upload_max_filesize"

How to upload images to a new unique folder every session php

I'm in the process of making a website for my dad that allows people to upload their own personal images because he is a window cleaning tech. He wants to allow people to be able to upload their images so he can give them an estimate on the cost. Below, I have two bits of code. The first bit successfully uploads images. That I won't have to worry about. The second bit, however, does not successfully upload images. What I want to accomplish is that every time a user uploads a set of images (maximum of 5), it will make a new folder in a directory that sets the current time as the name of the folder, that way it will be easier for him to keep track of who sends what. I'm still working out little details on how he can identify a person solely based on images (perhaps a person will call after sending the images in and verify the time of submission?). I am trying to do this with as little use for a database as possible, being I don't know how to use MySQL and tie it to PHP.
This is the code that works and successfully uploads the images to /upload:
<?php
$uploadpath = 'upload/';
$max_size = 4000;
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png');
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1){
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext);
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);
$err = '';
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> does not have an allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Your file exceeds the '. $max_size. ' KB. size limit.';
if($err == ''){
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)){
echo 'File: <b>'. basename( $_FILES['fileup']['name']). '</b> successfully uploaded:';
echo '<br/>File type: <b>'. $_FILES['fileup']['type'] .'</b>';
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
Upload File: <input type="file" name="fileup" /><br/>
Upload File: <input type="file" name="fileup" /><br/>
Upload File: <input type="file" name="fileup" /><br/>
Upload File: <input type="file" name="fileup" /><br/>
Upload File: <input type="file" name="fileup" /><br/>
<input type="submit" name='submit' value="Upload" />
</form>
And here's the code I'm trying to change to make a new folder with the timestamp as the name:
<?php
$uploadpath = 'upload/';
$max_size = 4000;
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png');
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1){
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext);
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);
$err = '';
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> does not have an allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Your file exceeds the '. $max_size. ' KB. size limit.';
if($err == ''){
$uploadpath = "upload/" . time();
$count = 0;
foreach ($_FILES['fileup']['name'] as $filename){
$temp = $_FILES['fileup']['tmp_name'][$count];
move_uploaded_file($temp, $uploadpath . '/' . $filename);
$count++;
}
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)){
echo 'File: <b>'. basename( $_FILES['fileup']['name']). '</b> successfully uploaded:';
echo '<br/>File type: <b>'. $_FILES['fileup']['type'] .'</b>';
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
Upload File: <input type="file" name="fileup" /><br/>
Upload File: <input type="file" name="fileup" /><br/>
Upload File: <input type="file" name="fileup" /><br/>
Upload File: <input type="file" name="fileup" /><br/>
Upload File: <input type="file" name="fileup" /><br/>
<input type="submit" name='submit' value="Upload" />
</form>
the main difference between the two is after the if($err == ''), the second bit of code has one more block here to replace the original "move file" command
I just did something similar for my uncle's company. To solve your issue of not knowing a good way to have the person submit there info you can create a form that takes info and then sends an email to your dad's work email. Here's an example of the php mail function.
$to = 'service#anywhere.com';
$subject = 'New Service Request:';
$time = date('l jS \of F Y h:i:s A');
$body = "New Service Request Submited - $time (time is coming from webserver)\nFirst Name: ".$_POST['fname']."
Last Name:\n ".$_POST['lname']."
Title:\n ".$_POST['title']."
Business:\n ".$_POST['business']."
Phone:\n ".$_POST['phone']."
Email:\n ".$_POST['email']."
Address:\n ".$_POST['address']."
Preferred Method of Contact:\n ".$method."
Equipment Type:\n ".$_POST['type']."
Equipment Issue:\n ".$_POST['issue']."
Additional Comments:\n ".$_POST['comments'];
$headers = 'From: Request Generator <noreply#anything.com>';
mail($to, $subject, $body, $headers);
Email address can be anything you want. Only requirement is that you have a mail server running where your website is (pretty much all hosting companies provide an email server in addition to the webserver). in the header section, you will notice the text in front of . That text shows up as the name of the 'person' who sent the email and the text between the <> is the 'address' it comes from which again doesn't have to be real.
In my body I left the text that generates tickets for my uncle to provide an example of what you may or may not want your tickets to look like.
For your upload error at first glance it looked like you never created the dynamic folder the content is being uploaded into. Try:
mkdir($uploadpath);
before you create or move any files in the directory.

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