Jump to content
Larry Ullman's Book Forums

Recommended Posts

i try to upload pdf file, it work but when i try another pdf it's fail. instead rather than show me the error it show me this code:

 

<input type="hidden" name="MAX_FILE_SIZE" value="5242880">
	
	<fieldset><legend>Fill out the form to add a PDF to the site:</legend>
	
<div class="form-group has-error"><label for="title" class="control-label">Title</label><input type="text" name="title" id="title" class="form-control"><span class="help-block">Please enter the title!</span></div><div class="form-group has-error"><label for="description" class="control-label">Description</label><span class="help-block">Please enter the description!</span><textarea name="description" id="description" class="form-control"></textarea></div><div class="form-group has-error"><label for="pdf" class="control-label">PDF</label><input type="file" name="pdf" id="pdf"><span class="help-block">No file was uploaded.</span><span class="help-block">PDF only, 5MB Limit</span>
</div>		<input type="submit" name="submit_button" value="Add This PDF" id="submit_button" class="btn btn-default" />
	
	</fieldset>

</form> 

			<!-- END CONTENT -->
			</div><!--/col-9-->
		
		</div><!--/row-->

      </div><!--/container-->

    </div><!--/wrap-->

    <div id="footer">
      <div class="container">
        <p class="text-muted credit"><span class="pull-left"><a href="site_map.php">Site Map</a> | <a href="policies.php">Policies</a></span> <span class="pull-right">© Knowledge is Power - 2013</span></p>
      </div>
    </div>

	<script src="js/bootstrap.min.js"></script>
  </body>
</html>
0

is it anything wrong? I use the code that I've download without a change. thanks.

 

Share this post


Link to post
Share on other sites

Read the content. It says that only PDFs smaller than 5MB are accepted. Change the code or make adjustments according to values in the code that makes sense. If that doesn't work, you'll have to alter som PHP settings.

Share this post


Link to post
Share on other sites

it's not the matter the file size, I've upload the file under 5 MB, and i already change the file size into 15 MB and set my php.ini more than 10MB and it's still the same. I think there's some problem on script that i missed. if it's error it supposes show error messages from error handler or from php it self rather than the code above.

Share this post


Link to post
Share on other sites

here's the code for that add_pdf.php 

<?php

// This page is used by an administrator to add a PDF to the site.
// This script is created in Chapter 5.

// Require the configuration before any PHP code as the configuration controls error reporting:
require('./includes/config.inc.php');

// If the user isn't logged in as an administrator, redirect them:
redirect_invalid_user('user_admin');

// Require the database connection:
require(MYSQL);

// Include the header file:
$page_title = 'Add a PDF';
include('./includes/header.html');

// For storing errors:
$add_pdf_errors = array();

// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {	

	// Check for a title:
	if (!empty($_POST['title'])) {
		$t = escape_data(strip_tags($_POST['title']), $dbc);
	} else {
		$add_pdf_errors['title'] = 'Please enter the title!';
	}
	
	// Check for a description:
	if (!empty($_POST['description'])) {
		$d = escape_data(strip_tags($_POST['description']), $dbc);
	} else {
		$add_pdf_errors['description'] = 'Please enter the description!';
	}

	// Check for a PDF:
	if (is_uploaded_file($_FILES['pdf']['tmp_name']) && ($_FILES['pdf']['error'] === UPLOAD_ERR_OK)) {
	
		// Get a reference:
		$file = $_FILES['pdf'];
		
		// Find the size:
		$size = ROUND($file['size']/1024);

		// Validate the file size (5MB max):
		if ($size > 15120) {
			$add_pdf_errors['pdf'] = 'The uploaded file was too large.';
		} 

		// Validate the file type:
		// Create the resource:
		$fileinfo = finfo_open(FILEINFO_MIME_TYPE);

		// Check the file:
		if (finfo_file($fileinfo, $file['tmp_name']) !== 'application/pdf') {
			$add_pdf_errors['pdf'] = 'The uploaded file was not a PDF.';
		} 

		// Close the resource:
		finfo_close($fileinfo);

		// Move the file over, if no problems:
		if (!array_key_exists('pdf', $add_pdf_errors)) {

			// Create a tmp_name for the file:
			$tmp_name = sha1($file['name']) . uniqid('',true);
	
			// Move the file to its proper folder but add _tmp, just in case:
			$dest =  PDFS_DIR . $tmp_name . '_tmp';

			if (move_uploaded_file($file['tmp_name'], $dest)) {
	
				// Store the data in the session for later use:
				$_SESSION['pdf']['tmp_name'] = $tmp_name;
				$_SESSION['pdf']['size'] = $size;
				$_SESSION['pdf']['file_name'] = $file['name'];
	
				// Print a message:
				echo '<div class="alert alert-success"><h3>The file has been uploaded!</h3></div>';
	
			} else {
				trigger_error('The file could not be moved.');
				unlink ($file['tmp_name']);				
			}

		} // End of array_key_exists() IF.
	
	} elseif (!isset($_SESSION['pdf'])) { // No current or previous uploaded file.
		switch ($_FILES['pdf']['error']) {
			case 1:
			case 2:
				$add_pdf_errors['pdf'] = 'The uploaded file was too large.';
				break;
			case 3:
				$add_pdf_errors['pdf'] = 'The file was only partially uploaded.';
				break;
			case 6:
			case 7:
			case 8:
				$add_pdf_errors['pdf'] = 'The file could not be uploaded due to a system error.';
				break;
			case 4:
			default: 
				$add_pdf_errors['pdf'] = 'No file was uploaded.';
				break;
		} // End of SWITCH.

	} // End of $_FILES IF-ELSEIF-ELSE.
	
	if (empty($add_pdf_errors)) { // If everything's OK.
		
		// Add the PDF to the database:
		$fn = escape_data($_SESSION['pdf']['file_name'], $dbc);
		$tmp_name = escape_data($_SESSION['pdf']['tmp_name'], $dbc);
		$size = (int) $_SESSION['pdf']['size'];
		$q = "INSERT INTO pdfs (title, description, tmp_name, file_name, size) VALUES ('$t', '$d', '$tmp_name', '$fn', $size)";
		$r = mysqli_query($dbc, $q);
		if (mysqli_affected_rows($dbc) === 1) { // If it ran OK.
	
			// Rename the temporary file:
			$original =  PDFS_DIR . $tmp_name . '_tmp';
			$dest =  PDFS_DIR . $tmp_name;
			rename($original, $dest);

			// Print a message:
			echo '<div class="alert alert-success"><h3>The PDF has been added!</h3></div>';

			// Clear $_POST:
			$_POST = array();

			// Clear $_FILES:
			$_FILES = array();

			// Clear $file and $_SESSION['pdf']:
			unset($file, $_SESSION['pdf']);
					
		} else { // If it did not run OK.
			trigger_error('The PDF could not be added due to a system error. We apologize for any inconvenience.');
			unlink ($dest);
		}
				
	} // End of $errors IF.
	
} else { // Clear out the session on a GET request:
	unset($_SESSION['pdf']);	
} // End of the submission IF.

// Need the form functions script, which defines create_form_input():
require('includes/form_functions.inc.php');
?><h1>Add a PDF</h1>
<form enctype="multipart/form-data" action="add_pdf.php" method="post" accept-charset="utf-8">

	<input type="hidden" name="MAX_FILE_SIZE" value="5242880">
	
	<fieldset><legend>Fill out the form to add a PDF to the site:</legend>
	
<?php
create_form_input('title', 'text', 'Title', $add_pdf_errors); 
create_form_input('description', 'textarea', 'Description', $add_pdf_errors); 

// Add the file input:
echo '<div class="form-group';

// Add classes, if applicable:
if (array_key_exists('pdf', $add_pdf_errors)) {
	echo ' has-error'; 
} else if (isset($_SESSION['pdf'])) {
	echo ' has-success'; 
}
echo '"><label for="pdf" class="control-label">PDF</label><input type="file" name="pdf" id="pdf">';

// Check for an error:
if (array_key_exists('pdf', $add_pdf_errors)) {
	
	echo '<span class="help-block">' . $add_pdf_errors['pdf'] . '</span>';
	
} else { // No error.

	// If the file exists (from a previous form submission but there were other errors),
	// store the file info in a session and note its existence:		
	if (isset($_SESSION['pdf'])) {
		echo '<p class="lead">Currently: "' . $_SESSION['pdf']['file_name'] . '"</p>';
	}

} // end of errors IF-ELSE.
echo '<span class="help-block">PDF only, 5MB Limit</span>
</div>';

?>
		<input type="submit" name="submit_button" value="Add This PDF" id="submit_button" class="btn btn-default" />
	
	</fieldset>

</form> 

<?php // Include the HTML footer:
include('./includes/footer.html');
?>

Share this post


Link to post
Share on other sites

Good to know. I would next start by doing a print_r() on $_FILES to see if anything is in it. It seems like no file is being uploaded at all.

Share this post


Link to post
Share on other sites

i'm changing the switch error code as you said like this:

} elseif (!isset($_SESSION['pdf'])) { // No current or previous uploaded file. 
print_r($_FILES['pdf']); 
} // End of $_FILES IF-ELSEIF-ELSE. 

am I doing it right? because i still saw nothing. 

