I have a function that allows only expected data from form submissions. I was using it before and it was working fine but now when I try to use it. it throws an error: Warning: Invalid argument supplied for foreach() I've tried using is_array() function but that didn't fix the error. any idea why this happening.
Function
function allowed_post_params($allowed_params=[]) {
$allowed_array = [];
foreach ($allowed_params as $param) {
if (isset($_POST[$param])) {
$allowed_array[$param] = $_POST[$param];
} else {
$allowed_array[$param] = NULL;
}
}
return $allowed_array;
}
Use in Processing
if (is_post_request()) {
$post_params = allowed_post_params('email', 'username', 'password', 'country');
$email = $post_params['email'] ?? '';
$username = $post_params['username'] ?? '';
$password = $post_params['password'] ?? '';
$country = $post_params['country'] ?? '';
}
You are supplying 4 string arguments to the function.
$post_params = allowed_post_params('email', 'username', 'password', 'country');
It should be a single array:
$post_params = allowed_post_params(['email', 'username', 'password', 'country']);
Related
I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.
I'm trying to rebuild my PHP API with SlimPHP v3 + PDO. The problem is I'm stuck with retrieving attributes passed in POST method. Here is part of my index.php file, I decided just to echo the variable to test if it's working.
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
require_once '../includes/UserOperation.php';
require_once '../includes/TweetOperation.php';
$app = new \Slim\App([
'settings' => [
'displayErrorDetails' => true
]
]);
//---UserOperation.php---//
//registering a new user
$app->post('/register', function (Request $request, Response $response) {
if (isTheseParametersAvailable(array('name', 'email', 'password', 'picture_path'))) {
$requestData = $request->getParsedBody();
$name = $request->getParsedBody()['name'];
$email = $requestData['email'];
$password = $requestData['password'];
$picture_path = $requestData['picture_path'];
echo "Hello " .$name;
}
});
//function to check parameters
function isTheseParametersAvailable($required_fields)
{
$error = false;
$error_fields = "";
$request_params = $_REQUEST;
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
$response = array();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echo json_encode($response);
return false;
}
return true;
}
$app->run();
The link for my website looks for example like below,but $name variable that I'm trying to echo remains empty.
https://myweblink/register?name=test&email=test#mail.com&password=pass&picture_path=lolololo
Please someone help me :( and sorry for these beginner problem , its really strange , $stdobj works completely fine when it is in auth and first elseif , and strange thing is that second elseif has exactly the same code , but retunes laravel error Trying to get property of non-object . but it works in first elseif , why it says it is not an object in the last one !!!
$our_user = User::check_if_user_matches($username);
$stdobj = new \stdClass();
$stdobj = $our_user['usid'];
if (\Auth::attempt(['username' => $username, 'password' => $password])) {
$logdata = [];
$v = new Verta();
$logdata['logTime'] = $v->formatTime();
$logdata['logDate'] = $v->formatDate();
$logdata['logCode'] = '001';
$logdata['user_id'] = $stdobj->id;
$logs->insert($logdata);
return redirect()->intended('home');
} elseif ($our_user['usname'] == $username) {
$v = new Verta();
//$stdobj1 = $our_user['usid'];
$logdata = [];
$logdata['logTime'] = $v->formatTime();
$logdata['logDate'] = $v->formatDate();
$logdata['logCode'] = '003';
$logdata['user_id'] = $stdobj->id;
$logs->insert($logdata);
return redirect()->intended('login');
} elseif ($our_user['usname'] != $username) {
$v = new Verta();
//$stdobj1 = $our_user['usid'];
$logdata = [];
$logdata['logTime'] = $v->formatTime();
$logdata['logDate'] = $v->formatDate();
$logdata['logCode'] = '002';
$logdata['user_id'] = $stdobj->id;
$logs->insert($logdata);
return redirect()->intended('login');
} else {
return back()->withInput();
}
You need to assign value to your obejct. Add this line at top-
$stdobj1 = new \stdClass();
$stdobj1->id = $our_user['usid'];;
because it can't get the password , when there is no username . and you can find a password and compare it to the one in the database , this way :
$passes = \DB::table('users')->pluck('password');
foreach ($passes as $pass) {
if(\Hash::check($password, $pass)) {
$this_user_pass = $pass;
return view('MainPages.example',['pass' => $this_user_pass]);
}
}
Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database.
in my view :
<label>Trimestres :</label>
<div class="controls" >
<?php $options = array(
'trim1' => ' Premier trimestre (Janv,Fév,Mars)',
'trim2' => ' Deuxiéme trimestre (Avril,Mai,Juin)',
'trim3' => ' Troisiéme trimestre (Juill,Aout,Sept)',
'trim4' => ' Quatriéme trimestre (Oct,Nov,Déc)',
);
echo form_multiselect('trimestres', $options , $this->input->post('trimestres') ? $this->input->post('trimestres') : $participant_sport->trimestres, 'id="trim"'); ?>
</div>
</div>
in my controller :
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
The function array_from_post() is defined on application\core\MY_Model.php :
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
in my model :
public function get_new()
{
$participant_sport = new stdClass();
$participant_sport->matricule = '';
$participant_sport->nom = '';
$participant_sport->prenom = '';
$participant_sport->beneficiaire = '';
$participant_sport->sexe = '';
$participant_sport->telephone = '';
$participant_sport->date_naissance = '';
$participant_sport->date_inscription_sport = '';
$participant_sport->trimestres = '';
$participant_sport->sport_montant_paye = '';
$participant_sport->sport_debut_periode = '';
$participant_sport->sport_fin_periode = '';
return $participant_sport;
}
Any help Please? i think that must be an array but i don't know how to do it?
i thing that i must do something like that :
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
to insert more than one option selected in one row but i don't know how to do it in codeigniter
the get() function :
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
If select name (in HTML tag) is trimestres it will always remember last selection. Use trimestres[] as a name to get array with all selected values`
<select name="trimestres[]" multiple …
By the way:
I don't know how array_from_post() works but it has to change trimestres[] values to one string to save all of them in one column. It is hard to search/add/delete one value if all values are in one string. It is "SQL Antipattern". You could do another table in database for trimestres - one value in one row.
Edit:
It will change all arrays into string with elements connected by ,. Not tested.
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
// print_r($this->input->post($field));
if( is_array( $this->input->post($field) ) ) {
$data[$field] = join(",", $this->input->post($field));
} else {
$data[$field] = $this->input->post($field);
}
// print_r($data[$field]);
}
return $data;
}
Edit:
Not tested.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
// explode to array
// print_r($this->data['participant_sport']->trimestres); // test before explode
// $this->data['participant_sport']['trimestres'] = explode(",", $this->data['participant_sport']['trimestres']);
$this->data['participant_sport']->trimestres = explode(",", $this->data['participant_sport']->trimestres);
// print_r($this->data['participant_sport']->trimestres); // test after explode
} else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// rest of code
}
There is a easy way to solve this problem that I found today.
you have to serialize the $_POST['trimestres'] array just after array_form_post .
the this array will save to database as a serialize string.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$data['trimestres'] = serialize($_POST['trimestres']);
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
When you just need this data back form database just use php unserialize() function .
Hope it will help to do this easily ....
-thanks
I have a form being validated in the following manner:
//Clear all variables
$formCheck = '';
$rep = '';
$name = '';
$department = '';
$location = '';
$email = '';
$phone = '';
$type = '';
$drink = '';
$notes = '';
$lastVisited = '';
$nextVisit = '';
$clean_formCheck = '';
$clean_rep = '';
$clean_name = '';
$clean_department = '';
$clean_location = '';
$clean_email = '';
$clean_phone = '';
$clean_type = '';
$clean_drink = '';
$clean_notes = '';
$clean_lastVisited = '';
$clean_nextVisit = '';
function validateRep($rep){
...some code...
}
$formCheck = $_POST["formCheck"];
$rep = $_POST["rep"];
$name = $_POST["name"];
$department = $_POST["department"];
$location = $_POST["location"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$type = $_POST["type"];
$drink = $_POST["drink"];
$notes = $_POST["notes"];
$lastVisited = $_POST["lastVisited"];
$nextVisit = $_POST["nextVisit"];
if (validateRep($rep)){
$clean_rep = $rep;
}else{
echo "Invalid Rep";
exit();
}
//.....and so on......
I was wondering if it would be more efficient / cleaner to validate using an an array instead of individual variable? If so, how would I go about that, and how would I write the different validation functions all in one (eg. right now I have a separate function to validate each field), would it be possible with a loop through the array? i was experimenting and so far this is what I have:
$unclean['formCheck'] = $_POST["formCheck"];
$unclean['rep'] = $_POST["rep"];
$unclean['name'] = $_POST["name"];
$unclean['department'] = $_POST["department"];
$unclean['location'] = $_POST["location"];
$unclean['email'] = $_POST["email"];
$unclean['phone'] = $_POST["phone"];
$unclean['type'] = $_POST["type"];
$unclean['drink'] = $_POST["drink"];
$unclean['notes'] = $_POST["notes"];
$unclean['lastVisited'] = $_POST["lastVisited"];
$unclean['nextVisit'] = $_POST["nextVisit"];
$clean = array(
'rep', 'name', 'department', 'location', 'email', 'phone', 'type', 'drink', 'lastVisited', 'nextVisit',
);
but I'm not sure how to proceed from here.
I would use something along these lines... Just coded this very quickly, basically you create validation functions that match the post fields and return true or false if the validation passed. e.g. validate_department, validate_type, validate_drink, etc. Will work if your post data doesn't have any strange characters in (which so far it doesn't)
$post_fields = array('rep',
'name',
'department',
'location',
'email',
'phone',
'type',
'drink',
'lastVisited',
'nextVisit'
);
$validate = new Validate();
foreach ($post_fields as $post_var)
{
if (isset($_POST[$post_var]))
{
$validate->validate_data($post_var, $_POST[$post_var]);
}
}
if ($validate->all_fields_valid() === true)
{
echo 'congrats, all validation passed!';
}
else
{
echo 'oh no! error in validation process. please see below errors: <p>' .
$validate->get_error_msg() . '</p>';
}
And the validate class... Use $errorMsg to see the error messages should you run into any issues
class Validate
{
var $valid = 0,
$error = 0,
$errorMsg = '';
function validate_data($var, $data)
{
if (method_exists($this, 'validate_'.$var))
{
if (call_user_func(array($this, 'validate_'.$var), $data) === true)
{
$this->valid++;
}
else
{
$this->throwError('validation for: "'.$var.'" was not considered valid');
}
}
else
{
$this->throwError('validation function for: "'.$var.'" does not exist');
}
}
function throwError($msg = '')
{
if ($msg) $this->errorMsg .= $msg . '<br/>';
$this->error++;
}
function all_fields_valid()
{
if (!$this->error) return true;
return false;
}
/***********************************************
*************************************************
Custom validation functions go below here
Function format: validate_<postFieldName>
Returns: true or false if the data passed is valid or not
*************************************************
*************************************************/
function validate_type($type)
{
if (is_numeric($type)) return true;
return false;
}
function validate_lastVisited($data)
{
}
//etc...............
}
use filter_input.
$rep = filter_input(INPUT_POST, "rep", FILTER_SANITIZE_STRING);
$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING);
$department = filter_input(INPUT_POST, "department", FILTER_SANITIZE_STRING);
$location = filter_input(INPUT_POST, "location", FILTER_SANITIZE_STRING);
if (filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
}
Like that.