A way to test for a file upload - php

I'm writing a script to handle a file upload. I've got the script in place, validating and uploading correctly.
But....the upload is optional. When I submit the form, the $_FILES['field_name'] is always present which consequently forces my validation to kick in.
How can I detect if there is a file upload or not?

Take a look at is_uploaded_file.
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
}

You could use :
if (!empty($_FILES['file']['name'])) {
}
Which amounts to (almost) the same as the other answers on here.

I use:
if(isset($_FILES['file']) && $_FILES['file']['name'] != '') {
Where 'file' is the name of your file field.

if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
// Code goes here
}

Related

How to check for error file input before sending them through post

In the web page I have 2 tabs and 1 submit button. I first tab inputs with type=text. In second inputs with type=file. I wanna to send both tabs with 1 submit. But problem isn't here. In the second tab I need to check files for error before sending them. So If it has an error then submit button isn't active. How can I do this?
Now I check them for error only after sending them. And when some of the files have an error then upload fails and its return to page with an error. And all other files which haven't error disappear from the input .
First tab http://prntscr.com/mnzc79 . Second tab http://prntscr.com/mnzca3 .
Here all inputs are the document of the student in university. So I can use just multi upload. Because all of them are a different files. I can't understand the mechanism of uploading many file inputs with error check.
Here my code
Check if text inputs uploaded. If files were set then I push them to the array to use in query.
if(!empty($_POST["first_name"])){
$keys=$keys."first_name,";
$first_name=$_POST["first_name"];
$values=$values."'".$_POST['first_name']."',";
}
if(!empty($_POST["last_name"])){
$keys=$keys."last_name,";
$last_name=$_POST["last_name"];
$values=$values."'".$_POST['last_name']."',";
}
...
...
Check if files uploaded
if(isset($_FILES["zayavlenie_o_zachisleniy"]["name"]) && !empty($_FILES["zayavlenie_o_zachisleniy"]["name"])){
array_push($uploads,"zayavlenie_o_zachisleniy");
upload("zayavlenie_o_zachisleniy");
}
...
...
Here checks file for error and upload
function upload($filename){
if (!file_exists('student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo)) {
mkdir('student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo, 0777, true);
}
$target_dir = 'student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo.'/';
$target_file = $target_dir . basename($_FILES[$filename]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
.....
}
// Check if file already exists
if (file_exists($target_file)) {
.....
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
.....
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
.....
} else {
if (move_uploaded_file($_FILES[$filename]["tmp_name"], $target_file)) {
array_push($values,$target_file);
echo "The file ". basename( $_FILES[$filename]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
$sql="UPDATE students set $set where id='$student_id'";
for($i=0;$i<sizeof($uploads);$i++){
if($i==(sizeof($uploads)-1)){
$sql=$sql."'".$uploads[$i]."'";
}
else{
$sql=$sql."'".$uploads[$i]."',";
}
}
$db->insert($sql.")");
You can either do this with javascript or php. If you are checking if the file does already exist on your webserver, you can't do this ONLY using javascript. So you need to check this with php, cause php is running on your server. Javascript not.
So, when you encounter any error while uploading the files (like already existing files or wrong file formats) you can redirect the user to any page you want and cancel the request like this:
header("Location: http://YourErrorPage.com");
exit;

prevent uploading of large and unsupported files in image upload form

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.

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...

Running php in JavaScript

I am making an application on my server, where the user uploads an image through some HTML combined with javascript.
The user finds an image on the computer through
<form action="uploadimage.php" method="post"
enctype="multipart/form-data">
<label for="file">Filnavn:</label>
<input type="file" name="file" id="file" value="100000" />
Then the point behind the javascript, is to validate on the users image
if(picture_headline.value == "" || picture_uploaded.value == "" || !ischecked)
{
// Don't execute, stay on same site
}
else
{
// execute php and upload image
}
the php is an upload image php script
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
I must say I am a bit confused here, since I have only been working with html, php and javascript for a few days now.
Am I totally off or what?
I found some "simple" examples online, which I put on my server through cuteFTP, but everytime i press upload, the website just sends me to the .php file and says the site doesn't exist.
Like Boann points out you're trying to access a non-existent file in your PHP code ("uploaded" and "uploadedfile" rather than "file" (which is what you named the field in your HTML form)).
But regarding "running PHP from JavaScript": You don't have to. The JavaScript should only return false if the form is invalid. If it's valid you don't need to do anything and the form will submit, in turn running your PHP script:
form.onsubmit = function () {
if (!formIsValid()) {
return false;
}
};
If the form is invalid it won't submit (the return false bit (you could use event.preventDefault() instead)), if it is valid nothing will happen and the form will do what it does (ie submit the data to the server).
Each array key in $_FILES corresponds with the name attribute of a file field in the form, so to match your form it should be 'file' rather than 'uploaded' or 'uploadedfile':
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['file']['name'] ) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}

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