PHP Captcha – Session from generated image ist not stored

I have a form that generated a captcha, which of course will be checked afterwards. This also worked great in my test environment.

Now i have integrated the form in a onlineshop and it doesn’t work. The image for the captcha is generated. But apparently the security code whoich is generated in captcha.ph is not saved in the SESSION.

This is the code I use to insert the image:

<?
session_start();
?>
<img src="/media/content/captcha.php?RELOAD=" alt="Captcha" title="Klicken, um das Captcha neu zu laden" onclick="this.src+=1;document.getElementById('captcha_code').value='';" width="130px" height="38px" />
<input type="text" name="captcha_code" id="captcha_code" class="form-control"/>

<?
echo 'Test: '.$_SESSION['captcha_spam'].'';
?>

This is the Code from the capcha.php

<?
#Ersetellt eine Session, wenn dies noch nicht passiert ist.
session_start();
#Setzt das bestehende Captcha zurück.
unset($_SESSION['captcha_spam']);

#Allgemeine Variablen für das Captcha-Bild
$captcha_bg_img     = 'https://akkurato.de/media/content/etl-formular/bg_captcha.png';          #Pfad zum Hintergrundbild
$captcha_over_img   = 'https://akkurato.de/media/content/etl-formular/bg_captcha_over.png'; #Pfad zum Bild, was über das Captcha gelegt wird
$font_file = $_SERVER["DOCUMENT_ROOT"].'/public/fonts/KFOlCnqEu92Fr1MmSU5fBBc9.ttf';
#$font_file             = 'https://akkurato.de/public/fonts/KFOlCnqEu92Fr1MmSU5fBBc9.ttf';
#$font_file             = dirname(__FILE__).'/railway-webfont.ttf'; #Pfad zur Schriftdatei
$font_size          = 25;                                       #Schriftgröße
$text_angle         = mt_rand(0, 5);                            #Schriftwinkel (Werte zwischen 0 und 5)
$text_x             = mt_rand(0, 18);                           #X-Position (Werte zwischen 0 und 18)
$text_y             = 35;                                       #Y-Position
$text_chars         = 5;                                        #Länge des Textes
$text_color         = array(0, 0 , 0);                          #Textfarbe (R, G, B)
    
#Generiert einen zufälligen String.
#Verwendet keine 0, 1, I, O da sich diese ähnlich sehen.
function rand_string($length=5) {
    $letters = array_merge(range('A', 'H'), range('J', 'N'), range('P', 'Z'), range(2, 9));
    $lettersCount = count($letters) - 1;        
    $result = '';
        for ($i = 0; $i < $length; $i++) {
        $result .= $letters[mt_rand(0, $lettersCount)];
        }
    return $result;
}

#Generiert einen zufälligen Text.
$text = rand_string($text_chars);
$_SESSION['captcha_spam'] = $text;
    
#Header: Mitteilen, dass es sich um ein Bild handelt und dass dieses nicht im Cache gespeichert werden soll.
header('Expires: Mon, 26 Jul 1990 05:00:00 GMT');
header("Last-Modified: ".date("D, d M Y H:i:s")." GMT");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Content-type: image/png');
    
#Captcha Bild erstellen, Text schreiben & Bild darüber legen.
$img = ImageCreateFromPNG($captcha_bg_img);
$text_color = ImageColorAllocate($img, $text_color[0], $text_color[1], $text_color[2]);
imagettftext($img, $font_size, $text_angle, $text_x, $text_y, $text_color, $font_file, $text);
imagecopy($img, ImageCreateFromPNG($captcha_over_img), 0, 0, 0, 0, 140, 40);
    
#Ausgabe und Löschen des Bildes.
imagepng($img); 
imagedestroy($img); 
?>

Both files are in the same directory.

What can be the reason that I can’t print the content of the session? All other sessions where print. This Code worked without any problems on my test system. It is now integrated into a shop system (not as an iFrame!), could it be due to a cache system or something?

