Set File Size Limit Message - php

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)

Related

Not updating a field if no image is inserted

I am quite new to PHP, but i'm having a problem with my thought process around some code i am writing.
I am trying to get the below to work so that a user can upload two images in a form, which uploads to the server, and updates the field in SQL, but i'm having a hard time working out how to make it so that the SQL field isn't updated unless an image is uploaded - I've managed to make it work with one image using;
$uploadArtwork = $_FILES['asset_name']['tmp_name'];
if($uploadArtwork == null) {
$sql = "";
}
else {
$sql = "";
}
I am struggling to work out, how i can do it for two images (and eventually more than two images?)
Tried a lot of googling, but without much luck yet!
$uploadArtwork1 = $_FILES['asset_name1']['tmp_name'];
$uploadArtwork2 = $_FILES['asset_name2']['tmp_name'];
// Image1 and/or image2 was uploaded successfully
if(($uploadArtwork1 != null) || ($uploadArtwork2 != null)) {
$sql = "";
// No images were selected, or there were problems uploading them
} else {
$sql = "";
}
Though it would be better to check $_FILES['asset_name']['error'] == UPLOAD_ERR_OK to determine if an image was uploaded successfully:
$uploadArtwork1 = $_FILES['asset_name1']['error'];
$uploadArtwork2 = $_FILES['asset_name2']['error'];
// Image1 and/or image2 was uploaded successfully
if(($uploadArtwork1 == UPLOAD_ERR_OK) || ($uploadArtwork2 == UPLOAD_ERR_OK)) {
// Do something with $_FILES['asset_name1']['tmp_name'] and $_FILES['asset_name2']['tmp_name']
$sql = "";
// No images were selected, or there were problems uploading them
} else {
$sql = "";
}
Update:
require_once("Inc/classCloud.php");
$sql = "UPDATE assets SET asset_title='$post_asset_title'";
if ($uploadArtwork != null) {
$getImageID= $res['data'];
$sql .= ", asset_name='$getImageID'";
}
if ($uploadMock != null) {
$getImageID2= $res2['data'];
$sql .= ", product_artwork='$getImageID2'";
}
$sql .= " WHERE asset_id='$post_asset_id'";
Here is a basic structure to work with.
Basically looping through all uploaded files and if they have been found then move them to a new location on the server and write the entry to database.
This code has not been tested.
<?php
// Loops through all possible file uploads.
foreach ($_FILES as $file) {
// Checks a file has been chosen.
if (isset($file['tmp_name']) && !empty($file['tmp_name'])) {
// Checks the uploaded (object) is a file.
if (is_file($file['tmp_name'])) {
// The filepath for the uploaded file.
$destination = 'LOCATION TO MOVE THE UPLOADED FILE TO';
/*
* Perform SQL Write here
*/
if (WRITE WAS SUCCESSFUL) {
// Move FIle
move_uploaded_file($file['tmp_name'], $destination);
}
}
}
}

Krajee file input invalid json response

I tried to integrate krajee file-input into my existing form. DEMO SITE
When i browse a file from my computer and click upload button (built-in with the plugin), i got this error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
The author of this plugin told me that i have to write valid json response in my php file for this to work but he did not have time to help individual case like mine. So I read the documentation from the website, it has this part:(you can find it on the demo site above)
Sending Data (from server)
Your server method as set in uploadUrl must send data back as a json encoded object. The only key you must send is the error which will be the error message for the upload and will help the plugin to identify error in the file upload. For example the response from server would be sent as {error: 'You are not allowed to upload such a file.'}. Note: The plugin will automatically validate and display ajax exception errors.
IMPORTANT
You MUST send a valid JSON response from your server, else the upload process will fail. Even if you do not encounter any error, you must at least send an empty JSON object {} from your server.
To trap and display a validation error, your JSON response data must include the error key, whose value will be the error HTML markup to display. This is to be setup as mentioned above.
Unfortunately, I can't understand it because I am just a new php learner and this is out of my scope. But I have my php file here, hope some expert can help me to add the json response to it as the documentaion explained above. Thank you very much in advance!
Here is my php file:
<?php
if(isset($_POST["submit"])){
require("../configs/dbconnect.php");
/*Form variable */
$owner = mysql_real_escape_string($_POST["owner"]);
$title = mysql_real_escape_string($_POST["title"]);
$description = mysql_real_escape_string($_POST["description"]);
$city = mysql_real_escape_string($_POST["city"]);
$brand = mysql_real_escape_string($_POST["brand"]);
$marketprice = mysql_real_escape_string($_POST["marketprice"]);
$price = mysql_real_escape_string($_POST["price"]);
$phone = mysql_real_escape_string($_POST["phone"]);
/*** the upload directory ***/
$upload_dir= 'uploads';
/*** numver of files to upload ***/
$num_uploads = 5;
/*** maximum filesize allowed in bytes ***/
$max_file_size = 5000000;
/*** the maximum filesize from php.ini ***/
$ini_max = str_replace('M', '', ini_get('upload_max_filesize'));
$upload_max = $ini_max * 1024;
/*** a message for users ***/
$msg = 'Please select files for uploading';
/*** an array to hold messages ***/
$messages = array();
$err=array();
/*** check if a file has been submitted ***/
if(isset($_FILES['file']['tmp_name']))
{
/** loop through the array of files ***/
for($i=0; $i < count($_FILES['file']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
/*** check if the file is less then the max php.ini size ***/
//elseif($_FILES['image']['size'][$i] > $upload_max)
//{
// $messages[] = "File size exceeds $upload_max php.ini limit";
//}
// check the file is less than the maximum file size
elseif($_FILES['file']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
//$temp = explode(".", $_FILES["file"]["name"][$i]);
//$extension = end($temp);
//$name[$i] = sha1(microtime()) . "." . $extension;
$name[$i]=$_FILES["file"]["name"][$i];
// copy the file to the specified dir
if(move_uploaded_file($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$name[$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $name[$i].' uploaded';
$image_path[$i]=$upload_dir.'/'.$name[$i];
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$name[$i].' Failed';
}
}
}
}
$image_path_string=serialize($image_path);
$sql = "INSERT INTO memberpost(owner, title, description, city, brand, marketprice, price, phone, image) VALUES ('$owner', '$title','$description','$city','$brand','$marketprice','$price','$phone', '" . $image_path_string . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
if(sizeof($messages) != 0)
{
foreach($messages as $err)
{
echo $err.'<br />';
}
}
}
?>
Your echo i think...
Put your error on any variable then echo json_encode(variable name). That's how to send JSON object.

php script for upload image not working

i have a edit page that allow users to upload a profile image using forms
but the problem is that i keep getting the the format is not acceptable even if the image type is one of the accepted format.
this is the code
if(isset($_POST['parse_var']) == "pic")
{
if(!$_FILES['fileField']['tmp_name'])
{
$errorMSG = '<font color= "#FF0000">Please browse for an Image Before you press the button.</font>';
}
else
{
$maxfilesize = 51200;//in bytes = 50kb
if($_FILES['fileField']['size']>$maxfilesize)
{
$errorMSG = '<font color="#FF0000">Your image was too large, please try again.</font>';
unlink($_FILES['fileField']['tmp_name']);
}
elseif(!preg_match("^.(gif|jpg|png)$/i^",$_FILES['fileField']['name']))
{
$errorMSG = '<font color="#FF0000">Your Image was not one of the accepted format, please try again</font>';
unlink($_FILES['fileField']['tmp_name']);
}
else
{
$newname = "image01.jpg";
$place_file = move_uploaded_file($_FILES['fileField']['tmp_name'],"members/$id/".$newname);
$message='<font color="#00FF00>Your Image has been upload successfully</font>';
}
}//end else
}//end if
Major problems:
a)
elseif(!preg_match("^.(gif|jpg|png)$/i^",$_FILES['fileField']['name']))
^---
you should not be using a regex metachar as the pattern delimiter. Try
preg_match('/\.(gif|jpg|png)$/i', ...) instead.
But in a bigger picture view, you shouldn't be matching on filenames at all. Filenames can be forged. You should be doing server-side MIME-type determination (e.g. via file_info()) instead.
b)
you are NOT properly checking for upload success. The presence of a ['tmp_name'] in the $_FILES array means NOTHING. failed uploads can STILL produce a tmp_name, yet you end up with garbage. Always use something like this:
if ($_FILES['fileField']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileField']['error']);
}
the error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
c) (minor)
you do no need to unlink the temp files. PHP does that automatically when the script exits.
d) (stylistically HUGE error)
font tags? in 2013? The 1990s called and want their HTML 1.0 back...

How can i get variable out of a class?

