Viewed   182 times

I am working to upload a file and then send it to myself as an attachment. I am new with php, I tried lookign up on the web for stuff and wrote this code.

    function mail_attachment($files, $path, $mailto, $subject, $message) {

$uid = md5(uniqid(time()));
$header = "MIME-Version: 1.0rn";
$header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";
$header .= "This is a multi-part message in MIME format.rn";
$header .= "Content-type:text/plain; charset=iso-8859-1rn";
$header .= "Content-Transfer-Encoding: 7bitrnrn";
$header .= $message."rnrn";

foreach ($files as $filename) { 

    $file = $path.$filename;
    $name = basename($file);
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    $content = chunk_split(base64_encode($content));

    $header .= "--".$uid."rn";
    $header .= "Content-Type: application/octet-stream; name="".$filename.""rn"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64rn";
    $header .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
    $header .= $content."rnrn";

$header .= "--".$uid."--";
if (@mail($mailto, $subject, $message, $header)) {
    echo "mail send ... OK";
} else {
    echo "mail send ... ERROR!";

   //Enter your email address here
  $mailto="[email protected]";
  $subject="Form Details";

   $FirstName = $_POST['firstName'] ;
   $LastName = $_POST['lastName'] ;
$EmailAdress= $_POST['emailAddress'] ;
   $ContactNumber= $_POST['contactNumber'] ;
   $ApartmentType= $_POST['apartmentType'] ;
   $ApartmentLocation = $_POST['apartmentLocation'] ;
   $CheckIn = $_POST['checkIn'] ;
   $CheckOut = $_POST['checkOut'] ;
   $NumberOfAdults = $_POST['numberOfAdults'] ;
   $NumberOfChildren = $_POST['numberOfChildren'] ;
   $TermsAndConditions =$_POST['termsAndConditions'];

   $required = array('firstName','lastName','emailAddress','contactNumber','apartmentType','apartmentLocation','checkIn','checkOut','numberOfAdults','numberOfChildren');

   $error = false;

   foreach($required as $field) {
     if (empty($_POST[$field])) {
       $error = true;

   if ($error) {
     echo "All fields are required.";

   if ( $TermsAndConditions=='disagree') {
     echo "Please agree to the terms and conditions";

    $message="First Name:t $FirstName nn" . 
"Last Name:t $LastNamenn". 
"Email Address:t $EmailAddress nn". 
"Contact Number:t $ContactNumber nn". 
"Apartment Types:t $ApartmentType nn". 
"Apartment Location:t $ApartmentLocation nn" .
"Check in:t $CheckIn nn" .
"Check out:t $CheckOut nn" .
"Number of Adults:t $NumberOfAdults nn" .
"Number of Children:t $NumberOfChildren nn";

   $uploaddir = './';
   foreach ($_FILES["documents"]["error"] as $key => $error) 
   if ($error == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["documents"]["tmp_name"][$key];
    $name = basename($_FILES["pictures"]["name"][$key]);
    move_uploaded_file($tmp_name, $uploaddir.$name);

   $path = $_SERVER['DOCUMENT_ROOT'];
   mail_attachment($files, $path, $mailto, $subject, $message);


I get an error for both the foreach:

  Warning: Invalid argument supplied for foreach() in /home/a4824849/public_html/PhpFile.php on line 88

 Warning: Invalid argument supplied for foreach() in /home/a4824849/public_html/PhpFile.php on line 12

What could possibly be wrong?



Foreach takes arrays and attributes each value of the array to the varname that you define. Invalid Argument simply means that the you did not provide a valid array.

For l.12, it simply means that you did not pass an array as the first arg to your function, which is due to your error line 88.

I would assume that your problem is that you haven't yet tried uploading a file and thus $_FILES is undefined. In my experience to use the $_FILES superglobal variable you usually have to upload a file via a form of enctype multi-part/formdata. To debug and check if it's defined do a var_dump or print_r on $_FILES before your foreach loop. As an added measure of security you might want to wrap said loop and your call to your mail_attachment function in an if (isset($_FILES))

Hope this helps

Tuesday, November 15, 2022

You're looking for the array_slice function:

array_slice() returns the sequence of elements from the array array as specified by the offset...

$lines = file(...);
$lines = array_slice($lines, -50);
Thursday, October 13, 2022

You should open and close your <rows/> in the books loop, and add a late check for odd books:

$count = 0;
foreach ($contents as $content) 
    $books      = $content["tags"];
    $book_image = $content['content_image'];
    $book_desc  = $content['content_social_description'];

    foreach ($books as $book) 
        if($count == 1)
            echo "<div class='et_pb_row'>";
        $book_name      = $book['tag_name'];
        $book_name_trim = str_replace(' ', '-', $book_name);
        <!-- Inside the Book Loop -->
        <div class='et_pb_column et_pb_column_1_2 books' style="background: url('<?php echo $book_image ;?>');">
            <h2><?php echo $book_name; ?></h2>
            <p><?php echo $book_desc; ?></p>
            <?php echo $count; ?>

        if ($count == 2)
            echo "</div>";
            $count = 0;


if ($count > 0)
    echo "</div>";

Doing so, your $count variable will be incremented only when foreach($books AS $book) loop is run (thus you have at least one book to print)

Thursday, October 20, 2022

you need to do a check before starting to iterate for the data, like: model code:

public function getAll() {
    $results = array();
    $this->db->select('bcode, bname, btel, badd');

    $query = $this->db->get();

    if($query->num_rows() > 0) {
        $results = $query->result();
    return $results;

view code:

if( !empty($results) ) {
    foreach($results as $row) {
        echo '<tr>';
        echo '<td>'.$row->bcode.'</td>';
        echo '<td>'.$row->bname.'</td>';
        echo '<td>'.$row->btel.'</td>';
        echo '<td>'.$row->badd.'</td>';
        echo '</tr>';
Sunday, September 18, 2022
function getSearchUniversity() {
  country = jQuery('[name=countryKey]').val();
  state = jQuery('[name=stateKey]').val();
  level= jQuery('[name=level]').val();
  degType= jQuery('[name=degType]').val();
    type: "POST",
    url:baseurl+ 'welcome/searchUnivtab', 
    cache: false,
    data: {countryKey: country, stateKey: state, level: level, degType: degType},
    error: function()
      //notify('Error: Your request could be processed.. try again..!!');
    success: function(html)
      return false;
Monday, November 21, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :