How to make the database connection to be utf-8 compliant in this setting? - phalcon

This is my index.php file ( the database is MySQL ) :
<?php
use Phalcon\Loader;
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
include("../app/config_const.php");
include("../app/config_inc.php");
include("../app/lib/PSR.php");
try {
// Register an autoloader
$loader = new Loader();
$loader->registerDirs(array(
'../app/controllers/',
'../app/models/'
))->register();
// Create a DI
$di = new FactoryDefault();
// Setup the database service
$di->set('db', function(){
$cnx = new DbAdapter(array(
"host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => BDD
));
return $cnx;
});
// Setup the view component
$di->set('view', function(){
$view = new View();
$view->setViewsDir('../app/views/');
$view->registerEngines(array(
".phtml" => 'Phalcon\Mvc\View\Engine\Volt'
));
return $view;
});
// Setup a base URI so that all generated URIs include the "phalcon" folder
$di->set('url', function(){
$url = new UrlProvider();
$url->setBaseUri('/resto/');
return $url;
});
//Register the flash service with custom CSS classes
$di->set('flash', function(){
$flash = new \Phalcon\Flash\Direct(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
return $flash;
});
//Handle the request
$app = new Application($di);
echo $app->handle()->getContent();
} catch(\Exception $e) {
echo "Exception: ", $e->getMessage();
}
?>
How to make the database setting to be utf-8 compliant in this case ?

Add encoding parameter to DB adapter as well:
// Setup the database service
$di->set('db', function(){
$cnx = new DbAdapter(array(
"host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => BDD,
"charset" => "utf8",
"options" => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
),
));
return $cnx;
});
Reference.
Also you can set encoding to your .htaccess file:
# your file could start with something like this
RewriteEngine On
RewriteBase /
# add next line
AddDefaultCharset utf-8

Ok I found the solution : I modified the ssp.class.php for the server processing :
static function sql_connect($sql_details) {
try {
$db = #new PDO("mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
$sql_details['user'],$sql_details['pass'],array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->exec("set names utf8");
$db->exec("set character_set_client='utf8'");
$db->exec("set character_set_results='utf8'");
$db->exec("set collation_connection='utf8_bin'");
}
catch (PDOException $e) {
self::fatal("An error occurred while connecting to the database. ".
"The error reported by the server was: ".$e->getMessage());
}
return $db;
}

Related

Laravel 9.x new Symphony Mailer Transport dynamic change

Before Laravel switched to Symfony Mailer I was able to check custom SMTP server response the following way:
try {
$transport = new Swift_SmtpTransport($request->smtp_server, $request->smtp_port, $request->secure_connection);
$transport->setUsername($request->smtp_username);
$transport->setPassword($request->smtp_password);
$mailer = new Swift_Mailer($transport);
$mailer->getTransport()->start();
return array(
'success' => true,
'statusCode' => 200,
'message' => 'Success.'
);
} catch (Swift_TransportException $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 500);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 500);
}
I am currently struggling to figure out how exactly to set the DSN(apparently this is the way to go) configuration and execute a transport connection test. I have been searching around for some documentation but was unable to find anything specific.
I too struggled with this issue. For the time being, you can send an actual email and catch the error if it does not send like below. The issue is that Symfony transport does not have start() and stop() methods like Swift Mailer did. I added the following code in a validator closure to not allow a user to save SMTP records unless the records were valid.
try{
$transport_factory = new \Symfony\Component\Mailer\Transport\Smtp\EsmtpTransportFactory;
$transport = $transport_factory->create(new \Symfony\Component\Mailer\Transport\Dsn(
!empty(request()->input('mail_encryption')) && request()->input('mail_encryption') === 'tls' ? ((request()->input('mail_port') == 465) ? 'smtps' : 'smtp') : '',
request()->input('mail_host'),
request()->input('mail_username'),
request()->input('mail_password'),
request()->input('mail_port')
));
$mailer = new \Symfony\Component\Mailer\Mailer($transport);
$email = (new \Symfony\Component\Mime\Email())
->from('noreply#domain.com')
->to($user->email)
->subject('Test Email')
->text("Email Test was Successful");
$mailer->send($email);
} catch (\Symfony\Component\Mailer\Exception\TransportException $e) {
$fail($e->getMessage());
} catch (\Exception $e) {
$fail($e->getMessage());
}

Lumen Google reCAPTCHA validation

I already seen some tuts and example about it and I have implemented it somehow.
Method in controller looks like this:
The logic used is just php and I would like to use more a lumen/laravel logic and not just simple vanilla php. Also I have tried and did not worked anhskohbo / no-captcha
public function create(Request $request)
{
try {
$this->validate($request, [
'reference' => 'required|string',
'first_name' => 'required|string|max:50',
'last_name' => 'required|string|max:50',
'birthdate' => 'required|before:today',
'gender' => 'required|string',
'email' => 'required|email|unique:candidates',
'g-recaptcha-response' => 'required',
]);
//Google recaptcha validation
if ($request->has('g-recaptcha-response')) {
$secretAPIkey = env("RECAPTCHA_KEY");
// reCAPTCHA response verification
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$request->input('captcha-response'));
$response = json_decode($verifyResponse);
if ($response->success) {
//Form submission
//Saving data from request in candidates
$candidate = Candidate::create($request->except('cv_path'));
$response = array(
"status" => "alert-success",
"message" => "Your mail have been sent."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Robot verification failed, please try again."
);
}
}
} catch(Exception $e) {
return response()->json($e->getMessage());
}
return response()->json(['id' => $candidate->id, $response]);
}
Okey. Google has an package for this:reCAPTCHA PHP client library
just: composer require google/recaptcha "^1.2"
and in your method inside controller:
$recaptcha = new \ReCaptcha\ReCaptcha(config('app.captcha.secret_key'));
$response = $recaptcha->verify($request->input('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
if ($response->isSuccess()) {
//Your logic goes here
} else {
$errors = $response->getErrorCodes();
}
config('app.captcha.site_key') means that I got the key from from config/app.php and there from .env file.
If you have not config folder, you should create it, also create app.php file same as in laravel.

Phalcon 4 multi module backend not loading

I'm in windows using php-7.4.1 Architecture-x64, phalcon - 4.0.2, psr - 0.7.0 and follow instruction from 'https://docs.phalcon.io/4.0/en/application' but the problem is its always render frontend module & its view. I'm unable to find out what i'm doing wrong?
[Index.php]
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;
$di = new FactoryDefault();
$di->set('router',function () {
$router = new Router(false);
$router->setDefaultModule('frontend');
$router->add('/login',
[
'module' => 'backend',
'controller' => 'index',
'action' => 'index',
]
);
$router->add('/admin/products/:action',
[
'module' => 'backend',
'controller' => 'index',
'action' => 1,
]
);
return $router;
}
);
$application = new Application($di);
$application->registerModules(
[
'frontend' => [
'className' => \Multiple\Frontend\Module::class,
'path' => '../apps/frontend/Module.php',
],
'backend' => [
'className' => \Multiple\Backend\Module::class,
'path' => '../apps/backend/Module.php',
],
]
);
try {
$response = $application->handle($_SERVER["REQUEST_URI"]);
$response->send();
} catch (\Exception $e) {
echo $e->getMessage();
}
[Backend module]
<?php
namespace Multiple\Backend;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Di\DiInterface;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;
class Module implements ModuleDefinitionInterface
{
public function registerAutoloaders(DiInterface $di = null)
{
$loader = new Loader();
$loader->registerNamespaces(
[
'Multiple\Backend\Controllers' => '../apps/backend/controllers/',
'Multiple\Backend\Models' => '../apps/backend/models/',
]
);
$loader->register();
}
public function registerServices(DiInterface $di)
{
$di->set('dispatcher',function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace('Multiple\Backend\Controllers');
return $dispatcher;
}
);
$di->set('view',function () {
$view = new View();
$view->setViewsDir('../apps/backend/views/');
return $view;
}
);
}
}
[Index Controller]
<?php
namespace Multiple\Backend\Controllers;
use Phalcon\Mvc\Controller;
class IndexController extends Controller
{
public function indexAction()
{
return '<h1>Back Controller!</h1>';
}
}
Did you set your namespaces in the frontend module as well? Like you did with registerAutoloaders in the backend.
Make sure you have registered your new module in
../app/bootstrap_web.php around line 47 which looks as shown below
$application->registerModules([
'frontend' => ['className' => 'MyApp\Modules\Frontend\Module'],
// <--- add your new module here --->
]);
and that your module class is also registered in the loader at ../app/config/loader.php around line 18 which looks as shown below
$loader->registerClasses([
'MyApp\Modules\Frontend\Module' => APP_PATH . '/modules/frontend/Module.php',
// <--- Add your new module class here --->
]);
Always keep an eye on your namespaces. I hope it helps.

Upload multiple files yii2

Tell me where I was wrong, everything is tried
my view file:
echo FileInput::widget([
'model' => $model,
'attribute' => 'files[]',
'options' => ['multiple' => true]
]);
Also i added
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
enctype option to form element
Model:
i add two variables as property:
public $files; // files instance
public $serialize; // set string which store the files
in rules
serialize as string, and files:
[['files'], 'file', 'skipOnEmpty' => true, 'extensions' => 'gif, jpg, png, pdf, doc, docx', 'maxFiles' => 10],
and controller action:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$oldFiles = $model->serialize;
$files = UploadedFile::getInstance($model, 'files');
if($files === false){
$model->serialize = $oldFiles;
} else {
$serialize = [];
if($model->validate()){
foreach($files as $file){
$ext = end((explode(".", $file)));
$filename = Yii::$app->security->generateRandomString().".{$ext}";
$serialize[] = $filename;
$file->saveAs(Yii::$app->basePath . '/web/image/' . $filename);
}
} else {
}
//print_r($model->getErrors()); die();
$model->serialize = serialize($serialize);
}
$model->save();
return $this->redirect(['view', 'id' => $model->news_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
So, $files is empty, why?
also i get a "4" code error in $_FILES array
It should be getInstances for multiple files.
$files = UploadedFile::getInstances($model, 'files');

How to connect multiple database in phalcon framework

i have to database namely master and xyz ,in that i required to connect both database in application .
so is it possible to connect multiple database in one application and yes then how.?
Set your connections in DI:
//This service returns a MySQL database
$di->set('dbMaster', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "",
"password" => "",
"dbname" => ""
));
});
//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "",
"password" => "",
"dbname" => ""
));
});
In your models choose the connection:
public function initialize()
{
$this->setConnectionService('dbMaster');
//or
$this->setConnectionService('dbSlave');
}
Another way to do this, using the same configuration
//This service returns a MySQL database
$di->set('dbMaster', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "",
"password" => "",
"dbname" => ""
));
});
//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "",
"password" => "",
"dbname" => ""
));
});
In your model set
public function initialize()
{
$this->setReadConnectionService('dbSlave');
$this->setWriteConnectionService('dbMaster');
$this->setSource('table_name');
}
If you use transaction, remember in the injector dependency to change
$di->set('dbMaster' ....
For
$di->setShared('dbMaster'....
And the rest is the same