I have a simple file uploader, which thanks to stackoverflow is now fully working, however when I copied the PHP code across to my main layout, once initialised to upload a file, but it is wrong format or size and it echos the error, it breaks the HTML below it. Im thinking its to do with the "exit;" after each echo? but could be wrong.
<?php
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
exit;
}
#we have a filename, continue
#directory to upload to
$uploads = '/home/habbonow/public_html/other/quacked/photos';
$usruploads = 'photos';
#allowed file types
$type_array = array(image_type_to_mime_type(IMAGETYPE_JPEG), image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_PNG), 'image/pjpeg');
if(!in_array($_FILES['image']['type'], $type_array))
{
#the type of the file is not in the list we want to allow
echo "<br/><b>That file type is not allowed!\n</b>";
exit;
}
$max_filesize = 512000;
$max_filesize_kb = ($max_filesize / 1024);
if($_FILES['image']['size'] > $max_filesize)
{
#file is larger than the value of $max_filesize return an error
echo "<br/><b>Your file is too large, files may be up to ".$max_filesize_kb."kb\n</b>";
exit;
}
$imagesize = getimagesize($_FILES['image']['tmp_name']);
#get width
$imagewidth = $imagesize[0];
#get height
$imageheight = $imagesize[1];
#allowed dimensions
$maxwidth = 1024;
$maxheight = 1024;
if($imagewidth > $maxwidth || $imageheight > $maxheight)
{
#one or both of the image dimensions are larger than the allowed sizes return an error
echo "<br/><b>Your file is too large, files may be up to ".$maxwidth."px x ".$maxheight."px in size\n</b>";
exit;
}
move_uploaded_file($_FILES['image']['tmp_name'], $uploads.'/'.$_FILES['image']['name']) or die ("Couldn't upload ".$_FILES['image']['name']." \n");
echo "<br/>The URL to your photo is <b>" . $usruploads . "/" . $_FILES['image']['name'] . "</b>. Please use this when defining the gallery photos";
}
?>
<form name="uploader" method="post" action="" enctype="multipart/form-data">
<input type="file" name="image" style="width:300px;cursor:pointer" />
<input type="submit" name="upload" value="Upload Image" />
</form>
Indeed, when you call exit; it means "immediately stop all processing; this script is finished." Anything that comes after it — including HTML — will not be interpreted.
A better organization would be to make this code a function, to the effect of:
function uploadMyStuffPlease() {
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
return;
}
#we have a filename, continue
// ....
}
Now you can simply call uploadMyStuffPlease(), which will do as much processing as it can, and perhaps return early in the event of an error. Either way, the function will return, and so the rest of your script (including that HTML) can still be interpreted.
If you call exit; your PHP script won't be able to output anything anymore. That's why the layout is broken.
You should maybe try to keep the HTML parts out of your PHP code and especially avoid opening tags that you don't close afterwards (i.e. divs or anything).
That being said, it's probably safest to just put everything into a function that won't exit the script when finished (see other's posts).
if(isset($_POST['upload'])){
OR
if(!empty($_POST['upload'])){
And remove exit...
Related
i have a php form with an image upload option as follows
<input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
<label for="new_picture">Picture:</label>
<input type="file" id="new_picture" name="new_picture" />
and php script something like
if (!empty($new_picture)) {
if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = MM_UPLOADPATH . basename($new_picture);
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
// The new picture file move was successful, now make sure any old picture is deleted
if (!empty($old_picture) && ($old_picture != $new_picture)) {
#unlink(MM_UPLOADPATH . $old_picture);
}
}
else {
// The new picture file move failed, so delete the temporary file and set the error flag
#unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
}
}
}
else {
// The new picture file is not valid, so delete the temporary file and set the error flag
#unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
}
}
every thing works fine but problem occurs when as a test i tried to upload a .zip file the image was not loaded but it flushed my database. all the entries for that user were deleted.
now i want a some suggessions about how to prevent this
thanks in advance
On the client side, there is not much you can do that you can actually rely on. But it can help prevent accidental problems.
Add this attribute to the file upload control to limit file types: accept="image/gif, image/jpeg"
Your validation needs to happen on server side if you want to be sure about what you are getting.
Check $_FILES['uploadctl']['size'] for the size of the file and see if it exceeds your limits.
You can force php to limit what size file uploads it accepts by setting upload_max_filesize in php.ini. Default for this is pretty low.
You cant really trust that the extension of an uploaded file is actually correct. Just because it says .jpg doesn't mean it really is. If all you are accepting is images, you should be able to verify the mimetype with getimagesize(). If you are accepting a larger range of files, check the file with Fileinfo.
If the entries in the database were deleted, you probably have a logic problem in code that you are not showing here.
I am trying to upload things to a database. I went through a few tutorials and none of them worked. I want to upload files such as images and text documents (including PowerPoint presentations) to the database.
This is my form
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input name="picture" type="file" id="picture" size="50">
<input name="upload" type="submit" id="upload" value="Upload Picture!">
</form>
This is upload.php
<?php
// if something was posted, start the process...
if(isset($_POST['upload']))
{
// define the posted file into variables
$name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
$type = $_FILES['picture']['type'];
$size = $_FILES['picture']['size'];
// get the width & height of the file (we don't need the other stuff)
list($width, $height, $typeb, $attr) = getimagesize($tmp_name);
// if width is over 600 px or height is over 500 px, kill it
if($width>600 || $height>500)
{
echo $name . "'s dimensions exceed the 600x500 pixel limit.";
echo 'Click here to try again.';
die();
}
// if the mime type is anything other than what we specify below, kill it
if(!($type=='image/jpeg' || $type=='image/png' || $type=='image/gif'))
{
echo $type . " is not an acceptable format.";
echo 'Click here to try again.' ;
die();
}
// if the file size is larger than 350 KB, kill it
if($size>'350000') {
echo $name . " is over 350KB. Please make it smaller.";
echo 'Click here to try again.' ;
die();
}
// if your server has magic quotes turned off, add slashes manually
if(!get_magic_quotes_gpc()){
$name = addslashes($name);
}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, $size);
$content = addslashes($content);
fclose($extract);
// connect to the database
include "inc/db.inc.php";
// the query that will add this to the database
$addfile = "INSERT INTO files (name, size, type, content ) ".
"VALUES ('$name', '$size', '$type', '$content')";
mysql_query($addfile) or die(mysql_error());
// get the last inserted ID if we're going to display this image next
$inserted_fid = mysql_insert_id();
mysql_close();
echo "Successfully uploaded your picture!";
// we still have to close the original IF statement. If there was nothing posted, kill the page.
}
else{
die("No uploaded file present");
}
?>
I know there is restriction on type -> if(!($type=='image/jpeg' || $type=='image/png' || $type=='image/gif')) on this. When I upload small photos, the error I am getting is "No database selected".
The database is configured correctly as other things that I have are able to connect to it.
Your code is fundamentally broken:
1) You simply assume an upload was performed, and never check for failure. At minimum you should have
if ($_FILES['picture']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['picture']['error']);
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
2) addslashes() provides about as much defense against SQL injection attacks as using a single square of wet toiler paper does to drying up a lake. Since you're using the mysql library, you MUST use mysql_real_escape_string() to do a PROPER job of escaping the data
3) You're using the mysql library, which is obsolete and deprecated. STOP USING IT. Switch to mysqli or PDO instead.
4) Your actual error message indicates that you never did a mysql_select_db() call to set your default database. You could get around it by simply modifying your query to be INSERT INTO name_of_db.name_of_table ....
Make sure that you correctly called mysql_select_db() in your inc/db.inc.php file.
In the code below you are simply echoing the text without performing any check. The success message will be displayed irrespective of success or failure.
echo "Successfully uploaded your picture!";
I have been assigned the task of fixing an older php site since it has been moved to a newer server. The server it is on now doesn't allow globalized variables and that's pretty much all this site was running off of. When trying to upload an image, my sql statement is showing everything but the id for the listing I am adding the image to. I was hoping someone could help me figure this out.
This is my upload function:
function upload(){
global $imagefolder, $id;
global $tbl_units;
include "globalizePOSTGET.php";
// $uid = uuid();
$minsize = 5000; // 5kb
$maxsize = 3000000; // 3mb
$ext = explode('.',basename($_FILES['userfile']['name']));
$ext = $ext[count($ext)-1];
$ext = strtolower($ext);
if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
echo "<script> alert('Image is not a png or jpeg format'); </script>";
return false;
}
$imagename = $_POST['id']."_img".$_FILES['img'].".$ext";
$imagename2 = "X_".$imagename;
$uploadfile = $imagefolder . $imagename;
$uploadfile2 = $imagefolder . $imagename2;
$uploadthumb = $imagefolder . "tn_" . $imagename;
if (file_exists($uploadfile)) unlink($uploadfile);
if (file_exists($uploadthumb)) unlink($uploadthumb);
if (file_exists($uploadfile)) {
echo "<script> alert('Image already exists!'); </script>";
}
else
{
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
// check the file is less than the maximum file size
if($_FILES['userfile']['size'] < $maxsize) {
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name'])); // prepare the image for insertion
$size = getimagesize($_FILES['userfile']['tmp_name']); // get the image info..
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile2)) {
$Image = #imagecreatefromjpeg($uploadfile2);
if ($Image) {
$img_height = imagesy($Image);
$img_width = imagesx($Image);
imagedestroy($Image);
}
if ($img_height > $img_width) { // portrait
$tempMultiplier = 150 / $img_height;
$tempMultiplierFull = 600 / $img_height;
} else {
$tempMultiplier = 150 / $img_width;
$tempMultiplierFull = 600 / $img_width;
}
$imageHeight = $img_height * $tempMultiplier;
$imageWidth = $img_width * $tempMultiplier;
$fullimageHeight = $img_height * $tempMultiplierFull;
$fullimageWidth = $img_width * $tempMultiplierFull;
createthumb($imagename2,"tn_".$imagename,$imageWidth,$imageHeight);
if($_FILES['userfile']['size'] > $minsize) {
createthumb($imagename2,$imagename,$fullimageWidth,$fullimageHeight);
if (file_exists($uploadfile2)) unlink($uploadfile2);
} else {
rename($uploadfile2, $uploadfile);
}
$sql = "UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
echo $sql;
if(!mysql_query($sql)) {
echo "<script> alert('Unable to upload file'); </script>";
} else {
?> <script>location.replace('memonly.php?action=edit_record&id=<?php echo $id; ?>');</script> <?php
}
}
} else {
// if the file is not less than the maximum allowed, print an error
$file_n = basename($_FILES['userfile']['name']);
$file_s = $_FILES['userfile']['size'];
?>
<script> alert("File exceeds the maximum limit of <?php echo $maxsize; ?>\nFile <?php echo $file_n; ?> is <?php echo $file_s; ?>");</script>
<?php
}
}
}
}
I am echoing the sql statement on the line that is giving me the error, I think. After clicking on submit, the page tells me Unable to upload file'. Which is why I echoed the sql there. I end up with a sql statement looking like this:UPDATE member_units SET photo = "_img.jpg" WHERE id = `
Someone please help me! I am very inexperienced in PHP and I have no idea what to do here.
Here is the form that is doing the uploading:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="hidden" name="_submit_check" value="1" />
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" name="img" value="<?php echo $img; ?>" />
Image URL: <input type="file" name="userfile" value="" style="font-size: 10px; width: 100%;">
<input type="submit" value="Submit" onClick="return validate();">
<input type="button" value="Cancel" onClick="location.href='/memonly.php?action=edit_record<?php echo "&id=$id&memberid=$memberid"; ?>';">
</form>
The first thing you need to do with this kind of problem is work through where the issues seem to be happening. So take your echoed statement...
UPDATE member_units SET photo = "_img.jpg" WHERE id = `
This corresponds to...
UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
We can see by comparison that it is clear that $_FILES['img'] is and empty variable as far as converting it to a string goes. The same is said for $_POST['id'], while $imagename gives a short _img.jpg file name.
Tracking back you can then see that $imagename comes from...
$_POST['id']."_img".$_FILES['img'].".$ext";
This is where your photo = "_img.jpg" comes from. Again, $_FILES['img'] and $_POST['id']
The fact that you're reaching the echo statement means that something is uploading, but it is through the $_FILES['userfile'] array, with all of it's associated variables, for example $_FILES['userfile']['name'] which would give you the filename of the image being uploaded.
What you need to ask yourself next is where you are expecting $_POST['id'] to come from, since it is missing or empty, and what field in your HTML form delivers that variable. Then you need to ask yourself what you are trying to achieve with your naming system. For example if you want an image file to look like: 1_imgLolCat.jpg then your variable will need to look more like
$imagename = $_POST['id']."_img".$_FILES['userfile']['name'];
However the final part of my answer below makes me think that instead of the file name, what you're looking for is actually a POST variable that denotes a category or type of image, in which case you may want to work from...
$imagename = $_POST['id']."_img".$_POST['img'].".$ext";
...if a HTML field exists with the name "img"!
Finally take a look at your SQL statement...
SET photo".$_FILES['img']." = \"" . $imagename . "\"
And double check your tables, since what you appear to be trying to do is set a unique variable in your table that would depend on something passed from the form. I may be wrong here but I assume (as I said above) you want $_POST['img'] in there.
Word of warning, you need...NEED to sanitise these variables before you input them in to a SQL statement like this. Someone could easily take
SET photo".$_POST['img']
and delete your whole table if permissions were set up for your database use to do so. There are plenty of other answers around as to how to do this properly. :)
It seems like 'id' field is not sent in the HTML form. I guess it should be a hidden input ?
Be careful, your script can be the target of an SQL injection : you use a user input ($_POST['id']) directly in an SQL query. You should check if this input is actually set and numeric.
im using this php video upload script. i have set my directory path to a folder called video which i have created with the same directory as the php file. But i can not find the video being uploaded.
It is not going to the directory i have asked it to? Why is this can someone please help me.
I am not receiving any errors.
Thanks.
HTML:
<form action="upload_videos_process.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploadFile" id="uploadFile" />
<br />
<input type="submit" name="submit" value="Upload File" />
</form>
php file:
<?php
//This handles the maximum size for the video file in kbs
define ("MAX_SIZE","500");
//This function reads the extension of the file to ensure that it is an video file
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable handles an error and won't upload the file if there is a problem with it
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$video=$_FILES['video']['name'];
//if it is not empty
if ($video)
{
//get the original name of the file from the clients machine
$video_filename = stripslashes($_FILES['video']['name']);
$video_extension = getExtension($filename);
$video_extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file, otherwise we will do more tests
if (($video_extension != "mpeg") && ($video_extension != "avi") && ($video_extension != "flv") && ($video_extension != "mov"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the video
$size=filesize($_FILES['video']['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;
}
//give the video a unique name in case a video already exists with the name on the server
$video_name=time().'.'.$extension;
//assign a folder to save the video to on your server
$newname="video/".$video_name;
//verify that the video has been loaded
$copied = copy($_FILES['video']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessful!</h1>';
$errors=1;
}}}}
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>
You've blindly assumed everything's working perfectly. Things fail. First step: check if the upload actually did anything:
if ($_FILES['video']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['video']['error']);
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
As well, don't use copy() on the upload file, once you've verified the upload succeeded. There's move_uploaded_file() for a reason - it has extra security checks to ensure that the file hasn't been tampered with on the server, and it actually MOVES the file. copy() can kill performance, especially on large files, since you're duplicating the file, instead of just doing some filesystem housekeeping.
You're also trusting the user to not tamper with the filename. There is NOTHING to prevent a malicious user from doing ren nastyvirus.exe cutekittens.avi before uploading, and your script will happily accept that .exe, because its filename has simply been changed. Use server-side mime-detection (e.g http://www.php.net/manual/en/book.fileinfo.phpenter link description here) to get around this. NEVER trust ANYTHING from a user.
It might be because your php configuration does not allow to upload big files. Try setting
upload_max_filesize = 500M
or even larger than 500M in php.ini & also as ppl mention here in comments, enable the errors
ini_set('display_errors', 1);
ini_set('error_reporting', 8191);
am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];