Share this post


Link to post
Share on other sites

i already put the code:

// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {	

print_r($_FILES['pdf']); 

but i still got the warning and nothing to show:

ZCFfWDZ.png

and at the form i got some error which tell me that i should write the file and description although i already do it:

OcVhTdz.png

Share this post


Link to post
Share on other sites

i think i know the error, it's always error when i'm upload the file more than 3MB, this is really confuse me, i check my php.ini again and my upload_max_filesize = 64M, meanwhile your code is allow file to be upload 5MB. 

 

if the file is too large your code suppose show error that the file is too large right? then why it isn't instead it print the form code?

 

when the file is succeed the print_r is work it print like this:

 

Array ( [name] => GoogleCash - Using Google AdWords 3.1.pdf [type] => application/pdf [tmp_name] => E:\wamp\tmp\phpB1AA.tmp [error] => 0 [size] => 1838466 )

, so it seems form is not submitted right? because it's not print any error when it fail.

Share this post


Link to post
Share on other sites

There are other PHP settings that limit how much data could be uploaded. The upload also might be timing out. Are you doing this on your own computer or on a live site? What PHP version are you running?

Share this post


Link to post
Share on other sites

i'm runing on my computer. because you mention that there's other setting i was go search and check my php setting again and found that the one that cause the error was post_max_size. now the only thing i can't understand is why error handler that you make or switch error in the script is showing nothing? is it anything we can do to check and show if there is an error at post_max_size or upload_max_size? thanks.

Share this post


Link to post
Share on other sites

it's not just for me, but for my client if I have to write a script for them. it should be any warning to show them that the upload file fail because some problem. it will confusing for my client if the upload is failing, but the page show nothing. at least it give a notice that upload is error and to contact administrator.

Share this post


Link to post
Share on other sites

Glad you found the problem. There's no error message in this case because PHP failed to handle the file upload because it was too large, resulting in no file. I would first check the settings on the client's hosting. Then, if no file is uploaded, you can add to the error message something like (make sure that the file is less than X).

Share this post


Link to post
Share on other sites

one more question, is it any PHP or other script that I can use to detect post_max_size or upload_max_size so i can make error handler from it, or is it checking my client hosting setting is the only way to prevent this error? thanks.

Share this post


Link to post
Share on other sites

You could look at the function ini_get(). It's the getting equalient of ini_set(). The basic thought is something along the lines of:


$file = "./testfile.pdf";

try {
    assertUploadSize($file);
    // Safe to work with $file
}
catch ( Exception $e )
{
    // Exceptional state
    echo $e->getMessage();
}


function assertUploadSize( $file )  
{  
    // Could not work with file
    if ( ! file_exists($file) )
        throw new Exception("Error: File is not readable, or does not exists at path.");

    // Get sizes
    $fileSize = filesize($file);
    $POSTRequestSize = convertPHPSizeToBytes(ini_get('post_max_size'));
    $fileUploadSize = convertPHPSizeToBytes(ini_get('upload_max_filesize'));

    // Post size is too small
    if ( $POSTRequestSize < $fileSize  )
        throw new Exception("Error: Filesize is larger than allowed POST size.");

    // Upload size is too small
    if ( $fileUploadSize < $fileSize  )
        throw new Exception("Error: Filesize is larger than allowed file upload size.");
}

//This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case)  
function convertPHPSizeToBytes($sSize)  
{  
    if ( is_numeric( $sSize) ) {
        return $sSize;
    }
    $sSuffix = substr($sSize, -1);  
    $iValue = substr($sSize, 0, -1);  
    switch(strtoupper($sSuffix))
    {  
        case 'P':  
            $iValue *= 1024;  
        case 'T':  
            $iValue *= 1024;  
        case 'G':  
            $iValue *= 1024;  
        case 'M':  
            $iValue *= 1024;  
        case 'K':  
            $iValue *= 1024;  
        break;  
    }  
    return $iValue;  
}

I've based my answer on This Stack Overflow. One of the main problems is parsing PHP ini's values into something we can work with. I've then based the main checking function on Exceptions, as this is absolutly exceptional state. The function should display errors when a file is not readable/does not exists, or when your settings are beneth the filesize.

 

I haven't tested the code, so it might not work at the moment. That's a basic outline to solving the problem, though.

Share this post


Link to post
Share on other sites

For the past several days, I have been  following virtually everything  from the  add_php.php file but for some reason nothing is being sent to the data base. I am getting the following message:

A system error occurred. We apologize for the inconvenience.

That is occoring on line 74, 85, 116, 117, 141 and 142.

 

I would really appreciate it if a member can clarifiy to me why this is not working and what steps needed to make it work. 

 

