Nested if(isset) is not working as intended - php

I have a nested if (isset) but it doesn't seem to work as I intended. I also tried if (!empty). Please see the code below.
if (isset($_POST['submit'])){
if(isset($_FILES['userFile'])){
//upload file, make tumbnail, then put info to the the tables on the database
//header location
} else if (isset($_POST['comment'])){
//put info to the tables on the database
//header location
} else {
die("you didn't write a comment or upload a file");
}
}
My intention was to let user upload a pic without a comment or let him or her comment without uploading a picture and obviously not letting the user to send an empty form. I searched a bit but I didn't find much info about nested isset or empty.
Am I on the right track? if so; how can I make this one work?
Because when I try the code above without setting a userFile, it still gives me the error from the userFile part and the part is like below:
if($imagesize2 > $max_size2) {
die("your file is bigger than max size");
} else if($safe_imagetype2 =='image/jpeg' || $safe_imagetype2 =='image/png' || $safe_imagetype2 == 'image/jpg' || $safe_imagetype2 == 'image/gif') {
move_uploaded_file($safe_uploadTmp2, "./images/$safe_uploadName2");
} else {
die("it must be gif, jpg or png");
}
any help appreciated.

This is what you're looking for.
if(isset($_FILES['userFile']) && strlen($_FILES['userFile']['inputNAME']) > 1)

You should to check the error during the file upload this way:
if (isset($_FILES['userFile']) && UPLOAD_ERR_OK == $_FILES['userFile']['error']) {
// The file has been uploaded successfully
}

Related

Echo something from script to html

I'm a noob in php and I need some help please.
I have a uploading script that uploads something to my server.
So after I upload the file i get a message your file was upload and I want this message to be posted in my html upload page(main page) and the code is like this:
if(empty($errors)===true){
move_uploaded_file($file_tmp,"upload/".$file_name);
echo "Your file was upload!"; <- I want this line to be printed in other page //
}else{
print_r($errors);
}
}
Edit :
And I found an error to my script if you could help me with this two please:
$file_name=$_FILES['file']['name'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type=$_FILES['file']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
$extensions = array("rar","zip","jpeg","jpg","png","gif");
if(in_array($file_ext,$extensions)=== false){
$error[]= "Extension not allowed, please choose a RAR or ZIP file or if you upload an image use JPEG, JPG, PNG or GIF format.</br> Thank you!";
}
This is my code to restrict file upload,but it won't take the restrictions,can any1 tell me why please?
Hope I'm explicit enough.
Thank you !
You can modify your script in the below way.
... if(empty($errors)===true){
move_uploaded_file($file_tmp,"upload/".$file_name);
header("Location: otherpage.php?msg=success");
}else{
header("Location: otherpage.php?msg=failure");
print_r($errors);
}
} ...
In otherpage.php,
if(isset($_GET['msg']) && $_GET['msg'] == 'success') {
echo "File uploaded sucessfully";
}
EDIT:
You have written print_r($errors). I am assuming that $errors is an array. In that case you can pass this variable to the url by using json_encode($errors), see below.
$err = json_encode($errors);
$urlEncode = urlencode($err);
//now pass this to the url like this
header("Location: otherpage.php?msg=failure&err=".$urlEncode);
//in otherpage.php, you have to decode it.
if(isset($_GET['err'])) {
$errDecode = urldecode($_GET['err']);
$err = json_decode($errDecode);
print_r($err); //prints the error
}
Extensions:
Your script seems to be correct, can you try it in the below way.
$extensions = array("rar","zip","jpeg","jpg","png","gif");
if(!in_array($file_ext,$extensions)){
$error[]= "your error statement";
}
Place your echo on the page you want it to appear on, not on a separate page. Alternately send your echo string as part of the form submission, but this is probably not appropriate for this case. But then you could set what should be printed on the next page, but set it in advance.

Check if specific input file is empty

In my form I have 3 input fields for file upload:
<input type=file name="cover_image">
<input type=file name="image1">
<input type=file name="image2">
How can I check if cover_image is empty - no file is put for upload?
You can check by using the size field on the $_FILES array like so:
if ($_FILES['cover_image']['error'] == 4 || ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0))
{
// cover_image is empty (and not an error), or no file was uploaded
}
(I also check error here because it may be 0 if something went wrong (ie. a file was selected, but there's no data received). I wouldn't use name for this check since that can be overridden). error with a value of 4 is UPLOAD_ERR_NO_FILE, so we can check for that too.
Method 1
if($_FILES['cover_image']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
Method 2
if($_FILES['cover_image']['size'] == 0) {
// No file was selected for upload, your (re)action goes here
}
You can check if there is a value, and if the image is valid by doing the following:
if(empty($_FILES['cover_image']['tmp_name']) || !is_uploaded_file($_FILES['cover_image']['tmp_name']))
{
// Handle no image here...
}
if (empty($_FILES['cover_image']['name']))
simple :
if($_FILES['cover_image']['error'] > 0)
// cover_image is empty
check after the form is posted the following
$_FILES["cover_image"]["size"]==0
if (!$_FILES['image']['size'][0] == 0){ //}
if( ($_POST) && (!empty($_POST['cover_image'])) ) //verifies if post exists and cover_image is not empty
{
//execute whatever code you want
}
if(!empty($_FILES)) { // code if not uploaded } else { // code if uploaded }
$_FILES is an associative POST method array, if You want to check anything about $_FILES You must take into account the index... I tried a lot of suggested options, and the only method that worked for me, was when I included an index in my verification method.
$_FILES['Your_File']['name'][0];
So bye doing this:
if(empty($_FILES['Your_File']['name'][0])){
print('this thing is empty');
}else{
print('Something, something, something');
}
There's nothing like good old experimentation and lots of reading.
if($_FILES['img_name']['name']!=""){
echo "File Present";
}else{
echo "Empty file";
}
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
// Code comes here
}
This thing works for me........
<input type="file" class="custom-file-input" id="imagefile" name="imagefile[]" multiple lang="en">
<input type="hidden" name="hidden_imagefile[]" value="<?=$row[2]; ?>" class="form-control border-input" >
if($_FILES['imagefile']['name'] == '')
{
$img = $_POST['hidden_imagefile'];
}
else{
$img = '';
$uploadFolder = 'uploads/gallery/';
foreach ($_FILES['imagefile']['tmp_name'] as $key => $image) {
$imageTmpName = time() .$_FILES['imagefile']['tmp_name'][$key];
$imageName = time() .$_FILES['imagefile']['name'][$key];
$img .= $imageName.',';
$result = move_uploaded_file($imageTmpName, $uploadFolder.$img);
}
}
if ($_FILES['cover_image']['error'] == 4){
// the user did not choose any file
}else{
// the user chose a file to be uploaded
}
This will work
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
// checking if file is selected and not an error
{
// file is not selected and it is not an error
}
UPDATED:
Use this method:
First check if 'cover_image' key exists in $_FILES then check other file errors
if (in_array('cover_image', array_keys($_FILES) && $_FILES['cover_image']['error'] == 0) {
// TODO: write your code
} else {
// return error
}

How to check if image was submitted with other form data

I have an user registration form and uploading image with other form elements is optional there. So sometimes users may not upload image along with other data.
Now the problem is even though the user has not uploaded image, the following code always echos that the file was uploaded
Could you please kindly tell me how to check if the image was submitted by the user and make it echo/display "not uploaded" if not uploaded ?
Thanks in Advance :)
In my Controller File
extract($_POST); // <<This is to retrieve all form data at once
if(isset($_FILES['userfile'])){
echo"file uploaded";
} else{
echo "Not Uploaded";
}
This is in my View File
<input type="file" class="" name="userfile" size="20" />
Per PHP documentation:
If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.
source: http://www.php.net/manual/en/features.file-upload.post-method.php
So your conditional can change to:
if(isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0){
echo"file uploaded";
} else echo "Not Uploaded" ;
You can combine both checks:
if (count($_POST) and !empty($_FILES['userfile'])) {
// uploaded
}
else {
// either is missing
}
Note that you should not use extract($_POST);. You can't control which local variables get overwritten from the outside with that. (If nothing else investigate EXTR_PREFIX.)

Uploading Photos Issue

i have wrote a function that takes a photo upload from a form, creates the file on the server and adds the information to the database, but Im having a nightmare trying to get it to do exactly what i want.
EDIT
Currently, it displays the correct error message if the filetype is wrong, and over 3MB but when i try to upload a 17MB .bmp file it cancels and logs me out. It appears to reinitiate my process.php file after it has processed the intended function.
I am baffled, so any help would be appreciated. Thanks
<form action="process.php" method="POST" enctype="multipart/form-data" name="formUpload">
<label>Picture:</label>
<input type="file" name="photo" id="photobrowser" tabindex="4">
<span class="error"><?php echo $form->error("photo"); ?></span><br />
<input type="hidden" name="sessionid" value="<?php echo $sessionid; ?>" />
<input type="hidden" name="subphoto" value="1" />
<input type="image" src="styling/images/button-add-photo.png" id="subBtn" tabindex="6" />
</form>
process.php
class Process {
function Process(){ /* Class constructor */
global $session;
if(isset($_POST['subphoto'])){ /* User submitted an advert photo */
$this->procAddPhoto();
} else if($session->logged_in){ /* No form was submitted therefor logout */
$this->procLogout();
} else { /* User trying to view this file */
header("Location: /");
}
}
function procAddPhoto(){
global $session, $form;
$retval = $session->addPhoto($_FILES['photo']['size'], $_FILES['photo']['type'], $_FILES['photo']['tmp_name'], $_POST['sessionid']);
if($retval == 0){ /* Successful */
// do stuff
} else if($retval == 1){ /* Errors found */
// do stuff
} else if($retval == 2){ /* Adding failed */
// do stuff
}
} // close function procAddPhoto()
};
$process = new Process; /* Initialize process */
?>
session.php
function addPhoto($subphotoSize,$subphotoType,$subphotoTmpname,$subsessionid){
global $database, $form;
$maxFileSize = 3000000; // bytes (3 MB)
/* Image error checking */
$field = "photo";
if($subphotoSize == 0){
$form->setError($field, "* No file selected");
} else {
list($width, $height, $type, $attr) = getimagesize($subphotoTmpname);
if($width > 4000){
$form->setError($field, "* Max photo width is 4000 pixels.");
} else if($subphotoSize > $maxFileSize) {
$form->setError($field, "* Photo is above the maximum of 3 MB");
} else if( ($subphotoType != "image/jpeg") && ($subphotoType != "image/pjpeg") && ($subphotoType != "image/png") ){
$form->setError($field, "* $subphotoType is wrong file type");
}
}
/* Errors exist, have user correct them */
if($form->num_errors > 0){
return 1; //Errors with form
} else { // Else use variables
/* Get random string for new filename name */
$randNum = $this->generateRandStr(10);
$filerootpath = PHOTOS_DIR.$subsessionid."/";
$thumbrootpath = PHOTOS_DIR.$subsessionid."/thumbs/";
if($subphotoType == "image/png"){
$filename = $randNum.".png";
} else if ($subphotoType == "image/jpeg" || $subphotoType == "image/pjpeg"){
$filename = $randNum.".jpg";
}
$fullURL = $filerootpath.$filename;
$thumbURL = $thumbrootpath.$filename;
/* Make sure file is RGB colors */
$getimagesize = getimagesize($subphotoTmpname);
if (isset($getimagesize['channels']) && $getimagesize['channels'] == 4 && $getimagesize[2] == IMAGETYPE_JPEG ) {
$im = #imagecreatefromjpeg($subphotoTmpname);
if ($im) {
imagejpeg($im, $image, 75);
imagedestroy($im);
}
}
/* Upload files to correct folders */
move_uploaded_file($subphotoTmpname, "$fullURL");
/* Use session ID for the advert ID because it hasnt been made yet */
$userSession = $this->userinfo['userid'];
$ownerID = $this->userinfo['id'];
if(!$database->addNewPhoto($ownerID,$fullURL,$userSession,$is_main_photo, $subsessionid, $thumbURL)){
return 2; // Failed to add to database
}
}
return 0; // Success
}
Just a thought... I am guessing that you have more than one issue here. You said that when someone tries to upload a file over X mb it basically hits the kill switch. Do you know, roughly, what that size is? If you do, can you compare it to the upload_max_filesize and post_max_size settings for your php installation? They should both be visible in phpinfo(). I think that the default is somewhere around 2mb but I could be wrong on that. Either way, I know that when you try to upload beyond those settings it basically spits the bit. You may have to change the php.ini settings for that one.
It displays an error if the filetype isnt correct, unless, the file
is several MB in size, in which case it completely logs the user out,
almost like its killing all session variables
Please open /etc/php5/apache2/php.ini (assuming you are using apache2) and set upload_max_filesize = 5M (for 5 megabyte file) and you have file_uploads = On. then restart apache. and try again.
The image cannot be displayed because it contatins errors." But when i
download the uploaded image from the server, the picture displays
fine, but not via http.
can you check you have enough permission to read image from the directory where it is stored. (and make sure you are accessing the right directory; try copying relative path of image in the browser address bar )
let me clear few things first:
1.you can upload 17 mb file but you want to restrict upload more than 3 mb.
2.it uploads 17 mb file but from browser you can see that. but if you download from your server windows can open it correctly.?
can you insert: var_dump($ubphotoSize); var_dump($$maxFileSize); at the beginning of addPhot() and try again. according to you it seems it cannot compare file sizes. please let us know our output.

Problem with uploading multiple files PHP

On my site I have a page where users can upload files to go with the news post they're adding. I allow them to upload one image and one sound file. They don't have to add files if they don't want to, or they can just add one if they want. Problem I'm having is that my script only works if the user selects both files. If they choose none, or only one, then the script spits out 'Invalid File' as it can't find a file where one hasn't been selected.
I tried using:
if (isset($_FILES['filetoupload1'])) {
if (($_FILES["filetoupload1"]["type"] == "image/gif")
|| ($_FILES["filetoupload1"]["type"] == "image/jpeg")
|| ($_FILES["filetoupload1"]["type"] == "image/pjpeg")
|| ($_FILES["filetoupload1"]["type"] == "image/png")
|| ($_FILES["filetoupload1"]["type"] == "image/jpg")
) {
if ($_FILES["filetoupload1"]["error"] > 0) {
echo "Return Code: " . $_FILES["filetoupload1"]["error"] . "<br />";
} else {
if (file_exists("media/" . $_FILES["filetoupload1"]["name"])) {
echo $_FILES["filetoupload1"]["name"] . " already exists. ";
}
move_uploaded_file(
$_FILES["filetoupload1"]["tmp_name"],
"media/" . $_FILES["filetoupload1"]["name"]
);
}
} else {
echo "Invalid file";
}
}
if (isset($_FILES['filetoupload2'])) {
if ($_FILES["filetoupload2"]["type"] == "audio/mp3") {
if ($_FILES["filetoupload2"]["error"] > 0) {
echo "Return Code: " . $_FILES["filetoupload2"]["error"] . "<br />";
} else {
if (file_exists("media/" . $_FILES["filetoupload2"]["name"])) {
echo $_FILES["filetoupload2"]["name"] . " already exists. ";
}
move_uploaded_file(
$_FILES["filetoupload2"]["tmp_name"],
"media/" . $_FILES["filetoupload2"]["name"]
);
}
} else {
echo "Invalid file";
}
}
and then
if((isset($_FILES['filetoupload1'])) && (isset($_FILES['filetoupload2']))) { }
before both first and second upload scripts if the user had selected both image and audio file. In other words it did this:
if filetoupload1 isset then run upload script that filters images.
if filetoupload2 isset then run upload script that filters audio.
if filetoupload1 AND filetoupload2 isset then run both upload scripts.
I have it set like that. The above should allow for all combinations of file uploads. right? but it doesnt work so..
Now I have no idea what to do. Here's the upload script for the audio, the image one is pretty much the same:
Can someone tell me what I'm doing wrong please!
"I get the error: Invalid file"
This is correct, since your code just does this.
Do not check if the file is set but if i.e. $_FILES["filetoupload1"]["type"] is not empty.
Your script makes your server vulnerable to a malicious user being able stomp on any file the webserver has access to:
$_FILES[...]['name'] - user supplied
$_FILES[...]['type'] - user supplied
You're trusting that the client has supplied the proper MIME type for the file, but nothing stops someone from forging a request and uploading "virus.exe" and setting the mime type to 'image/jpeg'. As well, since the remote filename is under user control, it can be subverted with malicious data. Consider:
$_FILES['picture']['type'] = 'image/gif'
$_FILES['picture']['name'] = 'remote_server_control.php'
Completely legitimate according to your script, because the mime type is "right", and yet you've now put a user-supplied PHP script on your server and with that they can take total control of your site and/or server.
Never EVER trust the data in the $_FILES array. Always determine MIME types via server-side utilities. If the script is only supposed to handle images, then use getimagesize(). As well, never use user-supplied filenames. Use something determined server-side to give the file a name, like a databasde auto_increment ID number. Even though your code doesn't allow for overwriting existing files, it's trivial to just come up with a new name and boom... new version of the remote takeover script.
I suggest to you to add a hidden text, this hidden will check witch upload fields are active, you make this check with javascript:
<html lang="en">
<head>
<meta charset="utf-8">
<style>
</style>
<script type="text/javascript">
function uploadForm()
{
var size = 0;
var x = document.forms["myForm"]["upload1"].value.length;
var y = document.forms["myForm"]["upload2"].value.length;
if (x > 0)
{
size = 3;
}
if (y > 0)
{
size += 2;
}
return size;
}
</script>
</head>
<body>
<form name="myForm" action="" method="GET" onsubmit="chose.value = uploadForm()">
<input type="file" name="upload1"><br>
<input type="file" name="upload2"><br>
<input type="hidden" name="chose" value=""><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Now, when you receive the form, you have to check the value of chose filed, if its 2, that is mean the image field is not empty, 3 audio filed is not empty, 5 both not empty:
<?php
switch($_GET["chose"])
{
case 2:
//
break;
case 3;
//
break;
case 5:
//
break;
default:
// here the user doesn't use any field
}
?>

Categories