Filesize Error Message - php

I wonder whether someone could please help me.
I'm trying to incorporate an 'filesize' error message into a script, shown below, which is used to upload BLOB files to a mySQL server.
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = 'No title provided';// use (empty title) string
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if($_FILES["fileupload"]["size"]/1024000 >= 10)
{
$fileErrMsg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed Size.<br />";
}
if (isset($_FILES['photo']))
{
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title: ',
data='$data'");
$msg = 'Success: Image Uploaded';
}
}
elseif (isset($_GET['title'])) // isset(..title) needed
$msg = 'Error: file not loaded';// to make sure we've using
// upload form, not form
// for deletion
if (isset($_POST['del'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'Image deleted';
}
if (isset($_POST['view'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['view']);
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid");
if(mysql_num_rows($result) == 1)
{
$image = $row['myimage'];
header("Content-type: image/gif"); // or whatever
print $image;
exit;
}
}
}
else
{
$imageid = intval($_POST['del']);
if ($_POST["action"] == "view")
{
$result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
FROM {$table}
WHERE imageid=$imageid LIMIT 1");
if (mysql_num_rows($result) == 0)
die('no image');
list($ext, $imagetime, $data) = mysql_fetch_row($result);
$send_304 = false;
if (php_sapi_name() == 'apache') {
// if our web server is apache
// we get check HTTP
// If-Modified-Since header
// and do not send image
// if there is a cached version
$ar = apache_request_headers();
if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
($ar['If-Modified-Since'] != '') && // not empty
(strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
$send_304 = true; // imagetime
}
if ($send_304)
{
// Sending 304 response to browser
// "Browser, your cached version of image is OK
// we're not sending anything new to you"
header('Last-Modified: '.gmdate('D, d M Y', $ts).' GMT', true, 304);
exit(); // bye-bye
}
// outputing HTTP headers
header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
// outputing image
echo $data;
exit();
}
else if ($_POST["action"] == "delete")
{
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'Image deleted';
}
}
}
?>
Through some guidance I received on this site I've been able to come up with the way to check the filesize, which starts at this line:
if($_FILES["fileupload"]["size"]/1024000 >= 10)
but I cannot get the error message to work.
The specific message needs to be activated if the file size is over 1MB. When I try to upload a file greater than this, the file is correctly rejected, but I receive the incorrect error message, 'Error: unknown file format'.
I've tried all number of ways to try to get this to work, but I just get the same incorrect error message.
I would be so grateful if someone could take a look at this and let me know where I'm going wrong.
Many thanks
SOLUTION
if (isset($_FILES['photo']))
{
list($width, $height, $imtype, $attr) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
if ($imtype == 3)
$ext="png"; //
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if($_FILES["photo"]["size"]/102400 >= 1) {
$msg = "he file you wish to upload is:<strong>[ ". $_FILES["photo"]["size"]/1024000 . " MB]</strong> is more than allowed Size.";
}

I'm new to php but i searched for that and found this in manual
http://php.net/manual/en/function.set-error-handler.php
I posted as an answer because i cant comment. i hope it helps.

Looks like all of your other error messages go into a variable called $msg. I updated your calculation to be a bit easier:
if($_FILES["fileupload"]["size"]/102400 >= 1)
{
$msg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed Size.<br />";
}

Related

PHP / MySQL: Failed to save image to folder at server but link URL is updated MySQL database

I currently created a system that allowed a user to upload a photo only. The photo the already upload can be replaced if the user want to change it.
The current code shows that there's no error in this function. The URL updated at MySQL database. But the problem is the image doesn't update. Below is my current code:
update_photo_before.php
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
if ($sql){
move_uploaded_file($_FILES['uploadFile']['name'], $imgPath); //line 28
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}else{
echo "Error!! Not Saved";
}
} else {
echo "<script>alert('File not allowed')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
?>
My folder images are located at 'tgotworker_testing' --> 'android' --> 'images'.
For update_photo_before.php:
'tgotworker_testing' --> 'pages' --> 'dashboard' --> 'engineer' --> 'view_task' --> 'update_photo_before.php'
Can anyone fix my problem? Thanks!
You check to see if the database gets updated, but not if the image is saved to the server.
move_uploaded_file() returns true on success and false on failure. So you can do a similar test as you have for $sql in your code.
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
// Check if image is uploaded to folder
if(move_uploaded_file($_FILES['uploadFile']['name'], $imgPath) === true) {
// If upload succeeds, then update database
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Check if database updated
if (!$sql){
echo "Error!! Database not updated.";
} else {
// Success!
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
} else {
// Could not upload file
echo "Error!! Could not upload file to server.";
}
}
When PHP can't upload the file it will throw a warning. If you turn on your warnings while you are debugging, it should give you the reason why it's not working and you will be better able to solve the problem.
Put these lines at the top of the script to show all warnings and errors:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Restricting uploads to PDFs and MS Word files

I'm making a file uploader using PHP and want to restrict it to PDFs and Microsoft Word files. However, it's currently allowing uploads from all file types to the database. How can I restrict it to only allowing PDFs and Microsoft Word files?
Here is my code:
<?php
# Check if a file has been uploaded
if (isset($_FILES['uploaded_file']))
# Make sure the file was sent without errors
if ($_FILES['uploaded_file']['error'] == 0) {
# Connect to the database
$dbLink = mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("webproject", $dbLink) or die(mysql_error());
/* if(mysql_connect()) {
die("MySQL connection failed: ". mysql_error());
} */
# Gather all required data
$filename = mysql_real_escape_string($_FILES['uploaded_file']['name']);
$filemime = mysql_real_escape_string($_FILES['uploaded_file']['type'] == "application/pdf" || $_FILES["uploaded_file"]["type"] == "application/msword");
$size = $_FILES['uploaded_file']['size'];
$data = mysql_real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$subjects = $_POST['subjects'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
# Create the SQL query
$query = "
INSERT INTO file(
Filename, Filemime, Filesize, Filedata, subjects, name, email, phone, Created
)
VALUES (
'{$filename}', '{$filemime}', {$size}, '{$data}', '{$subjects}','{$name}','{$email}','{$phone}', NOW()
)";
# Execute the query
$result = mysql_query($query, $dbLink);
# Check if it was successfull
if ($result) {
echo "Success! Your file was successfully added!";
} else {
echo "Error! Failed to insert the file";
echo "<pre>" . mysql_error($dbLink) . "</pre>";
}
} else {
echo "Error!
An error accured while the file was being uploaded.
Error code: " . $_FILES['uploaded_file']['error'];
}
# Close the mysql connection
mysql_close($dbLink);
# Echo a link back to the mail page
echo "<p><a href='index.html'>Click here to go back home page!.</a></p>";
?>
I am not sure how your code actually works, but if you replace your second if at the top by this, the program will run only if the type is pdf or word, other files will cause this error: "Error! An error accured while the file was being uploaded. Error code: ". $_FILES['uploaded_file']['error'];" to occur
if($_FILES['uploaded_file']['error'] == 0 && ($_FILES['uploaded_file']['type']=='application/pdf' || $_FILES['uploaded_file']['type']=='application/msword' || $_FILES["uploaded_file"]["type"] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))
Your first if: if (isset($_FILES['uploaded_file'])) has no braces... that's not a very good practice.
Here is a extract from a function I sometimes use:
function CheckFile ($file){
$mimeTypes = array(
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/excel",
"application/vnd.ms-excel",
"application/x-excel",
"application/x-msexcel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
$fileExtensions = array("pdf", "doc", "docx", "xls", "xlsx");
if (in_array($file['type'], $mimeTypes) &&
in_array(end(explode(".", $file["name"])), $fileExtensions)) {
return true;
}
}
Call it with CheckFile($_FILES['uploaded_file']) It will return true if the doc is a pdf word or excel file
Edit:
One way to use it would be like so:
if (!CheckFile($_FILES['uploaded_file'])){
?>
<p>Sorry, your file was not of the correct type</p>
<?php
exit();
}

Set File Size Limit Message

I wonder whether someone could help me please.
I have to admit I'm relatively new to writing PHP so please bear with me.
Through articles I've read on the internet and some first class tutition from one #Marcio on this site, I've put together a script that allows users to save Image Files to a mySQL database.
I've now gone a little further by restricting the size of the file that can be uploaded, but I I'd like to add a warning message that tells why the file cannot be uploaded i.e. because it's size is greater than the limit set.
I've made an attempt at this, as seen in the code below. But unfortunately I receive an error message stating that there is an unexpected '>' which I know relates to the line I've added, but not sure how to code this another way.
Revised Cut Down Code
<?php
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = '(No title provided';// use (empty title) string
if (isset($_FILES['photo']))
{
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if($_FILES["fileupload"]["size"]/1024000 >= 10) // 10mb
{
$fileErrMsg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed 10MB Size.<br />";
}
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
$msg = 'Success: Image Uploaded';
}
}
I just wondered whether someone could perhaps take a look at this and let me know what I'm doing wrong.
Many thanks and kind regards
You can use this
if($_FILES["fileupload"]["size"]/1024000 >= 10) // 10mb
{
$fileErrMsg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed 10MB Size.<br />";
}
getfilesize() returns image dimensions in pixels, not file size. You need something along the lines of this:
if (filesize($_FILES['tmp_name']) >= 100000)

PHP Error only present in Internet Explorer

Okay this has baffled me. My script works in Mozilla but not IE. I get this error in IE:
Warning: move_uploaded_file(uploads/properties/yh96gapdna8amyhhmgcniskcvk9p0u37/) [function.move-uploaded-file]: failed to open stream: Is a directory in /homepages/19/d375499187/htdocs/sitename/include/session.php on line 602
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpJkiaF3' to 'uploads/properties/yh96gapdna8amyhhmgcniskcvk9p0u37/' in /homepages/19/d375499187/htdocs/sitename/include/session.php on line 602
my code at Session.php is:
function addPhoto($subphotoSize,$subphotoType,$subphotoTmpname,$subphotoDesc,$subfieldID,$subsessionid){
global $database, $form;
/* Get random string for directory name */
$randNum = $this->generateRandStr(10);
$maxFileSize = 2500000; // bytes (2 MB)
$filerootpath = PHOTOS_DIR.$subsessionid."/";
if($subphotoType == "image/png"){
$filename = $randNum.".png";
} else if ($subphotoType == "image/jpeg"){
$filename = $randNum.".jpg";
}
$fullURL = $filerootpath.$filename;
/* Image error checking */
$field = "photo";
if(!$subphotoTmpname){
$form->setError($field, "* No file selected");
} else {
if($subphotoSize > $maxFileSize) {
$form->setError($field, "* Your photo is above the maximum of ".$maxFileSize."Kb");
} else if (!is_dir($filerootpath)){
mkdir($filerootpath,0777);
chmod($filerootpath,0777);
}
move_uploaded_file($subphotoTmpname, "$fullURL");
}
/* Errors exist, have user correct them */
if($form->num_errors > 0){
return 1; //Errors with form
} else {
if($subfieldID == "1"){ // If the first field...
$is_main_photo = 1;
} else {
$is_main_photo = 0;
}
if(!$database->addNewPhoto($ownerID,$subphotoDesc,$fullURL,$userSession,$is_main_photo, $subsessionid)){
return 2; // Failed to add to database
}
}
return 0; // Success
}
It creates the folder no problem but doesnt do anything else.
Add a log message to see what's the value of $subphotoType. My guess is that when you upload the file from Internet Explorer it's neither image/png nor image/jpeg, in which case $filename will be empty because you don't have an else clause.
if($subphotoType == "image/png"){
$filename = $randNum.".png";
} else if ($subphotoType == "image/jpeg"){
$filename = $randNum.".jpg";
} else {
// No else! $filename will be empty.
}
If you tune your error reporting settings properly you should see a notice saying you are trying to use an undefined variable.

swfupload destroy session? php

hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here

Categories