Skip to content

Instantly share code, notes, and snippets.

@xandros15
Created March 31, 2017 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xandros15/3c17a9c5961cca901bbfea3c226eca3b to your computer and use it in GitHub Desktop.
Save xandros15/3c17a9c5961cca901bbfea3c226eca3b to your computer and use it in GitHub Desktop.
example of contact form
<?php
/**
* Created by PhpStorm.
* User: xandros15
* Date: 2017-03-31
* Time: 02:26
*/
require_once __DIR__ . '/functions.php';
if ($errors = validateContactForm($_POST)) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['data' => $errors], JSON_PRETTY_PRINT);
} else {
if (sendMail($_POST)) {
http_response_code(200);
} else {
http_response_code(500);
}
}
{
"require": {
"swiftmailer/swiftmailer": "^5.4",
"respect/validation": "^1.1"
}
}
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "703e671afc9e967b11afc2ad24e615bc",
"content-hash": "62536cae59aa6ad837f15ec15c5e4898",
"packages": [
{
"name": "respect/validation",
"version": "1.1.12",
"source": {
"type": "git",
"url": "https://github.com/Respect/Validation.git",
"reference": "5ab87d1dd932872f6670136a513f72ff9ea41c67"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Respect/Validation/zipball/5ab87d1dd932872f6670136a513f72ff9ea41c67",
"reference": "5ab87d1dd932872f6670136a513f72ff9ea41c67",
"shasum": ""
},
"require": {
"php": ">=5.4",
"symfony/polyfill-mbstring": "^1.2"
},
"require-dev": {
"egulias/email-validator": "~1.2",
"malkusch/bav": "~1.0",
"mikey179/vfsstream": "^1.5",
"phpunit/phpunit": "~4.0",
"symfony/validator": "~2.6.9",
"zendframework/zend-validator": "~2.3"
},
"suggest": {
"egulias/email-validator": "Strict (RFC compliant) email validation",
"ext-bcmath": "Arbitrary Precision Mathematics",
"ext-mbstring": "Multibyte String Functions",
"fabpot/php-cs-fixer": "Fix PSR2 and other coding style issues",
"malkusch/bav": "German bank account validation",
"symfony/validator": "Use Symfony validator through Respect\\Validation",
"zendframework/zend-validator": "Use Zend Framework validator through Respect\\Validation"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"autoload": {
"psr-4": {
"Respect\\Validation\\": "library/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD Style"
],
"authors": [
{
"name": "Respect/Validation Contributors",
"homepage": "https://github.com/Respect/Validation/graphs/contributors"
}
],
"description": "The most awesome validation engine ever created for PHP",
"homepage": "http://respect.github.io/Validation/",
"keywords": [
"respect",
"validation",
"validator"
],
"time": "2017-03-14 09:44:11"
},
{
"name": "swiftmailer/swiftmailer",
"version": "v5.4.6",
"source": {
"type": "git",
"url": "https://github.com/swiftmailer/swiftmailer.git",
"reference": "81fdccfaf8bdc5d5d7a1ef6bb3a61bbb1a6c4a3e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/81fdccfaf8bdc5d5d7a1ef6bb3a61bbb1a6c4a3e",
"reference": "81fdccfaf8bdc5d5d7a1ef6bb3a61bbb1a6c4a3e",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"mockery/mockery": "~0.9.1",
"symfony/phpunit-bridge": "~3.2"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "5.4-dev"
}
},
"autoload": {
"files": [
"lib/swift_required.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Chris Corbyn"
},
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
}
],
"description": "Swiftmailer, free feature-rich PHP mailer",
"homepage": "http://swiftmailer.org",
"keywords": [
"email",
"mail",
"mailer"
],
"time": "2017-02-13 07:52:53"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.3.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "e79d363049d1c2128f133a2667e4f4190904f7f4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/e79d363049d1c2128f133a2667e4f4190904f7f4",
"reference": "e79d363049d1c2128f133a2667e4f4190904f7f4",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.3-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"time": "2016-11-14 01:06:16"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": []
}
<?php
/**
* Created by PhpStorm.
* User: xandros15
* Date: 2017-03-31
* Time: 01:06
*/
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Rules\Email;
use Respect\Validation\Rules\Length;
use Respect\Validation\Rules\StringType;
use Respect\Validation\Validator;
require_once __DIR__ . '/vendor/autoload.php';
/**
* @param array $form
*
* @return array of errors
*/
function validateContactForm(array $form): array
{
$errors = [];
$rules = [
'email' => (new Validator())->addRules([new Email()]),
'subject' => (new Validator())->addRules([new StringType(), new Length(4, 24)]),
'message' => (new Validator())->addRules([new StringType(), new Length(8, 255)]),
];
foreach ($rules as $key => $validator) {
/** @var $validator Validator */
try {
$validator->setName($key)->assert($form[$key] ?? null);
} catch (NestedValidationException $exception) {
$errors[$key] = $exception->getMessages();
}
}
if (validateReCaptcha($form['g-recaptcha-response'] ?? '')) {
$errors['g-recaptcha-response'][] = 'Zły kod recaptchy';
}
return $errors;
}
function validateReCaptcha(string $code): bool
{
$url = 'https://www.google.com/recaptcha/api/siteverify?' . http_build_query([
'secret' => (require_once __DIR__ . '/settings.php')['reCaptcha']['secret'],
'response' => $code,
]);
return ($content = file_get_contents($url)) && ($response = json_decode($content, true)) && $response['success'];
}
function getMailer(): Swift_Mailer
{
$config = (require_once __DIR__ . '/settings.php')['mailer'];
$transport = new Swift_SmtpTransport($config['host'], $config['port']);
$transport->setUsername($config['username']);
$transport->setPassword($config['password']);
return new Swift_Mailer($transport);
}
function prepareMail(array $params): Swift_Message
{
$config = (require_once __DIR__ . '/settings.php')['mailer'];
$mail = new Swift_Message(
$params['subject'],
$params['body'],
'text/plain',
'UTF-8'
);
$mail->setFrom($params['recipient']);
$mail->setReplyTo($params['recipient']);
$mail->setTo($config['email']);
return $mail;
}
function sendMail(array $params): bool
{
$mailer = getMailer();
//we can parse message
$params['body'] = $params['message'];
$params['recipient'] = $params['email'];
unset($params['message'], $params['email']);//free memory
return (bool) $mailer->send(prepareMail($params));
}
<?php
/**
* Created by PhpStorm.
* User: xandros15
* Date: 2017-03-31
* Time: 01:06
*/
require_once __DIR__ . '/functions.php';
if ($errors = validateContactForm($_POST)) {
$_SESSION['errors'] = $errors;
header('Location: /', 302); //redirect to form ofc
} else {
if (sendMail($_POST)) {
$_SESSION['alert'] = [
'message' => 'Wiadomość została wysłana',
'type' => 'success'
];
} else {
$_SESSION['alert'] = [
'message' => 'Usługa czasowo niedostępna',
'type' => 'error'
];
}
}
<?php
/**
* Created by PhpStorm.
* User: xandros15
* Date: 2017-03-31
* Time: 01:18
*/
return [
'reCaptcha' => [
'secret' => '',
],
'mailer' => [
'host' => '',
'port' => '',
'username' => '',
'password' => '',
'email' => '',
],
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment