0

Is it possible to use require and include_once inside a function.

I am trying to use sendGrid to send emails. I have created a function called sendMail.

somthing like this:

function sendEmail($to, $from, $subject, $message)
{

  // You need to install the sendgrid client library so run: composer require sendgrid/sendgrid
    require './vendor/autoload.php';
    // contains a variable called: $API_KEY that is the API Key.
    // You need this API_KEY created on the Sendgrid website.
    include_once('./credentials.php');

    $FROM_EMAIL = $from;
    $From_Name = $FROM_EMAIL;
    // they dont like when it comes from @gmail, prefers business emails
    $TO_EMAIL = $to;
    // Try to be nice. Take a look at the anti spam laws. In most cases, you must
    // have an unsubscribe. You also cannot be misleading.
    $subject = $subject;
    $from = new SendGrid\Email($From_Name, $FROM_EMAIL);
    $to = new SendGrid\Email(null, $TO_EMAIL);
    $htmlContent = $message;
    // Create Sendgrid content
    $content = new SendGrid\Content("text/html",$htmlContent);
    // Create a mail object
    $mail = new SendGrid\Mail($from, $subject, $to, $content);

    $sg = new \SendGrid($API_KEY);
    return $sg->client->mail()->send()->post($mail);
}

And I installed sendgrid library using composer to my libs folder. This folder has the functions.php file too but I get the following error:

Fatal error: require(): Failed opening required './vendor/autoload.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\samplepoject\libs\functions.php on line 65 

Just wondering how to call require and include_once inside a function? Can some one help me out?

Thanks!

user9163296
  • 37
  • 2
  • 7
  • using an `include` or `require` within a function should be fine, also see here: https://stackoverflow.com/q/21586313/3000771. So then the question is, where is the autoload.php file located with respect to the file containing the code you share in your post? In "samplepoject\vendor\"? – rolfv1 Jan 06 '18 at 02:11
  • Possible duplicate of [how to use require\_once inside function](https://stackoverflow.com/questions/16331221/how-to-use-require-once-inside-function) – Pyromonk Jan 06 '18 at 02:16
  • where is `.` in your project hierarchy ? you probably want to include from document root. – YvesLeBorg Jan 06 '18 at 02:32
  • Inside: C:\xampp\htdocs\samplepoject\libs\ - libs has functions.php and vendor folder too. – user9163296 Jan 06 '18 at 02:44

0 Answers0