Up until recently I've been using some PHP to upload photos to a site. But suddenly it's started triggering all sorts of error messages.
I use a form that on action runs the following code:
$uploaddir = "../../user_content/photo/";
$allowed_ext = array("jpeg", "jpg", "gif", "png");
if(isset($_POST["submit"])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
} else {
print "File not sent to server succesfully!";
exit;
}
The file upload part of the form has the following elements:
<input name="file" type="file" class="photo_file_upload">
The submit button for uploading has the following attributes:
<button type="submit" name="submit" class="photo_upload">Upload</button>
But whenever I run this, I always get the following warning:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in (upload PHP file) on line 10
(line 10 is this part: $info = getimagesize($file_temp);)
Anyone have any ideas on what the cause of this is?
You checked if the form was submitted, but didn't check if the file was sent. In some cases, a form could be submitted but the file will not sent (i.e. file size is bigger then file size limit in config).
Use this:
if(isset($_POST["submit"]) && isset($_FILES['file'])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
} else {
print "File not sent to server succesfully!";
exit;
}
You see && isset($_FILES['file']) is new
Or you can extend it
if(isset($_POST["submit"]) && isset($_FILES['file'])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
}
elseif(isset($_POST["submit"]) && !isset($_FILES['file'])) {
print "Form was submitted but file wasn't send";
exit;
}
else {
print "Form wasn't submitted!";
exit;
}
Change these parameters in your php.ini file; (Currently it allow only 2Mb size to
upload and post). Sometimes it's reason for these errors.
upload_max_filesize = 500M
post_max_size = 500M
max_execution_time = 120
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in
Verify the MAX_SIZE variable,
example to define it for a 2Mo image:
define('MAX_SIZE', 2000000);
<form enctype="multipart/form-data" method="post" action="upload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE; ?>" />
<input name="fichier" type="file" id="fichier_a_uploader" /> <br>
<input type="submit" name="submit" value="Uploader" />
</form>
you can also verify the Maximum size of POST data that PHP will accept and Maximum allowed size for uploaded files in PHP.ini :
post_max_size = ?
upload_max_filesize = ?
After you upgrade 'upload-max-filesize' , Restart all Services of wamp or xampp ! it will right !
you should change the form enctype to "multipart/form-data"
<form method="post" enctype="multipart/form-data">
....
</form>
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 38
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 43
Warning: getimagesize(): Filename cannot be empty in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 43
File is not an image.Sorry, file already exists.
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 58
Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.
If You Get Errors like this one you should check you have added form enctype to "multipart/form-data"
<form method="post" enctype="multipart/form-data">
....
</form>
Use to catch me out quite a lot to begin with.
Related
I have a an input type file which is hidden and triggered using another button .. the input must upload images only to a folder named Covers but the code is not working and not uploading any image..
html code
<div class="cover">
<img src="Layout/images/cover.jpg" alt="cover" name="cover-img" class="cover-img">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
<button type="submit" name="submit-cover" id="cover-btn">Change Cover</button>
<input type="file" name="avatar" id="cover-img-input" class="hidden" />
</form>
php codes:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['submit-cover'])) {
$avatarName = $_FILES['avatar']['name'];
$avatarTempName = $_FILES['avatar']['tmp_name'];
// List of allowed image extensions
$avatarAllowedExtensions = array("jpeg","jpg","png","gif");
// Get avatar extension
$avatarExtension = strtolower(end(explode('.',$avatarName)));
// Check if uploaded image extension is in allowed image extensions
$formErrors=array();
if(! empty($avatarName) && ! in_array($avatarExtension, $avatarAllowedExtensions)) {
$formErrors[]='This extension is <strong>not allowed</strong>';
}
if(empty($avatarName)) {
$formErrors[]='No image <strong>uploaded</strong>';
}
if(empty($formErrors)) {
// Create random number between zero to million to concatinate it with image name
$avatar = rand(0,1000000) . '_' . $avatarName;
// Move image into Covers folder
move_uploaded_file($avatarTempName, "Uploads\Covers\\" . $avatar);
}
}
}
I get
Fatal error: Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' in D:\XAMPP\htdocs\Warina\connect.php on line 7
after that I searched for a solution and get this: extension=php_pdo_mysql.dll should be uncommented in my php.ini and it is uncommented now I'm confused about this error too.
This line sends a notice:
$avatarExtension = strtolower(end(explode('.',$avatarName)));
Notice: Only variables should be passed by reference in file.php on line xx
Replace with
$avatarExtension = explode('.',$avatarName);
$avatarExtension = strtolower(end($avatarExtension));
Fix this path:
move_uploaded_file($avatarTempName, "Uploads\Covers\\" . $avatar);
With
move_uploaded_file($avatarTempName, "Uploads\\Covers\\" . $avatar);
And make sure it exists
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 years ago.
I tried to create an upload script in PHP. I getting this error message:
Notice: Undefined index: file in path\upload\index.php on line 3
This is my form (pretty basic):
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileUpload">
<input type="submit" value="Upload Image" name="submitt">
</form>
This is my (not working) upload script:
<?php
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
}
} else {
echo 'You should select a file to upload !!';
}
?>
This is my php.ini config:
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads=On
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize=40M
; Maximum number of files that can be uploaded via a single request
max_file_uploads=20
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size=50M
So what did I do wrong. I checked every previously asked question but didn't find an answer.
EDIT 1:
After checking out this and altering my code the problem still consists.
<?php
if (isset($_POST['submitt'])) {
if (isset($_FILES['file']) && isset($_FILES['file']['name']) && isset($_FILES['file']['tmp_name'])) {
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
} else {
echo 'You should select a file to upload !!';
}
}
}
?>
EDIT 2:
I found the problem: Replacing action upload with upload/index.php resolved the problem. I am using XAMPP on my local machine to test my code. This is an error due to an incorrect Apache config by XAMPP itself.
When user submit form and didn't pick file to upload your global variable (array) $_FILES won't have item file, hence you have this error, and you have to check if this key available, like this:
if (isset($_FILES['file']) && isset($_FILES['file']['name']) && isset($_FILES['file']['tmp_name'])) {
// Now you have strict and robust code!
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
// Rest of your code ...
}
In your 'upload' logic, you need to ensure that the form has been submitted before declaring the values. Otherwise, it's attempting to set variables with a value that does not yet exist;
<?php
//ensures the form was submitted before declaring variable values
if (isset($_POST['submitt']) {
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = '../data/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
}
} else {
echo 'You should select a file to upload !!';
}
}
?>
Secondly, Change your form code so that the 'action' is it self (in this case, we're leaving action="" as blank):
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileUpload">
<input type="submit" value="Upload Image" name="submitt">
</form>
I wanted to test out the file upload code. This is an upload file code and it has the option whether the user has the file to upload or just submit it blankly. I added the error message to limit the file extension. It works.
Then, I added an error message to notify the user about the limit file size. But somehow got the Warning: POST Content-Length of 681075903 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
instead of the error message of "Sorry, your file is too large. Only 3MB allowed" from the php code.
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
include("config.php");
if(isset($_POST['submit']) ){
//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$allowed = array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext, $allowed)){
if($filesize > 3000000) {
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
else{
echo "Sorry, your file is too large. Only 3MB allowed";
}
}
else{
echo "Sorry, only zip, rar, pdf, doc & docs files are allowed.";
}
//if user has no file to upload then proceed to this else statement
} else {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$query = "INSERT INTO contracts(`filename`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
$con->close();
}
?>
I don't get it. What did I do wrong in this code?
I think it is the if ($_FILES['upload']['size'] != 0 ){ part that gave the problem but I still want my user to have it optional to upload.
Its not a problem with your code. The http request isnt going through php because of the post max size setting.
Find this line in your php.ini of the server and change it:
; http://php.net/post-max-size
post_max_size = [max uploadsize like '32M' or '1G']
Can you post the form HTML code ?
The problem is, php has a directive (post_max_size) that limits the size of what he allows in POST - before any execution of your script. So, if this limit is reached, the warning is emitted before your script is called, and $_POST is not filled in.
It would deserves additional testing, but be sure :
to include MAX_FILE_SIZE hidden field in your form (see http://php.net/manual/en/features.file-upload.post-method.php).
to set post_max_size to something largely greater to what you want to accept
to set upload_max_filesize to (at first sight) the value you want.
In addition, it would also be intersting to try setting the maxlength attributes on the input, as this is is stated in the RFC-1867.
If the INPUT tag includes the attribute MAXLENGTH, the user agent should consider its value to represent the maximum Content-Length which the server will accept for transferred files.
In this way, servers can hint to the client how much space they have available for a file upload, before that upload takes place. It is important to note, however, that this is only a hint, and the actual requirements of the server may change between form creation and file submission.
This would allow to forbid the upload directly in the browser that respect the RFC.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Unable to do File Upload in PHP
I am trying to learn to write file upload script in PHP. I don't know why this doesn't work. Please have a look
<?php
$name=$_FILES["file"]["name"];
if(isset($name)) {
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
?>
It gives an error message Notice: Undefined index: file in
The html part is
<form action="submissions.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" /></form>
I am using wamp on Windows. What may be the cause for the error ?
You need to check if the form was submitted before executing your PHP code:
<?php
if (isset($_POST["submit"]) && $_POST["submit"] === "Submit") {
if (isset($_FILES["file"]["name"])) {
$name = $_FILES["file"]["name"];
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
}
?>
The clue is in the error message. The index 'file' doesn't exist in the FILES array. At a guess because you have this code before you've sumitted the form?
check if it exists first,
if(isset($_FILES['FormFieldNameForFile']) && $_FILES['FormFieldNameForFile']['size']>0){ # will be 0 if no file uploaded
then check your use of the field components.
$_FILES['userfile']['name'] # The original name of the file on the client machine.
$_FILES['userfile']['type'] # The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] # The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] # The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] # The error code associated with this file upload
Yes, I know that there are hundreds of questions similar, but I didn't find a working answer...
The problem is: I want upload multiple files...
The correct way should be this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="?u=1">
<input type="file" name="myFile[]" />
<input type="file" name="myFile[]" />
<input type="file" name="myFile[]" />
<input type="submit" value="Upload!" name="submit"/>
</form>
<?
if ($_GET['u']){
foreach ($_FILES["myFile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["myFile"]["tmp_name"][$key];
$name = $_FILES["myFile"]["name"][$key];
// here we move it to a directory called data
// you can move it wherever you want
move_uploaded_file($tmp_name, "/data/$name");
} else {
// an error occurred, handle it here
}
}
}
if (!$_FILES){
echo 'WTF?? No files sent?? There\'s a problem! Let\' hope that stack overflow will solve it!';
}
?>
</body>
</html>
The output is:
Notice: Undefined index: myFile in C:\xampp\htdocs\php\prova.php on line 18
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\php\prova.php on line 18
No files sent?? There's a problem! How can I access files uploaded from an array input tag?
I think using $_POSTOR $_FILES instead of $_GET['u'] to verify from submission, would fix the problem...
Also you can use <input type="file" name="myFile[]" multiple /> once instead of so many <input type="file"> for multiple file selection.
NOTE : Check php.ini for the following settings: (Edit as your needs , save & restart server)
file_uploads = On
upload_max_filesize = 2M (its 2 MB file limit by default !!! Exact error occurs as your's if file size > 2MB)
post_max_size = 8M (8 MB limit for post variable by default. Change as per your requirement...)
upload_tmp_dir = "c:/tmp" (Provide read/write permission to temporary opload directory )
This works ok in my wamp server with the above changes & settings... Good Luck !
Well, the easiest way to upload your files is to act as if you had only one, and repeat the process for every other file you have, all you have to do is give an name to your input. I would recommend using a multiple file input :
<input type="file" name="file[]" id="file" multiple>
Then, you can handle the upload with a simple for :
if(isset($_FILES['file']['tmp_name']))
{
//set upload directory
$target_dir = "uploads/";
$num_files = count($_FILES['file']['tmp_name']);
for($i=0; $i < $num_files;$i++)
{
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
else
{
if(#copy($_FILES['file']['tmp_name'][$i],$target_dir.'/'.$form['name']->getData()."/".$_FILES['file']['name'][$i]))
{
$messages[] = $_FILES['file']['name'][$i].' uploaded';
}
else
{
$messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
}
}
}
}
You can use either copy or move_uploaded_file to move the file to your directory.
I checked your code, and found that changing the line:
move_uploaded_file($tmp_name, "/data/$name"); to
move_uploaded_file($tmp_name, "data/$name");
[Changing absolute path to relative path]
does the trick. Now it works fine, in my local server. That should solve it for you.
Courtesy:http://forums.whirlpool.net.au/archive/788971