Solved

PHP - Assistance with IF Statement

Posted on 2014-12-26
7
13 Views
Last Modified: 2016-05-27
I have a script where a user can add info into a data entry page, containing several text fields and a file upload button. The data is then parsed to 2 separate tables. It works great, but I am running into an issue where if I decide to not upload a document, the script will still run, but make a blank entry into the table housing the file upload info. See below:

	//connect to db
	require_once('./includes/mysql_connect.inc');
	
	//enter data into db
	$sql="INSERT INTO masterlist (client, entry, type, createdBy, dateCreated, lastUpdate, description, notes)
          VALUES ('$cn', '$en', '$ty', '$ur', '$dc', '$ud', '$ds', '$nt')";
		 
	
	if (!mysql_query($sql,$dbc))
	{
		die('Error: ' . mysql_error());
	}else{
		echo "<font color='#CCCCFF'>New entry submitted!  </font>";
		}
		
			//start script for uploading function
			require_once('./includes/mysql_connect.inc');
			
			
			$pidQuery = "SELECT UID FROM masterlist WHERE client='$cn' AND notes='$nt'";
			$pidResult = mysql_query($pidQuery);
			$pidRow = mysql_fetch_array($pidResult);
			
			
			// Add the record to the database.
			$uploadQuery = "INSERT INTO masterupload (uploadID, fname, fsize, ftype) VALUES ('$pidRow[UID]','{$_FILES['file']['name']}', {$_FILES['file']['size']}, '{$_FILES['file']['type']}')";
			$uploadResult = @mysql_query($uploadQuery);
			echo mysql_error();
			//if info successfully posted to hel
			if($uploadResult){

				// Create the filename.
				$extension = explode('.', $_FILES['file']['name']);
				$filename = $pidRow['UID'] . '.' . $extension[1];

				// Move the file over.
				if(move_uploaded_file($_FILES['file']['tmp_name'], "\wamp\www\content/$filename")) {
					echo '<p><center>The file has been uploaded!</center></p>';
				} else {
					echo '<p><font color="#CCCCFF"><center>The file could not be moved.</font></p>';
					echo mysql_error();
				}

			} else { // If the query did not run OK.
				echo '<p><font color="#CCCCFF"><center>Your document could not be uploaded due to a system error.</center></font></p>';
			} 
			

			mysql_close(); // Close the database connection.
 }}
?>

Open in new window



I want to be able to simply bypass the file upload portion of this script if no doc was chosen for the upload. I have tried added a IF null statement, but its not working. Any help would be appreciated!

P.S. I know I should move over to PDO or mysqli. I will.
0
Comment
Question by:quimmy
  • 3
  • 2
7 Comments
 

Author Comment

by:quimmy
ID: 40518745
Sorry, new here. Thanks!
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40519067
OK, there are a lot of moving parts to this application / script so let's deconstruct it a little bit.  Before we go too far, please post the HTML document that you use to upload the file(s), so we can see how you're creating the PHP $_FILES array.

Next, please make a Google search for PHP security and read everything you can find.  What you've got here has the ability to destroy your database, as soon as a hacker finds it.  These links will be helpful, too.
http://php.net/manual/en/language.variables.external.php
http://php.net/manual/en/security.php
http://php.net/manual/en/features.file-upload.php

I'll try to show you some of the things that you need to know about file uploads in another post.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40519099
When you're working with PHP file uploads, you're dealing with specialized external data.  One part of the process is ensuring that the data in the $_FILES array is actually an uploaded file, and not something injected by a malicious co-resident of a shared server.  These links teach some of the things you need to check for.
http://php.net/manual/en/features.file-upload.php
http://php.net/manual/en/features.file-upload.common-pitfalls.php
http://php.net/manual/en/function.move-uploaded-file.php
http://php.net/manual/en/reserved.variables.files.php

