Get only a specified name of email - php

I have a problem with preg_math. So I have this methode :
public function filterUsers($a_users){
$a_authorizedEmail = array(
'#test.com',
'#test1.com'
);
$a_response = array();
foreach ($a_users as $user) {
if(false !== $email_user = EmailRepository::getEmail($user['id'])){
foreach($a_authorizedEmail as $email){
echo $email_user;
if(preg_match($email, $email_user)){
$a_response[]= $user;
}
}
}
}
return $a_response;
}
The array with $a_users : I have a user with email hcost#test.com. But in the return the array is empty. Probably I doen't made a correct verification. Please help me

Do this:
public function filterUsers($a_users){
$a_authorizedEmail = array(
'#test.com',
'#test1.com'
);
$pattern = "/".implode("|",$a_authorizedEmail)."$/"; //Note the "/" start and end delimiter as well as the $ that indicates end of line
$a_response = array();
foreach ($a_users as $user) {
$email_user = EmailRepository::getEmail($user['id']);
if(false !== $email_user){
echo $email_user;
if(preg_match($pattern, $email_user)){
$a_response[]= $user;
}
}
}
return $a_response;
}

Related

How to pass values from a assigned variable to view?

I wanted to pass some values to the view.
The $result may be 0 or 1 or '' and I tried to use this below code:
public function whatwedo($result='')
{
$result = array();
$result['status'] = $result;
$this->load->view('admin/whatwedo',$result);
}
public function add_whatwedo()
{
//$this->load->library('form_validation');
$this->form_validation->set_rules('text-input','Title','required');
if($this->form_validation->run() != true)
{
$result = 0;
$this->whatwedo($result);
}
else
{
$this->load->model('admin_model');
$result = $this->admin_model->ins_whatwedo($this->input->post());
//print_r($result);exit();
$this->whatwedo($result);
}
}
And in the view:
<?php
print_r($status);
?>
But, the $status is Array ( )
The problem is this line:
$result = array();
Because now the $result variable is an empty array so when you create the index status on result you assign it an empty array.
To fix you can do something like:
public function whatwedo($input = '')
{
$result['status'] = $input;
$this->load->view('admin/whatwedo', $result);
}
or even...
public function whatwedo($input = '')
{
$this->load->view('admin/whatwedo', ["status" => $input]);
}

Symfony- passing post params returns the same

I defined my postParams where I want to pass "hash" value from db.
What I am trying to accomplish is that if hash exists in my Session table to return TRUE and if not to return FLASE.
Problem is my code always returns TRUE.
What I am missing?
$postData = $this->requirePostParams(['hash']);
$this->container->get('app')->formService(
$this->data['hash']
);
if ($postData['hash']) {
$hash = $this->get('app')->getSessionRepository()->find($this->data['hash']);
if (!$hash) return false;
} else {
return true;
}
And my requirePostParams works fine! (tested on other functions)
protected function requirePostParams($params) {
$currentRequest = $this->get('request_stack')->getCurrentRequest();
$postData = $currentRequest->request->all();
$postContent = json_decode($currentRequest->getContent(), true);
if(!empty($postContent)) $postData = $postContent;
$this->data = $postData;
$missingParams = [];
foreach ($params as $param) {
if (!array_key_exists($param, $postData)) {
$missingParams[] = $param;
}
}
}
And my service:
$findHash = $this->getSessionRepository()->findOneBy([
'hash' => $hash
]);
As xmike mentioned in comments, function requirePostParams returns nothing. That's why $postData['hash'] is never set.
Try to replace $postData['hash'] with $this->data['hash']:
$this->requirePostParams(['hash']);
$this->container->get('app')->formService(
$this->data['hash']
);
if ($this->data['hash']) {
$hash = $this->get('app')->getSessionRepository()->find($this->data['hash']);
if (!$hash) return false;
} else {
return true;
}

I think I found a bug with setValue from ReflectionProperty

I'm working on a function to recursively remove arrays and objects recursively. The problem is that certain recursions may be inside private properties of objects.
below is what I tried as well as the entries I tried to use.
this is my entrie
class TestOBJ{
private $fooClosure = null;
public $bar = 5;
private $myPrivateRecursion = null;
private $aimArrayAndContainsRecursion = [];
public function __construct()
{
$this->fooClosure = function(){
echo 'pretty closure';
};
}
public function setMyPrivateRecursion(&$obj){
$this->myPrivateRecursion = &$obj;
}
public function setObjInsideArray(&$obj){
$this->aimArrayAndContainsRecursion[] = &$obj;
}
}
$std = new stdClass();
$std->std = 'any str';
$std->obj = new stdClass();
$std->obj->other = &$std;
$obj = new TestOBJ();
$obj->bar = new TestOBJ();
$obj->bar->bar = 'hey brow, please works';
$obj->bar->setMyPrivateRecursion($std);
my entrie is var $obj
and this is my function / solution
function makeRecursionStack($vector, &$stack = [], $from = null)
{
if ($vector) {
if (is_object($vector) && !in_array($vector, $stack, true) && !is_callable($vector)) {
$stack[] = &$vector;
if (get_class($vector) === 'stdClass') {
foreach ($vector as $key => $value) {
if (in_array($vector->{$key}, $stack, true)) {
$vector->{$key} = null;
} else {
$vector->{$key} = $this->makeRecursionStack($vector->{$key}, $stack, $key);
}
}
return $vector;
} else {
$object = new \ReflectionObject($vector);
$reflection = new \ReflectionClass($vector);
$properties = $reflection->getProperties();
if ($properties) {
foreach ($properties as $property) {
$property = $object->getProperty($property->getName());
$property->setAccessible(true);
if (!is_callable($property->getValue($vector))) {
$private = false;
if ($property->isPrivate()) {
$property->setAccessible(true);
$private = true;
}
if (in_array($property->getValue($vector), $stack, true)) {
$property->setValue($vector, null);
} else {
//if($property->getName() === 'myPrivateRecursion' && $from === 'bar'){
//$get = $property->getValue($vector);
//$set = $this->makeRecursionStack($get, $stack, $property->getName());
//$property->setValue($vector, $set);
//pre_clear_buffer_die($property->getValue($vector));
//}
$property->setValue($vector, $this->makeRecursionStack($property->getValue($vector), $stack, $property->getName()));
}
if ($private) {
$property->setAccessible(false);
}
}
}
}
return $vector;
}
} else if (is_array($vector)) {
$nvector = [];
foreach ($vector as $key => $value) {
$nvector[$key] = $this->makeRecursionStack($value, $stack, $key);
}
return $nvector;
} else {
if (is_object($vector) && !is_callable($vector)) {
return null;
}
}
}
return $vector;
}
The place where I have comments is where I noticed the problem. if the If is not commented there $get would receive a stdClass that has recursion and this works perfectly and $set would receive the stdClass without recursion. In that order.
$get =
$set =
After this lines
$property->setValue($vector, $set);
pre_clear_buffer_die($property->getValue($vector));
i obtain this
I try to put other value like an bool or null inside property and after set the $set but it's not works.
P.S: pre_clear_buffer_die kill php buffer, init other buffer and show var inside a <pre> after exit from script. Is an debugger function.

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database

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

Categories