0

I make a php page in which i get the files array and count array element, i want to apply loop and loop work until count like if count=3,then code run 3 times and 3 files uploaded.

Here is my code:

apply_now.tpl

{literal}
<script>
    function applySubmit() {
        $("#ApplicationForm").hide();
        $("#ProgressBar").show();
        $("#applyForm").ajaxSubmit({
            url: $("#applyForm").attr("action"),
            type: "POST",
            success: function (data) {
                $("#messageBox").html(data);
            }
    });
    return false;
}
$(document).ready(function() {
    $("#applyForm").jqTransform();
});
</script>
{/literal}

<div id="ProgressBar" style="display:none"><img src="{$GLOBALS.site_url}/system/ext/jquery/progbar.gif" alt="[[Please wait ...]]" />[[Please wait ...]]</div>

<div id="ApplicationForm">
{if $is_data_submitted && !$errors}
    <p class="message">[[You applied successfully]]</p>
{else}
    {foreach from=$errors key=error_code item=error_message}
            <p class="error">
                {if $error_code  eq 'EMPTY_VALUE'} [[Enter Security code]]
                {elseif $error_code eq 'NOT_VALID'} [[Security code is not valid]]
                {elseif $error_code eq 'SEND_ERROR'} [[There was an error while sending your application.]]
                {else}[[{$error_message}]]
                {/if}
            </p>
    {/foreach}
    {include file='field_errors.tpl'}
    <form method="POST" enctype="multipart/form-data" action="{$GLOBALS.site_url}/apply-now/" id="applyForm">
        <input type="hidden" name="is_data_submitted" value="1">
        <input type="hidden" name="listing_id" value="{$listing_id}">
        {if NOT $GLOBALS.current_user.logged_in}
            <fieldset>
                <div class="inputName">[[Your name]]:</div>
                <div class="inputField"><input type="text" name="name" value="{$request.name}" /></div>
            </fieldset>
            <fieldset>
                <div class="inputName">[[Your e-mail]]:</div>
                <div class="inputField"><input type="text" name="email" value="{$request.email}" /></div>
            </fieldset>
        {/if}
        <fieldset>
            <div class="inputName">[[Cover letter (optional)]]:</div>
            <div class="inputField"><textarea name="comments" rows="5">{$request.comments}</textarea></div>
        </fieldset>
        {if $GLOBALS.current_user.logged_in && $resume}
            <fieldset>
                <div class="inputName">[[Select your resume]]:</div>
                <div class="inputField">
                    <select name="id_resume[]" multiple="multiple">
                        <option value="0" selected="selected">[[Select your resume]]</option>
                        {html_options options=$resume selected=$request.id_resume}
                    </select>
                    <br />or
                </div>
            </fieldset>
        {/if}
        <fieldset>
            <div class="inputName">[[Attach your resume]]:</div>
            <div class="inputField"><input type="file" name="file_tmp[]" multiple /></div>
        </fieldset>
        {if $isCaptcha == 1}
            <fieldset>
                <div class="inputName">[[$captcha.caption]]:</div>
                <div class="inputField">{input property=$captcha.id object=$captchaObject}</div>
            </fieldset>
        {/if}
        <input type="hidden" name="anonymous" value="1" />
        {if $form_fields}
            <fieldset>
                {include file="questionnaire.tpl" form_fields=$form_fields}
            </fieldset>
        {/if}
        <fieldset>
            <div class="inputName">&nbsp;</div>
            <div class="inputButton"><input id="SubmitButton" type="submit" value="[[Send]]" onclick="return applySubmit();"/></div>
        </fieldset>
    </form>
{/if}
</div>