If you're working with large files, like images or video, these links matter too.
http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
http://php.net/manual/en/ini.core.php#ini.post-max-size
http://php.net/manual/en/info.configuration.php#ini.max-input-time

Basically what you want to do follows these steps:

1. Check $_FILES to see if there are any errors in the upload process.  If there are, just ignore the input since it may be attack data.  Here are the things you need to test for:
// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;

Open in new window

So if the ['error'] part is zero, there are no errors and you can use the file.  It will not be zero if no document was uploaded; it will be 4, so that helps with one part of your question.
0
 

Author Comment

by:quimmy
ID: 40519112
Thanks Ray. Here is the HTML code:

<br><h1 align="left">Enter Information:</h1></font>
<form name="entryadd" method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data">
<table class="clean">
<tr><td>Client Name:</td><td><select name="client">
	    <option value="">Please select client
		<option value="Client Name">Client Name
</select></td></tr>
<tr><td>Entry Name:</td><td>
<input type="text" name="entry" size="20" maxlength="20" /></td></tr>
<tr><td>Type:</td><td><select name="type">
	    <option value="">Please select type
		<option value="General Info">General
		<option value="Password">Password
		<option value="Network Info">Network Info
		<option value="Licensing">Licensing
</select></td></tr>
<tr><td>Created By:</td><td><select name="user">
	    <option value="">Please select type
		<option value="Tech 1>Tech 1
</select></td></tr>
<tr><td>Select File:</td><td>
<input type="file" name="file"></tr></td>
<tr><td>Description:</td><td>
<textarea name="desc" rows="5" cols="75"></textarea></td></tr>
<tr><td>Notes:</td><td>
<textarea name="notes" rows="20" cols="75"></textarea></td></tr>
<input type="hidden" 
	   name="udate" 
	   value="<?php if (isset($_POST['date'])) echo $_POST['date']; else echo date('Y-m-d H:i:s');?>" 
	   size="20" 
	   maxlength="20" /></td></tr>
<tr><td colspan="4" align="center"><input type="submit" name="submit" value="Submit" /></td></tr></table>

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points
ID: 40520460
I see a couple of things that you might want to deal with, in addition to handling the file uploads.  It's important to write valid HTML, and you can use the W3 validator to help you check for validity.
http://validator.w3.org/

One of the obvious things -- HTML option tags need to be closed.  Some browsers will allow invalid markup, but any hope of consistent cross-browser styling goes out the window if you're dealing with invalid markup.  So instead of this:

<option value="General Info">General

you would want this:

<option value="General Info">General</option>

I would also remove the hidden input for udate.  This information is already available on the server; there is no value in putting it into the form, and most likely this form is a web page that is accessed via a GET request.  Since it's not accessed via a POST request, the reference to $_POST['date'] will always be unset.  (The form makes a POST request to the server, but that's different than the request that loads the web page).

I think I'll write an article about how to upload files -- this is a very common question.  For now, here is my teaching example that shows how it's done.  Please read it over - code and comments - and post back with any questions.  You will see that the PHP action script and the HTML form are all part of this one script file.  It's sometimes useful to organize your work this way since it keeps the related scripts together.

<?php // demo/upload_one_file.php
error_reporting(E_ALL);

// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/reserved.variables.files.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT (USE UPPERCASE ONLY)
$file_exts = array
( 'XLS'
, 'XLSX'
, 'PDF'
, 'CSV'
)
;
$f_exts = implode(', ', $file_exts);

// ESTABLISH THE NAME OF THE DESTINATION FOLDER
$my_dir = getcwd();

// OR USE THIS TO PUT UPLOADS IN A SEPARATE FOLDER
$my_dir = 'storage';
if (!is_dir($my_dir))
{
    mkdir($my_dir);
}

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;


// IF THERE IS INFORMATION POSTED
if (!empty($_POST))
{
    // IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code)
    {
        trigger_error($errors[$error_code], E_USER_ERROR);
    }

    // GET THE FILE SIZE
    $fsize = number_format($_FILES["userfile"]["size"]);

    // SYNTHESIZE THE NEW FILE NAME FOR TEMPORARY STORAGE
    $fname = basename($_FILES['userfile']['name']);

    // FAIL IF THIS IS NOT AN ALLOWABLE EXTENSION
    $f_ext = explode('.', $fname);
    $f_ext = end($f_ext);
    $f_ext = strtoupper(trim($f_ext));
    if (!in_array($f_ext, $file_exts)) trigger_error("$f_ext NOT ALLOWED.  CHOOSE FROM $f_exts", E_USER_ERROR);

    // THE SERVER PATH TO THE FILE
    $my_path
    = getcwd()
    . DIRECTORY_SEPARATOR
    . $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // THE URL PATH TO THE FILE
    $my_url
    = $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // MESSAGES ABOUT THE UPLOAD STATUS, IF ANY
    $msg = NULL;

    // IF THE FILE IS NEW (DOES NOT EXIST)
    if (!file_exists($my_path))
    {
        // IF THE MOVE FUNCTION WORKED CORRECTLY
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
        {
            $upload_success = 1;
        }
        // IF THE MOVE FUNCTION FAILED IT PROBABLY THREW A MESSAGE
        else
        {
            $upload_success = -1;
            trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
        }
    }

    // IF THE FILE ALREADY EXISTS
    else
    {
        $msg .= "<br/><b><i>$my_url</i></b> already exists" . PHP_EOL;

        // SHOULD WE OVERWRITE THE FILE? IF NOT
        if (empty($_POST["overwrite"]))
        {
            $upload_success = 0;
        }

        // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
        else
        {
            $now    = date('Y-m-d-His');
            $my_bak = $my_path . '.' . $now . '.bak';
            if (!copy($my_path, $my_bak))
            {
                $msg .= "<br/><strong>Attempted Backup Failed!</strong>" . PHP_EOL;
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
            {
                $upload_success = 2;
            }
            else
            {
                $upload_success = -1;
                trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
            }
        }
    }

    // PREPARE A REPORT OF THE SCRIPT'S SUCCESS OR FAILURE
    if ($upload_success == 2) { $msg .= "<br/>A backup was made and the file was overwritten" . PHP_EOL; }
    if ($upload_success == 1) { $msg .= "<br/><strong>$my_url</strong> has been saved" . PHP_EOL; }
    if ($upload_success == 0) { $msg .= "<br/><strong>It was NOT overwritten.</strong>" . PHP_EOL; }
    if ($upload_success < 0)  { $msg .= "<br/><strong>ERROR: $my_url NOT SAVED - SEE WARNING FROM move_uploaded_file()</strong>" . PHP_EOL; }

    // ADD FILE SIZE AND PERMISSION INFORMATION
    if ($upload_success > 0)
    {
        $msg .= "<br/>$fsize bytes uploaded" . PHP_EOL;
        if (!chmod ($my_path, 0755))
        {
            $msg .= "<br/>chmod(0755) FAILED: fileperms() = ";
            $msg .= substr(sprintf('%o', fileperms($my_path)), -4);
        }
    }

    // SHOW THE SUCCESS OR FAILURE
    echo $msg;

    // SHOW A LINK TO THE FILE
    echo '<br/>'
    . '<a href="'
    . $my_url
    . '" target="_blank">'
    . "See: $my_url"
    . '</a>'
    ;
}


// CREATE THE FORM FOR INPUT (USING HEREDOC SYNTAX)
$form = <<<ENDFORM
<p>Upload one file
<form enctype="multipart/form-data" method="post">
<!-- MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD -->
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
Find a file to Upload ($f_exts): <input name="userfile" type="file" />
<br/>Check this box
<input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files
</br><input type="submit" value="Upload" />
</form>
</p>
ENDFORM;

echo $form;

Open in new window

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

These days socially coordinated efforts have turned into a critical requirement for enterprises.
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now