Skip to main content
Known Participant
October 1, 2010
Answered

File upload glitch

  • October 1, 2010
  • 2 replies
  • 1528 views

I am working with another tutorial (Lesson 9) in David Powers new book on adding attachments to an email sent from an online form. When I bring the form up in my browser, enter the information and attach the file, and submit, the form information and attachments do show up in my inbox fine. However, I get the following error messages in the browser:

Warning:  file_get_contents(C:/upload_test/att1285896997-Mountains OMourne.docx) [function.file-get-contents]: failed to open stream: No such file or directory in C:\xampp\htdocs\WFRMA\scripts\process_attachments.php on line 53

Warning:  unlink(C:/upload_test/att1285896997-Mountains OMourne.docx) [function.unlink]: No such file or directory in C:\xampp\htdocs\WFRMA\scripts\process_attachments.php on line 56

Is there anyone who might know why I'm getting these messages even though the form submittal seems to otherwise be operating fine?

This topic has been closed for replies.
Correct answer David_Powers

Sorry, I've been up to my eyeballs working on the second edition of my "PHP Solutions", and have only just seen this.

I haven't had chance to test it, but the clue to the problem is a space in the filename. The code in get_attachments.php replaces spaces with underscores, but it looks as though there's a mistake in my code that gets the contents of the file in process_attachments.php.

Try changing the following line (should be around line 52) in process_attachments.php:

$current_file = $destination . '/' . $_SESSION['att_id'] . $attached;

Change it to this:

$current_file = $destination . '/' . $_SESSION['att_id'] . str_replace(' ', '_', $attached);

I think that should fix it. If it does, we'll need to issue a correction to the book.

2 replies

David_Powers
David_PowersCorrect answer
Inspiring
October 10, 2010

Sorry, I've been up to my eyeballs working on the second edition of my "PHP Solutions", and have only just seen this.

I haven't had chance to test it, but the clue to the problem is a space in the filename. The code in get_attachments.php replaces spaces with underscores, but it looks as though there's a mistake in my code that gets the contents of the file in process_attachments.php.

Try changing the following line (should be around line 52) in process_attachments.php:

$current_file = $destination . '/' . $_SESSION['att_id'] . $attached;

Change it to this:

$current_file = $destination . '/' . $_SESSION['att_id'] . str_replace(' ', '_', $attached);

I think that should fix it. If it does, we'll need to issue a correction to the book.

bmmotionAuthor
Known Participant
October 10, 2010

That did work. Thank you David for your help. Look also at a post a week or so ago entitled User registration problem - Powers tutorial . There appears to be an omission in the book you should be aware of in the section "Inserting the user details withZend_Db." Great book though and I'm getting much use out of it already.

David_Powers
Inspiring
October 11, 2010

DW did not like the errata code provided at the other site. I copied and pasted it over the code I had and received a syntax error warning. The code that I have that doesn't give me that warning follows. email and password are transposed from your example, which may or may not be relevant:

$data = array('first_name'  => $_POST['first_name'],
                    'last_name' => $_POST['surname'],
                    'username'    => $_POST['username'],
                    'password'    => sha1($_POST['password']),
                    'email'    => $_POST['email']);

Thoughts?


Sorry about that. There was a typo in the code. There should have been a comma after $_POST['email']. I have corrected it now.

The different order of the columns makes no difference. What should have alerted you to the problem was the syntax checker in Dreamweaver CS5. Without the comma, the following line is flagged with a red marker.

As you grow more familiar with PHP, you'll learn to spot errors like this more easily. There's no excuse for me posting a "correction" that had a mistake in it, but even after years of working with PHP, the fingers do slip from time to time.

October 1, 2010

hmm... dejavu: problem described without supplied code. Tiring pattern forming. My guess is as the error message suggests: you do not have a directory to upload the files to as defined in the mentioned line of the code you failed to supply.

bmmotionAuthor
Known Participant
October 1, 2010

Sorry to offend, I'm really quite new and obviously dumb as a post with the technology (even forums like this). I'll try to do better more quickly. The process_attachments script referred to in the error message looks like this:

<?php
require_once('library.php');
$errors = array();
try {
  $public_key = 'Your_public_key';
  $private_key = 'Your_private_key';
  $recaptcha = new Zend_Service_ReCaptcha($public_key, $private_key);
  if (isset($_POST['send'])) {
    // validate the user input
    if (empty($_POST['recaptcha_response_field'])) {
      $errors['recaptcha'] = 'reCAPTCHA field is required';
    } else {
      $result = $recaptcha->verify($_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
      if (!$result->isValid()) {
        $errors['recaptcha'] = 'Try again';
      }
    }
    $val = new Zend_Validate_Alnum(TRUE);
    if (!$val->isValid($_POST['name'])) {
      $errors['name'] = 'Name is required';
    }
    $val = new Zend_Validate_EmailAddress();
    if (!$val->isValid($_POST['email'])) {
      $errors['email'] = 'Email address is required';
    }
    $val = new Zend_Validate_StringLength(10);
    if (!$val->isValid($_POST['comments'])) {
      $errors['comments'] = 'Required';
    }
    require_once('get_attachments.php');
    if (!$errors) {
       // create and send the email
       require_once('mail_connector.php');
       $mail = new Zend_Mail('UTF-8');
       $mail->addTo('me@example.com', 'A N Other');
       $mail->setFrom('webmaster@example.com', 'Zend Mail Test');
       $mail->setSubject('Comments from feedback form');
       $mail->setReplyTo($_POST['email'], $_POST['name']);
       $text = "Name: {$_POST['name']}\r\n\r\n";
       $text .= "Email: {$_POST['email']}\r\n\r\n";
       $text .= "Comments: {$_POST['comments']}";
       $html = '<html><head><title>';
       $html .= $mail->getSubject();
       $html .= '</title></head><body>';
       $html .= "<p><strong>Name: </strong><a href='mailto:{$_POST['email']}'>{$_POST['name']}</a></p>";
       $html .= '<p><strong>Comments: </strong>' . nl2br($_POST['comments']) . '</p>';
       $html .= '</body></html>';
       $mail->setBodyText($text, 'UTF-8');
       $mail->setBodyHtml($html, 'UTF-8');
       if (isset($_SESSION['attachments']) && !empty($_SESSION['attachments'])) {
          foreach($_SESSION['attachments'] as $attached) {
            $current_file = $destination . '/' . $_SESSION['att_id'] . $attached;
            $contents = file_get_contents($current_file);
            $att = $mail->createAttachment($contents);
            $att->filename = $attached;
            unlink($current_file);
          }
          unset($_SESSION['attachments']);
          unset($_SESSION['att_id']);
       }
       $success = $mail->send();
       if (!$success) {
         $errors = TRUE;
       }
    }
  }
} catch (Exception $e) {
  echo $e->getMessage();
}
?>

I've intentionally left out the recaptcha keys in the code here.

The get_attachments.php referred to in the above script looks like this:

<?php
session_start();
$destination = 'C:/upload_test';
$max_size = '50kB';
$not_allowed = 'exe,vbs,shs,pif,lnk,dll';
if (!isset($_SESSION['att_id'])) {
  $_SESSION['att_id'] = 'att' . time() .'-';
  $_SESSION['attachments'] = array();

  // set the destination for the upload
  $uploader = new Zend_File_Transfer_Adapter_Http();
  $uploader->setDestination($destination);
  // permit blank file fields
  $uploader->setOptions(array('ignoreNoFile' => TRUE));
  // set the validation criteria
  $uploader->addValidator('Size', FALSE, $max_size);
  $uploader->addValidator('ExcludeExtension', FALSE, $not_allowed);
 
  // get the details of the uploaded files
  $files = $uploader->getFileInfo();
  // loop through the files and deal with each file individually
  foreach($files as $file => $info) {
    // make sure a file has been uploaded
    if ($uploader->isUploaded($file)) {
      // get the file's name and replace spaces with underscores
      $filename = $uploader->getFileName($file, FALSE);
      if (!$uploader->isValid($file)) {
        $messages[] = "$filename exceeds $max_size or is not an acceptable type";
      } else {
        $attachment = $_SESSION['att_id'] . str_replace(' ', '_', $filename);
     
        $uploader->addFilter('Rename', array('target' => $attachment), $file);
        $success = $uploader->receive($file);
        // if the transfer failed, get the error messages
        if (!$success) {
          $messages[] = "$filename could not be attached";
        } else {
          // the transfer was OK, so tell the user what happened
          $messages[] = "$filename attached";
          $_SESSION['attachments'][] = $filename;
        }
      }
    }
  }
}

bmmotionAuthor
Known Participant
October 1, 2010

If someone is still willing and able to help, that would be great. This is my final hurdle I think with this project and it would be a huge timesaver to me to at least get put on a productive path to resolving this. Thanks very much.