and here is my apply_now.php file code:

 <?php

 class SJB_Classifieds_ApplyNow extends SJB_Function
 {
public function isAccessible()
{
    $this->setPermissionLabel('apply_for_a_job');
    return parent::isAccessible();
}

public function execute()
{
    $errors = array();
    $field_errors = array();
    $tp = SJB_System::getTemplateProcessor();
    $loggedIn = SJB_UserManager::isUserLoggedIn();
    $current_user_sid = SJB_UserManager::getCurrentUserSID();

    $controller      = new SJB_SendListingInfoController($_REQUEST);
    $isDataSubmitted = false;
    $isCaptcha       = 0;
    if (SJB_PluginManager::isPluginActive('CaptchaPlugin') && SJB_System::getSettingByName('contactUserCaptcha') == 1) {
        $isCaptcha = 1;
    }
    $captcha      = new SJB_Captcha($_REQUEST, 'modal');
    $captcha_form = SJB_ObjectMother::createForm($captcha);
    $captcha_form->registerTags($tp);
    $tp->assign('captcha', array_pop($captcha_form->form_fields));
    $tp->assign('captchaObject', $captcha);

    $jobInfo = SJB_ListingManager::getListingInfoBySID($controller->getListingID());
    if ($controller->isListingSpecified()) {
        if ($controller->isDataSubmitted()) {
            $captcha_errors = array();
            if ($isCaptcha && !$captcha_form->isDataValid($captcha_errors)) {
                foreach ($captcha_errors as $error)
                    $errors[$error] = true;
            }
            else {
                // получим уникальный id для файла в uploaded_files

                $file_id_current = 'application_' . md5(microtime());
                $upload_manager = new SJB_UploadFileManager();
                $upload_manager->setFileGroup('files');
                $upload_manager->setUploadedFileID($file_id_current);
                for($i = 0; $i < count($_FILES['file_tmp']['name']); $i++){

$file_name = $upload_manager->uploadFile($_FILES['file_tmp']['name'][$i]);
}
                $id_file = mysql_insert_id();

                $post = $controller->getData();
                $listingId = 0;


                $mimeType = isset($_FILES['file_tmp']['type']) ? $_FILES['file_tmp']['type'] : '';

                if (isset($_FILES['file_tmp']['size']) && $file_name != '' && $_FILES['file_tmp']['size'] == 0) {
                    $errors['FILE_IS_EMPTY'] = 'The uploaded file should not be blank';
                }

                if (!empty($_FILES['file_tmp']['name'])){
                    $fileFormats = explode(',',SJB_System::getSettingByName('file_valid_types'));
                    foreach ( $_FILES['file_tmp']['name'] as $key => $file ) {
                        $fileInfo = pathinfo($_FILES['file_tmp']['name'][$key]);
                        if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
                            $errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
                        }
                    }
                }

                if ($file_name == '' && $listingId == 0) {
                    $canAppplyWithoutResume = false;
                    SJB_Event::dispatch('CanApplyWithoutResume', $canAppplyWithoutResume);
                    if (!$canAppplyWithoutResume) {
                        $errors['APPLY_INPUT_ERROR'] = 'Please select file or resume';
                    }
                }
                else if (SJB_Applications::isApplied($post['submitted_data']['listing_id'], $current_user_sid) && !is_null($current_user_sid)) {
                    $errors['APPLY_APPLIED_ERROR'] = 'You already applied';
                }

                $res = false;
                $listing_info = '';
                $notRegisterUserData = $_POST;
                $score = 0;
                // для зарегестрированного пользователя получим поля email и name
                // для незарегестрированных - поля name и email приходят с формы

                    if(!empty($file_name))
                        $file_name = 'files/files/'. $file_name;
                    if (!SJB_Notifications::sendApplyNow($post, $file_name, $listing_info, $current_user_sid, $notRegisterUserData, $score))
                        $errors['SEND_ERROR'] = true;



    $tp->assign('request', $_REQUEST);
    $tp->assign('isCaptcha', $isCaptcha);
    $tp->assign('errors', $errors);
    $tp->assign('listing_id', $controller->getListingID());
    $tp->assign('is_data_submitted', $isDataSubmitted);
    $tp->display('apply_now.tpl');
}
 }

Thanks in Advance

3
  • Anyone who apply loop in my code and loop end at count Commented Mar 12, 2014 at 8:04
  • Can you try to explain better what you want? because I can't understand most of what you say, like "apply loop" or the error "you already applied" Commented Mar 12, 2014 at 8:40
  • i want to select more than one files in select box and then these value count in apply_now.php i want to apply same job with different resumes that i selected from select box Commented Mar 12, 2014 at 8:48

3 Answers 3

1

example.html

<!DOCTYPE html>
<html>
    <head>
    </head>
<body>
    <form action="my_parser.php" method="post" enctype="multipart/form-data">
        <p><input type="file" name="file_array[]"></p>
        <p><input type="file" name="file_array[]"></p>
        <p><input type="file" name="file_array[]"></p>
        <input type="submit" value="Upload all files">
    </form>
</body>
</html>

my_parser.php

<?php
    if(isset($_FILES['file_array'])){
        $name_array = $_FILES['file_array']['name'];
        $tmp_name_array = $_FILES['file_array']['tmp_name'];
        $type_array = $_FILES['file_array']['type'];
        $size_array = $_FILES['file_array']['size'];
        $error_array = $_FILES['file_array']['error'];
        for($i = 0; $i < count($tmp_name_array); $i++){
            if(move_uploaded_file($tmp_name_array[$i], "test_uploads/".$name_array[$i])){
                echo $name_array[$i]." upload is complete<br>";
            } else {
                echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
            }
        }
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

1

If you add the multiple attribute to your <input> tag in html, your files will be available in PHP as an array, under $_FILES["file_tmp"].

HTML

<input type="file" accept="image/*" name="file_tmp[]" multiple>

PHP

for($i = 0; $i < count($_FILES["file_tmp"]["name"]); $i++){
    //your upload code

    //You can access your file as following:
    $filename = $_FILES["file_tmp"]['tmp_name'][$i];
}

In the future, please do not post your entire code, but only the relevant snippet(s). Noone wants to read through all of that code just to find your issue.

5 Comments

How did it not work? Did it give any error? Please try yourself what causes it to not work. Also, why did you re-add the entire block of code? You will not get a lot of people to help you because noone wants to read through 1000 lines of code to find the 1 important line of code. Furthermore, don't add tags that are irrelevant to the question.
i updated my code plz see my code i include your code in my code but no file uploading
@Arif Can you remove all of the irrelevant code? I don't want to waste 15 minutes trying to find what you changed.
@Arif And do you get any error? How exactly is it "not working"?
If the answer was nice enough to accept, maybe it is nice enough for you to also upvote it @MuhammadArif
1

A slight changes in above mentioned code..

for($i = 0; $i < count($_FILES["file_tmp"]["name"]); $i++){     
   $filename[] = $_FILES["file_tmp"]['tmp_name'][$i];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.