I had inserted the file with and without the URL (https:://), but there was no difference either.

I used the search function and couldn’t find any solution.

Post request to firebase with curl in PHP return false

I’m trying to send a POST request in server to fcm.googleapis.com/fcm/send but curl return false after amount of time.

$url = 'https://fcm.googleapis.com/fcm/send';

// Set the FCM server key for your Firebase project
$server_key = '<FCM server key>';

// Prepare the message payload in JSON format
$message = array(
    'to' => '<FCM token>',
    'notification' => array(
        'title' => 'New Message',
        'body' => 'Hello, this is a test message'
    )
);
$fields = json_encode($message);

// Set the cURL request headers
$headers = array(
    'Authorization: key=' . $server_key,
    'Content-Type: application/json'
);

$ch = curl_init();

// Set the cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, false);
// Execute the cURL request
$result = curl_exec($ch);

The value of $resulat will be false after call.

I tried openssl s_client -connect fcm.googleapis.com:443
and it just return CONNECTED and nothing else.

and also curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Attempt to read property “nama” on array [closed]

I’m beginner in laravel, when I put stats table in blade I got this warning

Attempt to read property "nama" on array

This is Controller

public function show(Paslon $id)
    {
       //return "<h1> Saya siswa $id </h1>";
        $data ['data']= Paslon::where('id',$id);
        return view('/show')->with('data', $data);
    } 

This is view:

@extends('layouts.navbar')

@section('content1')

    <div>   
        
            <a href="/paslon" class="btn btn-secondry"><< Kembali</a>
            <h1></h1>
            <p>
                <b>Dapil</b>{{$data->nama}}
            </p>

            <p>
                <b>Fraksi</b>{{$data->fraksi}}
            </p>
            
    </div>

@endsection()

please help me in solving this problem

In frontend, how to deserialize data serialized by php?

I am pulling some data from a database using Graphql, but I noticed that some data are actually serialized by PHP,I looked for a package to quickly deserialize the data but I didn’t find one. I tried myself using Regex but I spent many hours without luck.

Knowing that the type of serialized data is: array, string, number.

Any efficient way to do so? (Package or Code)

Thanks in advance.

Styling the WordPress customization section

To style the WordPress settings section, I have introduced my style file to WordPress using the following code:

 function WordPress_style_management()
{
  echo wp_enqueue_style( 'WordPress', get_template_directory_uri() . '/style.css', array(), '4.0.0' );
}
add_action( 'admin_head', 'WordPress_style_management' );

This code works correctly and all styles are correctly applied to the WordPress settings section.

But the problem that happened to me is that I can’t give any style to the customization section of WordPress.

Is there a code like above so I can style the customization section as well?

Probleme with post_max_size variable in php.ini [duplicate]

I have a php server with Symfony (and API Platform) and I’ve just created a file upload system with Vich Uploader bundle. I have an Assert attribute on my File property that restricts its maximum size to 5MB.

The problem is that if I enter a file larger than 5MB but also larger than the post_max_size value in php.ini, the server can’t process the request and returns a 500 error.

[Web Server ] PHP Warning: POST Content-Length of 27052288 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
[Web Server ] :00″,”message”:”/api/documents”}
[Web Server ] Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 81153520 bytes) in C:[…]vendorsymfonyhttp-kernelProfilerFileProfilerStorage.php on line 150
[Web Server ] PHP Stack trace:
[many lines of the stack trace]

I looked for a solution but the only one I found was to increase the value of post_max_size. But I think it’s a workaround to do that, since all you have to do is enter a file heavier than this limit to bug the server.

So does anyone have a real solution (that doesn’t involve increasing values in php.ini) that return a php error (422?) without having memory problems and so on?

For now, I’ve created an EventListener to return an 422 error :

namespace AppEventListener;

use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpKernelEventRequestEvent;

class MaxPostSizeListener
{
    public function onKernelRequest(RequestEvent $event): void
    {
        if (!isset($_SERVER['CONTENT_LENGTH'])) {
            return;
        }

        $contentLength = (int) $_SERVER['CONTENT_LENGTH'];
        if ($contentLength > $this->getPostMaxSize()) {
            $errorMessage = 'La taille du fichier est trop grande.';
            $response = new Response(json_encode(['message' => $errorMessage]), Response::HTTP_UNPROCESSABLE_ENTITY);
            $response->headers->set('Content-Type', 'application/json');
            $event->setResponse($response);
        }
    }

    private function getPostMaxSize(): int
    {
        $maxSize = ini_get('post_max_size');
        if (!preg_match('/^(d+)(.)$/', $maxSize, $matches)) {
            return 0;
        }

        $value = (int) $matches[1];
        switch (strtoupper($matches[2])) {
            case 'G':
                $value *= 1024;
            // no break
            case 'M':
                $value *= 1024;
            // no break
            case 'K':
                $value *= 1024;
        }

        return $value;
    }
}

But I still have the memory problem and the multiple lines in the terminal.

What makes preventing the default form submission behavior fail in this use case of jQuery AJAX?

I have made a blogging application in Laravel 8.

I am currently working on submitting comments and comment replies via AJAX instead of doing it “classically”.

The comment form:

<form class="commentForm" method="post" action="{{ route('comment.submit') }}" autocomplete="off">
  @csrf
    <fieldset>
      <input type="hidden" name="article_id" value="{{ isset($article->id) ? $article->id : $article_id }}">
      <input type="hidden" name="parent_id" value="{{ $comment->id ?? '' }}">

      <div class="message form-field">
          <textarea name="msg" id="message" class="h-full-width" placeholder="Your Message" required></textarea>

          @error('msg')
          <p class="help-block text-danger">{{ $message }}</p>
          @enderror
      </div>
      <br>
      <input name="submit" id="submit" class="btn btn--primary btn-wide btn--large h-full-width" value="Add Comment" type="submit">
    </fieldset>
</form>

For validation, I use the jQuery Validation Plugin (v1.19.0) by Jörn Zaefferer

The (jQuery) AJAX part:

// Validate comment form
$(".commentForm").each(function(){
  var form = $(this);
  form.validate({
    errorElement: 'p',
    errorClass: "help-block text-danger",

    submitHandler: function(event) {
      event.preventDefault();
      var $fields = form.find('textarea'),
      url = form.attr('action'),
      data = form.serialize();
      $.ajax({
        dataType: "json",
        type: "post",
        url: url,
        data: data,
        cache: false,
        success: function(response) {
          $('#commentSuccess').slideDown(250).delay(2500).slideUp(250);
          $fields.val('');
        },
        error: function() {
          $('#commentFail').slideDown(250).delay(2500).slideUp(250);
        }
      });
    }
  });
});

The problem

For a reason I have been unable to find out, the part that should prevent “classic” form submission, event.preventDefault() does not work.

Questions:

  1. What am I doing wrong?
  2. What is the most reliable way to fix this problem?

wpcf7 spinning no stop and doesn’t show from submission ok (wpcf7-response-output)

Goodmorning, I used this hook with CF7

'wpcf7_before_send_mail', 'log_cf7'

and when the form are submited “wpcf7-spinner” doesn’t stop to turning and the message of from submission ok doesn’t show (wpcf7-response-output)

I tried to disable every other plug in with out good news.

I tried to disable parts of php text but this isn’t the right way

Only if I exclude:

'wpcf7_before_send_mail', 'log_cf7

spinner disappear and the response output come showed.

Some one can help me?

Follow the code that I used:

<?php

add_action('wpcf7_before_send_mail', 'log_cf7');

 function log_cf7($WPCF7_ContactForm) {
  $submission = WPCF7_Submission::get_instance();
  $data = $submission->get_posted_data();

 $upload_dir   = wp_upload_dir();
  echo $upload_dir['basedir'] . '/wpcf7_uploads';

   $text .= "CSTPRODREG";
   $text .= "|||";
   $text .= $data['text-638'];
   $text .= "|||||||||||||";
   $text .=  $data['checkbox-613'];
   $text .= "||";
   $text .=  $data['your-name'];
   $text .= "|";
   $text .=  $data['text-628'];
   $text .= "||||||";
   $text .=  $data['tel-709'];
   $text .= "|||";
   $text .=  $data['your-email'];
   $text .= "||||||";
   $text .=  $data['menu-470'][0];
   $text .= "|";
   $text .=  $data['menu-749'][0];
   $text .=  $data['menu-750'][0];
   $text .=  $data['menu-751'][0];
   $text .=  $data['menu-752'][0];
   $text .=  $data['menu-753'][0];
   $text .= "||";
   $text .=  $data['number-540'];
   $text .=  $data['number-550'];
   $text .=  $data['number-563'];
   $text .=  $data['number-576'];
   $text .=  $data['number-580'];
   $text .=  $data['text-576'];
   $text .=  $data['number-581'];
   $text .=  $data['number-581'];
   $text .=  $data['number-585'];
   $text .= "||";
   $text .= $formatted_date = str_replace('-', '', $data['date-855']);
   $text .= "|||";
   $text .= 'www.mysite/wp-content/uploads/cfdb7_uploads/' . $_FILES['file-799']['name'];

   foreach ($data as $key => $value) {
}
function getUniqueFilename() {
    return date("YmdHis" , strtotime('+2 hours')) . '.prr';
   }
  $myfile = fopen($_SERVER['DOCUMENT_ROOT'] . '/' . getUniqueFilename(), 'wb');
  fwrite($myfile, $text);
  $ftp_server="ftp.mysite";
  $ftp_username="xxx";
  $ftp_userpass="xxx";
  $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to server");
   $login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
  if(ftp_put($ftp_conn,"newdata.prr",$_SERVER['DOCUMENT_ROOT'] . "/tempFile.prr",FTP_ASCII))
  {
       print("yay");
  }
  else
  {
     print("f...");
  }
  
   ftp_close($ftp_conn);
   fclose($myfile);

}
?>

?>

codeigniter4 code to add employee redirects to itself on submit when regenerate is set to true in config.security

I have a codeigniter4 application.
When i set public $regenerate = true; in Security.php
the view with a form submit to add employee redirects to itself on submit. But when regenerate is false, code submits to the controller and data is processed as required
How can i solve the issue with regenerate set to true?.

The controller function handling add_employee is:

public function add_employee()
    {
        $session = session();
        $request = ConfigServices::request();
        $db = ConfigDatabase::connect();
       
        $usermodel = new AppModelsUserModel();
        $data['user']=$usermodel->getRow($session->get('email'));
        $data['title'] = 'Add employee';

        $employeemodel = new AppModelsEmployeeModel();
        $divisionmodel = new AppModelsDivisionModel();
        $userRoleModel = new AppModelsUserRoleModel();

        $data['employee'] = $employeemodel->getAll();
        $data['designation'] = $employeemodel->getAllDesignations();
        $data['division'] = $divisionmodel->findAll();
        $data['roles']  = $userRoleModel->findAll();
        
        
         $role_id= $data['user']['role_id'];
        if($role_id==5||$role_id==10){ //Division Admin or Division head

         $builder=$db->table('tbl_division');
         $builder->select('tbl_division.int_divisionID');

             if($role_id==5){         
            
                 $builder->join('tbl_administrator','tbl_administrator.int_divisionID=tbl_division.int_divisionID');
            } else{
                $builder->join('tbl_employee','tbl_employee.int_divisionID=tbl_division.int_divisionID');
            }

         $division=$builder->get()->getRowArray();
         $data['selected_division'] = $division['int_divisionID'];

         $builder=$db->table('tbl_department');
         $builder->select('tbl_department.int_departmentID,tbl_department.vchr_departmentName');
         $builder->where('tbl_department.int_divisionID',$division['int_divisionID']);
         $data['department']= $builder->get()->getResultArray();
        }
         elseif($role_id==11)//Department Head
         {
          $builder=$db->table('tbl_employee');
          $builder->select('int_departmentID');          
          $builder->where('tbl_employee.int_userID',$data['user']['id']);
          $department = $builder->get()->getRowArray();          
          $department_id = $department['int_departmentID'];
          $data['department_id']=$department_id;

          $builder=$db->table('tbl_department');
          $builder->select('tbl_department.int_divisionID');
          $builder->where('tbl_department.int_departmentID',$department_id);
          $division=$builder->get()->getRowArray();
          $data['selected_division'] = $division['int_divisionID'];

          $builder=$db->table('tbl_department');          
          $builder->select('tbl_department.id,tbl_department.int_departmentID,tbl_department.vchr_departmentName');
          $builder->where('tbl_department.int_divisionID',$division['int_divisionID']);
          $data['department']= $builder->get()->getResultArray();
         }

        
        if ($this->request->getMethod() == "post") {

            
             $validation =  ConfigServices::validation();

             $_POST['csrf_test_name']=$_REQUEST['csrf_test_name'];

             $rules = [
           
                    "csrf_test_name" => [
                        "label" => "CSRF Token Name",
                        "rules" => "required|trim|alpha_numeric|max_length[64]"
                    ],
                    "vchr_CDIT_employeeID" => [
                        "label" => "CDIT EmployeeID",
                        "rules" => "required|trim|alpha_numeric|max_length[10]"
                    ],
                    "vchr_employeeName" => [
                        "label" => "Employee Name",
                        "rules" => "required|trim|alpha_space|max_length[100]"
                    ],
                    "vchr_email_id" => [
                        "label" => "Email",
                        "rules" => "required|trim|valid_email|max_length[100]"
                    ],
                    "int_mobileNo" => [
                        "label" => "Mobile No",
                        "rules" => "required|trim|numeric|max_length[10]|min_length[10]"
                    ],
                    "int_empType" => [
                        "label" => "Mobile No",
                        "rules" => "required|trim|numeric|max_length[3]"
                    ]
                    
                ];

                 $int_empType = $request->getPost('int_empType');
      
      
      if(!($int_empType==7 || $int_empType==8)){


        $rules1= [
            "int_designationID" => [
                        "label" => "Designation",
                        "rules" => "required|trim|numeric|max_length[4]"
                    ],
            "int_divisionID" => [
                        "label" => "Division",
                        "rules" => "required|trim|numeric|max_length[4]"
                    ]

        ];

        $rules=array_merge($rules,$rules1);
        
        }

        if(!($int_empType==7 || $int_empType==8 || $int_empType==9 )){

        
        $rules1= [
            "int_departmentID" => [
                        "label" => "Department",
                        "rules" => "required|trim|numeric|max_length[4]"
                    ]

        ];

         $rules=array_merge($rules,$rules1);

        }
       
        if (!($this->validate($rules))) {   

                $session->setFlashdata('employeemessage', '<div class="alert alert-danger" role="alert">
                Validation Errors!</div>');
           
                return redirect()->back()->withInput();
           
            } 
        else{
                
                $email = strip_tags($request->getPost('vchr_email_id'));
                $name = strip_tags($request->getPost('vchr_employeeName'));

         

          $employeeemailexists = $employeemodel->where('vchr_email_id',$email)->first();
          
          if($employeeemailexists){

             $session->setFlashdata('employeemessage', '<div class="alert alert-danger" role="alert">
             employee Creation Failed. employee with this email already exists</div>');
             return redirect()->to('employee');
            
          }

          $userdata  = $usermodel->where('email',$email)->first();
          if($userdata){

            $session->setFlashdata('employeemessage', '<div class="alert alert-danger" role="alert">
             User Creation Failed. User with this email already exists</div>');
             return redirect()->to('employee');
            
          }
          $date_created = date("Y-m-d H:i:s", time());

          $comb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*_-";
          $shfl = str_shuffle($comb);
          $pwd = substr($shfl,0,12);
          $data = [
              'name' => $name,
              'email' => $email,
              'image' => 'default.jpg',
              'password' => md5($pwd),
              
              'role_id' => 4,
              'is_active' => 1,
              'isFirstLogin' => 1,
              'date_created' => $date_created
          ];

         $token = base64_encode(random_bytes(32));

         
          $emailstatus=sendemail($name,$email,$token,$pwd, 'verify');

          if(!$emailstatus){
               
                $emailmsg='<span class="alert alert-danger" role="alert">Password couldnot be send through email.Check mail configuration</span>';

            }
            else
                $emailmsg='<span class="alert alert-success" role="alert"> Password send to employee email </span>';
           $usermodel->insert($data);
          
           $res=$usermodel->where('email',$email)->first();

            $insert_id=$res['id'];

            $employeemodel->saveToDB($insert_id);

            $session->setFlashdata('employeemessage', '<div class="alert alert-success" role="alert">
                Employee added successfully!.Password is <b>'.$pwd.'</b></div>'.$emailmsg);
                return redirect()->to('employee');
            }
        }
        else{
            echo view('templates/admin_header', $data).
            view('templates/admin_sidebar').
            view('templates/admin_topbar', $data).
            view('employee/add_employee').
            view('templates/admin_footer');
        }

      
    }

My view add_employee

<!-- Begin Page Content -->

<div class="container-fluid">

    <!-- Page Heading -->
    <h1 class="h3 mb-4 text-gray-800">Add Employees </h1>

    <div class="card shadow mb-3">
        <!--<div class="card-header">
            Add Employees
        </div>-->

        <div class="card-body">
        <div style="display: flex; justify-content: flex-end"> <button  onclick="history.back();"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
          <?php
          $attributes = array('id' => 'myform');
          echo form_open('employee/add_employee',$attributes);?>


                <div class="form-group">
                    <label for="vchr_CDIT_employeeID">CDIT Employee ID<font color="red"> *</font></label>
                    <input class="form-control" maxlength="100" 
                    type="text" name="vchr_CDIT_employeeID" placeholder="Enter CDIT Employee ID"
                    value="<?= set_value('vchr_CDIT_employeeID'); ?>">
                    <?= form_error('vchr_CDIT_employeeID', '<small class="text-danger pl-3">', '</small>'); ?>
                </div>
                <div class="error" width="100%"></div>


                <div class="form-group">
                    <label for="vchr_employeeName">Employee Name<font color="red"> *</font></label>
                    <input class="form-control" maxlength="100" 
                    type="text" name="vchr_employeeName" placeholder="Enter Employee Name" value="<?= set_value('vchr_employeeName'); ?>">
                    <?= form_error('vchr_employeeName', '<small class="text-danger pl-3">', '</small>'); ?>
                </div>
                <div class="error" width="100%"></div>


                <div class="form-group">
                    <label for="vchr_email_id">E-Mail ID<font color="red"> *</font></label>
                    <input class="form-control" maxlength="100" 
                    type="email" name="vchr_email_id" placeholder="Enter Email ID" value="<?= set_value('vchr_email_id'); ?>">
                    <?= form_error('vchr_email_id', '<small class="text-danger pl-3">', '</small>'); ?>
                </div>
                <div class="error" width="100%"></div>


                <div class="form-group">
                    <label for="int_mobileNo">Mobile Number<font color="red"> *</font></label>
                    <input class="form-control"
                    type="text" minlength="10" maxlength="10" name="int_mobileNo" placeholder="Enter Mobile Number" value="<?= set_value('int_mobileNo'); ?>">
                    <?= form_error('int_mobileNo', '<small class="text-danger pl-3">', '</small>'); ?>
                </div>
                <div class="error" width="100%"></div>
                
                <div class="form-group">
                    <label for="int_empType">Enter Employee Type <font color="red"> *</font></label>
                    <select name="int_empType" id="int_empType" class="form-control">
                      <option value="">---Select Role---</option>
                      <?php foreach ($roles as $r) : ?>
                      <?php 
                     
                     if(!in_array($r['id'],[1,3,5]))
                      {
                      
                      ?><option value="<?= $r['id']; ?>"><?= $r['role']; ?></option>
                    <?php } endforeach; ?>
                      </select>
                      <?= form_error('int_empType', '<small class="text-danger pl-3">', '</small>'); ?>
                </div>
                <div class="error" width="100%"></div>

                <div class="form-group" id="divisionDiv">
                    <label for="int_divisionID">Enter Division <font color="red"> *</font></label>
                    <select name="int_divisionID" id="int_divisionID" class="form-control"
                    
                    >
                    
                     <?php if(isset($selected_division)) { 
                     foreach ($division as $d) :
                     if($d['int_divisionID']==$selected_division){
                     ?>
                    >
                     <option value="<?= $d['int_divisionID']; ?>" selected > <?= $d['vchr_divisionName']; ?></option>
                    <?php
                    } endforeach;
                    } else {
                    ?>
                    
                    
                        <option value="">---Select Division---</option>
                        <?php foreach ($division as $d) : ?>
                        <option value="<?= $d['int_divisionID']; ?>"                     
                        >
                        <?= $d['vchr_divisionName']; ?></option>
                        <?php endforeach; }?>
                    </select>
                    <?= form_error('int_divisionID', '<small class="text-danger pl-3">', '</small>'); ?>
                </div>
                <div class="error" width="100%"></div>

                <div class="form-group" id="deptdiv">
                    <label for="int_departmentID">Enter Department <font color="red"> *</font></label>
                    <select name="int_departmentID" id="int_departmentID" class="form-control">
                    <?php if(isset($department_id)) { 
                     foreach ($department as $d) :
                     if($d['int_departmentID']==$department_id){
                     ?>
                   
                     <option value="<?= $d['int_departmentID']; ?>" selected > <?= $d['vchr_departmentName']; ?></option>
                    <?php
                    } endforeach;
                    } else {
                    ?>
                        <option value="" selected>---Select Department---</option>
                        <?php if(isset($department)){
                         foreach ($department as $d) : ?>
                        <option value="<?= $d['int_departmentID']; ?>">
                        <?= $d['vchr_departmentName']; ?></option>
                        <?php endforeach; }
                        
                        }?>

                    </select>
                    <?= form_error('int_departmentID', '<small class="text-danger pl-3">', '</small>'); ?>
                </div>
                <div class="error" width="100%"></div>


                <div class="form-group" id="desigDiv">
                    <label for="int_designationID">Enter Designation <font color="red"> *</font></label>
                    <select name="int_designationID" id="int_designationID" class="form-control">
                        <option value="">---Select Designation---</option>

                    </select>
                    <?= form_error('int_designationID', '<small class="text-danger pl-3">', '</small>'); ?>

                </div>
                <div class="error" width="100%"></div>


                <!-- button save -->
                  <div class="form-group">
                        <button type="submit" class="btn btn-success" >Add Employee!</button>
                    </div>
            </form>
        </div>

        <div class="card-footer small text-muted">
        <font color="red"> *</font> must be filled
        </div>
    </div>

</div>
<!-- /.container-fluid -->

</div>
<!-- End of Main Content -->

</div>
<!-- /.container-fluid -->

</div>
<!-- End of Main Content -->

<script type="text/javascript">


$('#int_divisionID').on('change', function(){
    var int_divisionID = $('#int_divisionID').val();
   
     var csrfName = "csrf_test_name";
    var csrfHash = $('[name="csrf_test_name"]').val();

    $.ajax({
        type:"POST",
        url: "<?php echo site_url('Department/getDepartments')?>",
        data: {[csrfName]: csrfHash, int_divisionID: int_divisionID},
        success:function(response){

            $('#int_departmentID').html('<option value=""> ---Select Department--- </option>');
            $.each(JSON.parse(response), function(key,val) {
                $('#int_departmentID').append('<option value="' + val.id + '">'+ val.vchr_departmentName +'</option>');
            });
        }
    });


});

$('#int_departmentID').on('change', function(){
    var int_divisionID = $('#int_divisionID').val();
   
     var csrfName = "csrf_test_name";
    var csrfHash = $('[name="csrf_test_name"]').val();
$.ajax({
        type:"POST",
        url: "<?php echo site_url('Department/getDesignations')?>",
        data: {[csrfName]: csrfHash, int_divisionID: int_divisionID},
        success:function(response){

            $('#int_designationID').html('<option value=""> --Select Designation-- </option>');
            $.each(JSON.parse(response), function(key,val) {
                $('#int_designationID').append('<option value="' + val.id + '">'+ val.vchr_designation +'</option>');
            });
        }
    });
});
</script>

<script type="text/javascript">

$(document).ready(function() {

$('#int_empType').on('change', function(){
 var int_empType = $('#int_empType').val();
 if(int_empType==7 || int_empType==8 || int_empType==9 ){
 $('#deptdiv').hide();
 $('#int_departmentID').val(0);
 }
 else{
 $('#deptdiv').show();
 $('#divisionDiv').show();
  $('#desigDiv').show();
 }
 if(int_empType==7 || int_empType==8){
 
  $('#divisionDiv').hide();
  $('#desigDiv').hide();
  $('#int_divisionID').val(0);
  }
  else{
  $('#divisionDiv').show();
  }
 
});

 var int_divisionID = $('#int_divisionID').val();
    
    var csrfName = "csrf_test_name";
    var csrfHash = $('[name="csrf_test_name"]').val();
$.ajax({
        type:"POST",
        url: "<?php echo site_url('Department/getDesignations')?>",
        data: {[csrfName]: csrfHash, int_divisionID: int_divisionID},
        success:function(response){
            $('#int_designationID').html('<option value=""> --Select Designation-- </option>');
            $.each(JSON.parse(response), function(key,val) {
                $('#int_designationID').append('<option value="' + val.id + '">'+ val.vchr_designation +'</option>');
            });
        }
    });

jQuery.validator.addMethod("name_check", function(value, element) {
return this.optional(element) || /^[a-zA-Zs.-]+$/.test(value);
});

jQuery.validator.addMethod("CDIT_employeeID", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9s.-]+$/.test(value);
});

jQuery.validator.addMethod("email_check", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._-]+@([a-zA-Z0-9-]+.[a-zA-Z])*[a-zA-Z0-9-]+.[a-zA-Z]{2,5}$/i.test(value);
});

jQuery.validator.addMethod("phonenumber", function(value, element) {
return this.optional(element) || /^d{10}$/.test(value);
});


$("#myform").validate({

rules: {

vchr_CDIT_employeeID: {

required: true,
CDIT_employeeID:true,

},

vchr_employeeName: {

required: true,
name_check:true,

},

vchr_email_id: {

required: true,
//email_check:true,

},

int_mobileNo: {
required:true,
minlength:10,
maxlength:10,
phonenumber:true,

},

int_divisionID:{
  required: {
                depends: function(element) {
                    return (!($('#int_empType').val()==7 || $('#int_empType').val()==8))
                }
                }

},

int_departmentID :{
  required: {depends: function(element) {
                    return (!($('#int_empType').val()==7 || $('#int_empType').val()==8 ||  $('#int_empType').val()==9))
                }}

},

int_designationID: {
  required: {depends: function(element) {
                    return (!($('#int_empType').val()==7 || $('#int_empType').val()==8 ||  $('#int_empType').val()==9))
                } }
},



int_empType: {
  required:true,
},


},
messages: {

vchr_employeeName: {
required: "<font color='#FF0000'> Employee Name required !!</font>",
name_check:"<font color='#FF0000' > Invalid Special characters in Employee Name!!</font>"
},

vchr_email_id: {
required: "<font color='#FF0000'> E-mail ID is required !!</font>",
//email_check: "<font color='#FF0000'> Invalid Email Format !!</font>",
},

int_mobileNo: {
  required: "<font color='#FF0000'> Mobile Number is required !!</font>",
  minlength : "<font color='#FF0000'> Mobile Number should be of 10 characters long !!</font>",
  maxlength : "<font color='#FF0000'> Mobile Number should be of 10 characters long !!</font>",
  phonenumber : "<font color='#FF0000'> Mobile Number is Invalid !!</font>",
},

vchr_CDIT_employeeID :{
  required: "<font color='#FF0000'> CDIT Employee ID required !!</font>",
  CDIT_employeeID : "<font color='#FF0000'> Invalid Employee ID !!</font>",

},

int_divisionID :{
  required: "<font color='#FF0000'> Division required !!</font>",

},

int_departmentID :{
  required: "<font color='#FF0000'> Department required !!</font>",

},

int_designationID :{
  required: "<font color='#FF0000'> Designation required !!</font>",

},

int_empType : {
  required: "<font color='#FF0000'> Employee Type required !!</font>",

},


},
errorElement: "span",
errorPlacement: function(error, element) {
  error.appendTo(element.parent("div").next());
},
submitHandler: function (form) {
            /*var key = "eTicketingCI4CDIT#$abc";
            var form = document.getElementById("myForm");
            var inputs = form.getElementsByTagName("input");

            for (var i = 0; i < inputs.length; i++) {
                var input = inputs[i];
                if (input.type !== "submit" && input.type !== "button") {
                    var encryptedValue = CryptoJS.AES.encrypt(input.value, key).toString();
                    input.value = encryptedValue;
                }
            }*/
              
              form.submit();
          }

});

});


</script>

EasyAdmin (Symfony) does not update ManyToOne entities in Association Field with multiple relationships

We have a backoffice developed with EasyAdmin (4.4.5), for a Symfony (5.4.24) project. Among other entities and features, we have a bunch of related entities, as shown in the following code example. The thing is, with these relationships, when we create an entity, everything is working correctly; but when we want to update one of the related entities, this change is not made (everything updates except for the relation).

We have been investigating and we see that EasyAdmin’s CRUD forms sends the new data, and the new values goes through the “setXxxx” functions of the modified entities. But those entities, when they reach the “updateEntity()” function, arrive with the old related data.

Can someone tell us if this situation is due to a bad configuration of the entities, or if there is an error in the code, or if it’s a Symfony or Doctrine cache problem, or if it is a bug in EasyAdmin?

We have not been able to solve this situation.

Thank you so much.

PD: The number “2” in the entities name is because I generated an example of code from our project, simplified to be able to explain the case.

Entities:

// namespace AppModuleAC2EntityManufacturer2;
class Manufacturer2 implements EntityInterface
{
    use IdEntityTrait;
    use NameEntityTrait;

    #[AssertNotNull(message: 'trans.assert.systemRanges.notNull')]
    #[AssertType(type: Collection::class, message: 'trans.assert.systemRanges.type')]
    #[AssertValid]
    #[AssertAll([
        new AssertType([Key::TYPE => SystemRange2::class, Key::MESSAGE => 'trans.assert.systemRanges.all.type'])
    ])]
    #[ORMOneToMany(targetEntity: SystemRange2::class, mappedBy: 'manufacturer', orphanRemoval: true)]
    private Collection $systemRanges;

    #[AssertNotNull(message: 'trans.assert.acModels.notNull')]
    #[AssertType(type: Collection::class, message: 'trans.assert.acModels.type')]
    #[AssertValid]
    #[AssertAll([
        new AssertType([Key::TYPE => ACModel2::class, Key::MESSAGE => 'trans.assert.acModels.all.type'])
    ])]
    #[ORMOneToMany(targetEntity: ACModel2::class, mappedBy: 'manufacturer', orphanRemoval: true)]
    private Collection $acModels;

    public function __construct()
    {
        $this->setId();
        $this->systemRanges = new ArrayCollection();
        $this->acModels     = new ArrayCollection();
    }
...
}
// namespace AppModuleAC2EntitySystemRange2;
class SystemRange2 implements EntityInterface
{
    use IdEntityTrait;
    use NameEntityTrait;

    #[AssertNotNull(message: 'trans.assert.manufacturer.notNull')]
    #[AssertType(type: Manufacturer2::class, message: 'trans.assert.manufacturer.type')]
    #[AssertValid]
    #[ORMManyToOne(targetEntity: Manufacturer2::class, inversedBy: 'systemRanges')]
    #[ORMJoinColumn(nullable: false)]
    private ?Manufacturer2 $manufacturer = null;

    #[AssertNotNull(message: 'trans.assert.lines.notNull')]
    #[AssertType(type: Collection::class, message: 'trans.assert.lines.type')]
    #[AssertValid]
    #[AssertAll([
        new AssertType([Key::TYPE => Line2::class, Key::MESSAGE => 'trans.assert.lines.all.type'])
    ])]
    #[ORMOneToMany(targetEntity: Line2::class, mappedBy: 'systemRange', orphanRemoval: true)]
    private Collection $lines;

    #[AssertNotNull(message: 'trans.assert.acModels.notNull')]
    #[AssertType(type: Collection::class, message: 'trans.assert.acModels.type')]
    #[AssertValid]
    #[AssertAll([
        new AssertType([Key::TYPE => ACModel2::class, Key::MESSAGE => 'trans.assert.acModels.all.type'])
    ])]
    #[ORMOneToMany(targetEntity: ACModel2::class, mappedBy: 'systemRange', orphanRemoval: true)]
    private Collection $acModels;

    public function __construct()
    {
        $this->setId();
        $this->lines    = new ArrayCollection();
        $this->acModels = new ArrayCollection();
    }
...
}
// namespace AppModuleAC2EntityLine2;
class Line2 implements EntityInterface
{
    use IdEntityTrait;
    use NameEntityTrait;

    #[AssertNotNull(message: 'trans.assert.systemRange.notNull')]
    #[AssertType(type: SystemRange2::class, message: 'trans.assert.systemRange.type')]
    #[AssertValid]
    #[ORMManyToOne(targetEntity: SystemRange2::class, inversedBy: 'lines')]
    #[ORMJoinColumn(nullable: false)]
    private ?SystemRange2 $systemRange = null;

    #[AssertNotNull(message: 'trans.assert.acModels.notNull')]
    #[AssertType(type: Collection::class, message: 'trans.assert.acModels.type')]
    #[AssertValid]
    #[AssertAll([
        new AssertType([Key::TYPE => ACModel2::class, Key::MESSAGE => 'trans.assert.acModels.all.type'])
    ])]
    #[ORMOneToMany(targetEntity: ACModel2::class, mappedBy: 'line', orphanRemoval: true)]
    private Collection $acModels;

    public function __construct()
    {
        $this->setId();
        $this->acModels = new ArrayCollection();
    }
...
}
// namespace AppModuleAC2EntityACModel2;
class ACModel2 implements EntityInterface
{
    use IdEntityTrait;
    use NameEntityTrait;