I am trying to get variable out of a class but seems that I am not doing it correctly.
Here is code for upload_inc.php
class upload
{
var $directory_name;
var $max_filesize;
var $error;
var $user_tmp_name;
var $user_file_name;
var $user_file_size;
var $user_file_type;
var $user_full_name;
function set_directory($dir_name =".")
{
$this->directory_name = $dir_name;
}
function set_max_size($max_file = 2000000)
{
$this->max_filesize = $max_file;
}
function error()
{
return $this->error;
}
function is_ok()
{
if(isset($this->error))
return FALSE;
else
return TRUE;
}
function set_tmp_name($temp_name)
{
$this->user_tmp_name = $temp_name;
}
function set_file_size($file_size)
{
$this->user_file_size = $file_size;
}
function set_file_type($file_type)
{
$this->user_file_type = $file_type;
}
function set_file_name($file)
{
$this->user_file_name = $file;
$this->user_full_name = $this->directory_name."/".$this->user_file_name;
echo $this->user_full_name;
}
function start_copy()
{
if(!isset($this->user_file_name))
$this->error = "You must define filename!";
if ($this->user_file_size <= 0)
$this->error = "File size error (0): $this->user_file_size KB<br>";
if ($this->user_file_size > $this->max_filesize)
$this->error = "File size error (1): $this->user_file_size KB<br>";
if($this->user_file_type != "image/jpeg")
$this->error = "the image must be jpeg extension";
if (!isset($this->error))
{
$filename = basename($this->user_file_name);
if (!empty($this->directory_name))
$destination = $this->user_full_name;
else
$destination = $filename;
if(!is_uploaded_file($this->user_tmp_name))
$this->error = "File " . $this->user_tmp_name . " is not uploaded correctly.";
if (!move_uploaded_file ($this->user_tmp_name,$destination))
$this->error = "Impossible to copy " . $this->user_file_name. " from " . $userfile . "to destination directory.";
echo 'test file' . $userfile;
}
}
}
In the second page after uploading the file, I am trying to get only the file name. Then, I can store the file name in my database. Here is my code.
upload.php
// Defining Class
$uploaded = new upload;
// Set Max Size
$uploaded->set_max_size(350000);
// Set Directory
$uploaded->set_directory("data");
// Do not change
// Set Temp Name for upload, $_FILES['file']['tmp_name']
$uploaded->set_tmp_name($_FILES['file']['tmp_name']);
// Set file size,
$uploaded->set_file_size($_FILES['file']['size']);
// Set File Type,
$uploaded->set_file_type($_FILES['file']['type']);
// Set File Name,
$uploaded->set_file_name($_FILES['file']['name']);
// Start Copy Process
$uploaded->start_copy();
// Control File is uploaded or not
// If there is error write the error message
if($uploaded->is_ok()){
echo "successfully loaded <br />";
}else{
echo $uploaded->error()."<br>";
}this should show only file name but it does not.
Why do you expect the class to contain the filename in the member variable? Where are you assigning it to the member variable? All I see is that you are creating a new class (besides, it should be "new upload();", you missed the parentheses) whose member variables are not initalized. So you get a null value when doing the echo, which is the expected result.
What do you try to achieve? If you want the class-instance to "keep" its values across different request-response cycles you would have to store the whole instance somewhere (seralizing it) and restoring it when needed (unserializing it). You could also simply store the filename in the session if that is all you need.
I'm not sure what you're trying to achieve but as far as the error you're currently getting... You'll need to create a constructor for your Upload class that accepts a value for $user_file_name and then set it. Alternatively you can use set_file_name() before trying to use the $user_file_name var. As it stands right now that value is never being set, which is why you're getting an error on your call to echo.
Also, as others have said, you should really go back and accept answers to your questions if you found them helpful.
Main thing which you need is good IDE, with smart code highlighting :)
I recommend PhpStorm (not ideal, but best at this moment, I hope somebody will create something better).
In your code $userfile are not defined. You can define this variable:
$userfile = $this->user_tmp_name;
in function start_copy().

How to test if a user has SELECTED a file to upload?

on a page, i have :
if (!empty($_FILES['logo']['name'])) {
$dossier = 'upload/';
$fichier = basename($_FILES['logo']['name']);
$taille_maxi = 100000;
$taille = filesize($_FILES['logo']['tmp_name']);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['logo']['name'], '.');
if(!in_array($extension, $extensions)) {
$erreur = 'ERROR you must upload the right type';
}
if($taille>$taille_maxi) {
$erreur = 'too heavy';
}
if(!empty($erreur)) {
// ...
}
}
The problem is, if the users wants to edit information WITHOUT uploading a LOGO, it raises an error : 'error you must upload the right type'
So, if a user didn't put anything in the inputbox in order to upload it, i don't want to enter in these conditions test.
i tested :
if (!empty($_FILES['logo']['name']) and if (isset($_FILES['logo']['name'])
but both doesn't seems to work.
Any ideas?
edit : maybe i wasn't so clear, i don't want to test if he uploaded a logo, i want to test IF he selected a file to upload, because right now, if he doesn't select a file to upload, php raises an error telling he must upload with the right format.
thanks.
You can check this with:
if (empty($_FILES['logo']['name'])) {
// No file was selected for upload, your (re)action goes here
}
Or you can use a javascript construction that only enables the upload/submit button whenever the upload field has a value other then an empty string ("") to avoid submission of the form with no upload at all.
There is a section in php documentation about file handling. You will find that you can check various errors and one of them is
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
In your case you need code like
if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }
or
if ($_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { ... }
You should consider checking (and probably providing appropriate response for a user) for other various errors as well.
You should use is_uploaded_file($_FILES['logo']['tmp_name']) to make sure that the file was indeed uploaded through a POST.
I would test if (file_exists($_FILES['logo']['tmp_name'])) and see if it works.
Or, more approperately (thanks Baloo): if (is_uploaded_file($_FILES['logo']['tmp_name']))
We Could Use
For Single file:
if ($_FILES['logo']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
For Multiple files:
if ($_FILES['logo']['tmp_name'][0] == "") {
// No files were selected for upload, your (re)action goes here
}
if($_FILES["uploadfile"]["name"]=="") {}
this can be used
No file was selected for upload, your (re)action goes here in if body
echo "no file selected";
if ($_FILES['logo']['error'] === 0)
is the only right way

Categories