here are the affected areas. I have highlighted them in red so you could see in the following:

 

    if (move_uploaded_file($file['tmp_name'], $dest)) {
    
                // Store the data in the session for later use:
                $_SESSION['pdf']['tmp_name'] = $tmp_name;
                $_SESSION['pdf']['size'] = $size;
                $_SESSION['pdf']['file_name'] = $file['name'];
    
                // Print a message:
                echo '<div class="alert alert-success"><h3>The file has been uploaded!</h3></div>';
    
            } else {
              trigger_error('The file could not be moved.');
                unlink ($file['tmp_name']);                
            }

        } // End of array_key_exists() IF.
    
    } elseif (!isset($_SESSION['pdf'])) { // No current or previous uploaded file.
        switch ($_FILES['pdf']['error']) {
            case 1:
            case 2:
                $add_pdf_errors['pdf'] = 'The uploaded file was too large.';
                break;
            case 3:
                $add_pdf_errors['pdf'] = 'The file was only partially uploaded.';
                break;
            case 6:
            case 7:
            case 8:
                $add_pdf_errors['pdf'] = 'The file could not be uploaded due to a system error.';
                break;
            case 4:
            default:
                $add_pdf_errors['pdf'] = 'No file was uploaded.';
                break;
        } // End of SWITCH.

    } // End of $_FILES IF-ELSEIF-ELSE.
    
    if (empty($add_pdf_errors)) { // If everything's OK.
        
        // Add the PDF to the database:
        $fn = escape_data($_SESSION['pdf']['file_name'], $dbc);
        $tmp_name = escape_data($_SESSION['pdf']['tmp_name'], $dbc);
        $size = (int) $_SESSION['pdf']['size'];

        $q = "INSERT INTO pdfs (title, description, tmp_name, file_name, size) VALUES ('$t', '$d', '$tmp_name', '$fn', $size)";
        $r = mysqli_query($dbc, $q);
        if (mysqli_affected_rows($dbc) === 1) { // If it ran OK.
    
            // Rename the temporary file:
            $original =  PDFS_DIR . $tmp_name . '_tmp';
            $dest =  PDFS_DIR . $tmp_name;
            rename($original, $dest);

            // Print a message:
            echo '<div class="alert alert-success"><h3>The PDF has been added!</h3></div>';

            // Clear $_POST:
            $_POST = array();

            // Clear $_FILES:
            $_FILES = array();

            // Clear $file and $_SESSION['pdf']:
            unset($file, $_SESSION['pdf']);
                    
        } else { // If it did not run OK.
            trigger_error('The PDF could not be added due to a system error. We apologize for any inconvenience.');
            unlink ($dest);

        }

Share this post


Link to post
Share on other sites

I'd start by verifying that a file was uploaded and verifying what the destination path is. Then check your permissions on that. Then make sure the file is being copied over properly.

Share this post


Link to post
Share on other sites

I fixed two errors with my add_pdf.php upload to MySQL database tonight!

 

My environment is both localhost using XAMPP and a school Wake Tech server.

 

First problem. I was getting an error message something about can initialize fileinfo(). Found out that the php.ini need the comment removed in front of the following line: 

 

extension=php_fileinfo.dll

 

Restarted the apache server after the change and add_pdf.php works now.

 

Second problem. On school server I was getting a different message. Big long error message that dropped to line 141 and said I had a system error. Error message was useless for debug. Read through the actual error and it said description was two long.

 

Went into database and changed the size of the description field in the pdfs table from tinytext to just text. Ran the add_page.pdf and it ran clean.

 

Hope this helps anyone with either of these errors!

Share this post


Link to post
Share on other sites

I am getting the same error complaining about  index. Kindly assist.

 

Array

(

    [0] => Array

        (

            [file] => C:\wamp\www\newstore\add_pdf.php

            [line] => 81

            [function] => my_error_handler

            [args] => Array

                (

                    [0] => 8

                    [1] => Undefined index: pdf

                    [2] => C:\wamp\www\newstore\add_pdf.php

                    [3] => 81

                    [4] => Array

                        (

                            [GLOBALS] => Array

*RECURSION*

                            [php_errormsg] => POST Content-Length of 182070 bytes exceeds the limit of 25 bytes

                            [_POST] => Array

                                (

                                )



                            [_GET] => Array

                                (

                                )



                            [_COOKIE] => Array

                                (

Share this post


Link to post
Share on other sites

The important bit is right here: 

 [php_errormsg] => POST Content-Length of 182070 bytes exceeds the limit of 25 bytes

Either your HTML form or your PHP configuration is set to allow a maximum POST data of 25 bytes (which is almost nothing). I assume this is in your PHP config, but I could be wrong about that.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...