    #[AssertNotNull(message: 'trans.assert.systemRange.notNull')]
    #[AssertType(type: SystemRange2::class, message: 'trans.assert.systemRange.type')]
    #[AssertValid]
    #[ORMManyToOne(targetEntity: SystemRange2::class, inversedBy: 'acModels')]
    #[ORMJoinColumn(nullable: false)]
    private ?SystemRange2 $systemRange = null;

    #[AssertNotNull(message: 'trans.assert.line.notNull')]
    #[AssertType(type: Line2::class, message: 'trans.assert.line.type')]
    #[AssertValid]
    #[ORMManyToOne(targetEntity: Line2::class, inversedBy: 'acModels')]
    #[ORMJoinColumn(nullable: false)]
    private ?Line2 $line = null;

    #[AssertNotNull(message: 'trans.assert.manufacturer.notNull')]
    #[AssertType(type: Manufacturer2::class, message: 'trans.assert.manufacturer.type')]
    #[AssertValid]
    #[ORMManyToOne(targetEntity: Manufacturer2::class, inversedBy: 'acModels')]
    #[ORMJoinColumn(nullable: false)]
    private ?Manufacturer2 $manufacturer = null;

    public function __construct()
    {
        $this->setId();
    }
...
}

Workflow in images:

Define manufacturers

Define SystemRange

Define Line

Define ACModel

Try to update Manufacturer in ACModel

We have tried: Check the circular references of the entities, configure the Symfony and Doctrine cache so that it does not run, keep track of the value changes in the entities, we have also tried to remove some of the relations of the entities (just for testing), …

We expected that you could change any of the related entities, and save the change normally from EasyAdmin.

Symfony error : EntityManager#remove() expects parameter 1 to be an entity object, NULL given

I’m new to symfony, I’m trying to build a little web projet and I met an error on my symfony
interface.

I get this error while I want laugh my web project :

EntityManager#remove() expects parameter 1 to be an entity object, NULL given.

And here is the related code :

    public function homepage(EntityManagerInterface $em)
    {

        $productRepository = $em->getRepository(Product::class);

        $product = $productRepository->find(3);


            $em->remove($product);

            $em->flush();


        dd($product);

        return $this->render('home.html.twig');
    }

}

Someone can help me to fix it ?

I tried to change the value setting of the $product but nothing happens.

WooCommerce add custom order count in admin backend

Based on that article Include order count from custom order status in WooCommerce admin menu, I know that we can adjust the count from the WooCommerce default “in processing” orders count. We want to add a second count for orders in a special status “shipped”. I don’t find a way to add this second count in that area.

// Add orders count of a specific order status
function filter_woocommerce_menu_order_count( $wc_processing_order_count ) {
    // Call function and pass custom order status
    $order_count_shipped = wc_orders_count( 'shipped' );
    
    return $wc_processing_order_count + $order_count_shipped;
}
add_filter( 'woocommerce_menu_order_count', 'filter_woocommerce_menu_order_count', 10, 1 );

Does someone know how I can add there such a count in blue?

enter image description here

How to count all value of visits coloum where uid is 2?

I want to know how to count all Visits values between selected dates. i want to count all visits values betwwen two dates where uid is =2. Below is my mysql db structure.

ID | uid | visits|  Date
1  | 1   |10     |02/07/23 
2  | 2   |85     |01/07/23 
3  | 1   |56     |29/06/23 
4  | 2   |06     |28/06/23 
5  | 2   |12     |27/06/23