TIMESTAMP inserting wrong date in database when run from PHP

I have a insert query from PHP file to database.

While executing the query from MySQL Workbench it is inserting last_used value in database exact time given in the query. But when I try to run the same query from PHP code it is inserting 1 day future date.

In both scenarios created_at inserting correct value which is mentioned in the table structure

I have set timezone to Asia/Kolkata in php.ini file.

I have searched a lot in the google and executed all the things mentioned by all.

<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO `login_token` (`userid`, `username`, `token`, `last_used`, `role_id`) VALUES ('aiIRX+5v35p4vOokrgVR+Q==', '/McgiDGM0JpsyCSie2cIV4sTwrtkE+ev', 'token1', '2022-09-19 12:47:59', '')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}
?>

Table Structure
table structure

Result of records inserted from php

enter image description here

As you see in the above question i have last_used column in database with TIMESTAMP datatype. I have a insert query in my php code. If i run the query in php it is inserting ‘2022-09-20 01:77:59’ instead of ‘2022-09-19 12:47:59’. If i run the same query in mysql workbench it is inserting same value ‘2022-09-19 12:47:59”

when i echo date(‘Y-M-d H:i:s’) it is showing correct time which is matched with my local machine.

when i run SELECT CURRENT_TIMESTAMP() in workbench it is also showing same time which is given in date() in php.

FCM for sending multiple notifications in an efficient manner

I am retrieving push message data from database and want to send notifications in one go instead of using while loop in php.

Code:

$pushMessageDetails->DbQueryPrepare('CALL procGetAllPushMessages()');
$pushMessageDetails->DbQueryHit();
while ( $pushMessageDetails->DbQueryFetch() )
{
  //having few checks and forming postData
  //connecting using curl_setopt and executing

}

Testing Guzzle request and PDF converter

I’m pretty new into testing things, and I was wondering how I could test such code or even if it’s valuable to test this.

this is what my code looks like :

    public function convert(string $urlToConvert, string $path, array $options = []): void
    {
        try {
            $result = $this->getClient()->post(
                sprintf('%s/%s', $this->config->getEndpoint(), self::GOTENBERG_CHROMIUM_ENDPOINT),
                [
                    'multipart' => [
                        ['name' => 'url', 'contents' => $urlToConvert],
                        ['name' => 'emulatedMediaType', 'contents' => 'screen'],
                        ...$options
                    ]
                ]
            );

            $directory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
            $directory->writeFile($path, $result->getBody());
        } catch (Exception | GuzzleException $e) {
            $this->logger->error($e, ['context' => 'm2-gotenberg']);

            throw new GotenbergConvertException(__('Failed converting PDF'), $e);
        }
    }

The getClient() returns an instance of a GuzzleHttp.

The process is the following :

  • Do a request on an endpoint with the URL
  • Get the response body which is the converted PDF
  • Create a file with the content given by the response

I don’t feel like I could test anything, or a really small amount of the code.

About the lines creating the files, this is the done by the framework I’m using

The only thing I see is to do an integration test, and fetching the endpoint to create a real pdf, then delete it.

Can someone clarify this for me or give me some advices? When using framework I have troubles on what to test to avoid testing the implementation of my code

Jquery min values from html table

On my project, I have an html table from curl made with php

I need to get some statistics from this table as Minimal, maximal and average values frome a specific column. All the colums have an td id
I would like to use jquery for that.

Here is the table:

table id='table'

//title line
echo ("<tr id='title'><td id ='orderNo'>orderNo</td><td id ='orderDate'>orderDate</td><td id ='yourReference'>yourReference</td><td id ='Reference'>Reference</td><td id ='projectName'>projectName</td><td id ='statusId'>statusId</td><td id ='statusText'>statusText</td><td id ='shippedOn'>shippedOn</td><td id ='deliveredOn'>deliveredOn</td><td id ='signedBy'>(POD) signedBy</td><td id ='days'>Number of days</td><td id ='packages'>Number of packages</td><td id ='netWeight'>netWeight</td></tr>");

//content line (in a foreach loop
echo ("<tr><td>".$order."</td><td>".$orderDate."</td><td>".$references."</td><td>".$yourReference."</td><td>".$projectName."</td><td>".$statusId."</td><td>".$statusText."</td><td>".$shippedOn."</td><td>".$deliveredOn."</td><td>".$signedBy."</td><td>".$diffDate."</td><td>".$quantity."</td><td>".$netWeight." Kg</td></tr>"); 

the values in the "days" column are obtained by subtracting shippedOn and deliveredOn or :

if(isset($result['results'][$i]["shippedOn"])){
                        $shippedOn = $result['results'][$i]["shippedOn"];
                    }else{
                        $shippedOn = "0";
                    }
                    if(isset($result['results'][$i]["deliveredOn"])){
                        $deliveredOn = $result['results'][$i]["deliveredOn"];
                    }else{
                        $deliveredOn = "0";
                    }
                    
                    //Calcul de la différence entre $shippedOn et $deliveredOn
                    $debut = strtotime($shippedOn);
                    $fin = strtotime($deliveredOn);
                    $diffDate = ceil(abs($fin - $debut) / 86400);

The values that I need are : min, max, average for Number of days

How can I do that ?

Thanks

How can i solve it?

It’s giving me error:
Warning: Undefined array key “id” in D:xampphtdocsBlogFulladminedit-user-logic.php on line 5

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘LIMIT 1’ at line 1 in D:xampphtdocsBlogFulladminedit-user-logic.php:14 Stack trace: #0 D:xampphtdocsBlogFulladminedit-user-logic.php(14): mysqli_query(Object(mysqli), ‘UPDATE users SE…’) #1 {main} thrown in D:xampphtdocsBlogFulladminedit-user-logic.php on line 14

I tried replacing single quotes with ` , but it didn’t help

<?php 
require 'config/database.php';

if(isset($_POST['submit'])) {
    $id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
    $firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $lastname = filter_var($_POST['lastname'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $is_admin = filter_var($_POST['userrole'], FILTER_SANITIZE_NUMBER_INT);

    if(!$firstname || !$lastname) {
        $_SESSION['edit-user'] = "Invalid form input on edit page.";
    } else {
        $query = "UPDATE users SET firstname='$firstname', lastname='$lastname', is_admin=$is_admin WHERE id=$id LIMIT 1";
        $result = mysqli_query($connection, $query);

        if(mysqli_errno($connection)) {
            $_SESSION['edit-user'] = "Failed to update user.";
        } else {
            $_SESSION['edit-user-success'] = "User $firstname $lastname updated sucessfully";

        }

    }
}

header('location: ' . ROOT_URL . 'admin/manage-users.php');
die();

Check for a database update using PHP and AJAX

I have a website where when the user clicks a canvas, he draws on it and it gets pushed into the database. And it draws for every user 10 times in one second.

        setInterval(function(){
        $.ajax({
            url: 'data/canvasSave.php',
            success: function(data) {
                $('.result').html(data);
                console.log(data);
                imageCanvas = data;
            }
        });
        let img = new Image();
        img.src = imageCanvas; 
        context.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0 , 0, canvas.width, canvas.height);
    }, 100);
    

Now I notice that this isn’t the best way. But is there a good way to check for Database updates?
I tried a few if statements but none of them really worked.

Getting random alphabets and number in the output instead of xml

I am trying to authenticate the UIDAI API 2.5. But instead of getting response XML, I am getting random numbers and alphabets and it’s also not showing any error.

I think it is happening in the XMLdSig section, if I remove it I am not getting any output.

Also, I did not need to hit any URL to get the response so I have commented the CURL section for now

Output

This is the documentation for better understanding of the above XML uidai.gov.in/images/resource/aadhaar_authentication_api_2_5.pdf

<?php
    require_once 'xmlseclibs/xmlseclibs.php';
    use RobRichardsXMLSecLibsXMLSecurityDSig;
    use RobRichardsXMLSecLibsXMLSecurityKey;
    
    // certificate file locations
    $public_certif = 'uidai_auth_stage.cer';
    $stag_sign_file = 'Staging_Signature_PrivateKey.p12';
    
    // set variables
    $aadhaar_no = '999999990019';
    $api_version = "2.5";
    $asa_license_key = "MMxNu7a6589B5x5RahDW-zNP7rhGbZb5HsTRwbi-VVNxkoFmkHGmYKM";
    $lk = "MBni88mRNM18dKdiVyDYCuddwXEQpl68dZAGBQ2nsOlGMzC9DkOVL5s";
    $ac = "public";
    $sa = "public";
    $tid = "public";
    $txn = "AuthDemoClient:public:".date("Ymdhms");
    $ts = date('Y-m-d').'T'.date('H:i:s');
    
    // PID Block
    $pid_block='<?xml version="1.0"?><Pid ts="'.$ts.'"><Demo><Pi ms="E" mv="100" name="Shivshankar Choudhury"/></Demo></Pid>';
    
    // generate aes-256 session key
    $session_key = openssl_random_pseudo_bytes(32);
    
    
    // generate auth xml
    $auth_xml = '<?xml version="1.0" encoding="UTF-8"?><Auth uid="'.$aadhaar_no.'" ac="'.$ac.'" lk="'.$lk.'" sa="'.$sa.'" tid="'.$tid.'" txn="'.$txn.'" ver="'.$api_version.'"><Uses bio="n" otp="n" pa="n" pfa="n" pi="y" pin="n"/><Meta fdc="NA" idc="NA" lot="P" lov="560094" pip="NA" udc="1122"/><Skey ci="'.certif_expire().'">'.encrypt_session_key($session_key).'</Skey><Data type="X">'.encrypt_pid($pid_block, $session_key).'</Data><Hmac>'.calculate_hmac($pid_block, $session_key).'</Hmac></Auth>';
    
    //echo $auth_xml;
     //die();
    // $xml=simplexml_load_string($auth_xml) or die("Error: Cannot create object");
    //print_r($xml);
    
    // xmldsig the auth xml
    $doc = new DOMDocument();
    $doc->loadXML($auth_xml);
    $objDSig = new XMLSecurityDSig();
    $objDSig->setCanonicalMethod(XMLSecurityDSig::C14N);
    $objDSig->addReference(
        $doc,
        XMLSecurityDSig::SHA256,
        array(
            'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
            'http://www.w3.org/2001/10/xml-exc-c14n#'
        ),
        array('force_uri' => true)
    );
    $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, array('type'=>'private'));
    openssl_pkcs12_read(file_get_contents($stag_sign_file), $key, "public");
    $objKey->loadKey($key["pkey"]);
    $objDSig->add509Cert($key["cert"]);
    $objDSig->sign($objKey, $doc->documentElement);
    
    
    // make a request to uidai
    //$ch = curl_init("http://auth.uidai.gov.in/$api_version/public/".$aadhaar_no[0]."/".$aadhaar_no[0]."/$asa_license_key");
    //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($ch, CURLOPT_POST, 1);
    //curl_setopt($ch, CURLOPT_POSTFIELDS, $doc->saveXML());
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      "Accept: application/xml",
      "Content-Type: application/xml"
    ));
    //echo "nRequest XMLn";
    echo $doc->saveXML();
    echo "nn";
    //echo "Response from UIDAIn";
    //echo htmlspecialchars_decode(curl_exec($ch));
    
    
    
    function encrypt_pid($pid_block, $session_key)
    {
        return encrypt_by_session_key($pid_block, $session_key);
    }
    
    function encrypt_by_session_key($data, $session_key)
    {
        global $public_certif;
        $data = openssl_random_pseudo_bytes(128, $cryptStrength);

        $publicKeyRes = openssl_pkey_get_public(file_get_contents($public_certif));
        $publicKeyDetails = openssl_pkey_get_details($publicKeyRes); // openssl_pkey_get_details
        $res = openssl_public_encrypt($data, $crypted, $publicKeyDetails['key']);
        $session_key = base64_encode($crypted); 
    
    }
    
    function calculate_hmac($data, $session_key)
    {
        return encrypt_by_session_key(hash('sha256', $data, true), $session_key);
    }
    
    function certif_expire()
    {
        global $public_certif;
        $certinfo = openssl_x509_parse(file_get_contents($public_certif));
        return date('Ymd', $certinfo['validTo_time_t']);
    }
    
    function encrypt_session_key($session_key)
    {
        global $public_certif;
        $pub_key = openssl_pkey_get_public(file_get_contents($public_certif));
        $keyData = openssl_pkey_get_details($pub_key);
        openssl_public_encrypt($session_key, $encrypted_session_key, $keyData['key'], OPENSSL_PKCS1_PADDING);
        return base64_encode($encrypted_session_key);
    }

The admin panel is not opening when i host my website online but in xampp it is working fine

this is my login page code my project is in CodeIgniter

<!DOCTYPE html>
<html lang="en">
<head>        
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
    <!--[if gt IE 8]>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <![endif]-->
    
    <title>Login - Admin Panel</title>

    <?php  ?>
    
    <link href="<?php echo $this->config->item('assets_url');?>css/stylesheets.css" rel="stylesheet" type="text/css" />
    
        <link href="<?php echo $this->config->item('assets_url');?>css/ie7.css" rel="stylesheet" type="text/css" />
   
    <link rel='stylesheet' type='text/css' href='<?php echo $this->config->item('assets_url');?>css/fullcalendar.print.css' media='print' />
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/jquery/jquery-1.9.1.min.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/jquery/jquery-ui-1.10.1.custom.min.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/jquery/jquery-migrate-1.1.1.min.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/jquery/jquery.mousewheel.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/cookie/jquery.cookies.2.2.0.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/bootstrap.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/charts/excanvas.min.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/charts/jquery.flot.js'></script>    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/charts/jquery.flot.stack.js'></script>    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/charts/jquery.flot.pie.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/charts/jquery.flot.resize.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/sparklines/jquery.sparkline.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/fullcalendar/fullcalendar.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/select2/select2.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/uniform/uniform.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/maskedinput/jquery.maskedinput-1.3.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/validation/languages/jquery.validationEngine-en.js' charset='utf-8'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/validation/jquery.validationEngine.js' charset='utf-8'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/mcustomscrollbar/jquery.mCustomScrollbar.min.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/animatedprogressbar/animated_progressbar.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/qtip/jquery.qtip-1.0.0-rc3.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/cleditor/jquery.cleditor.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/dataTables/jquery.dataTables.min.js'></script>    
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/fancybox/jquery.fancybox.pack.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/pnotify/jquery.pnotify.min.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins/ibutton/jquery.ibutton.min.js'></script>
    
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/cookies.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/actions.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/charts.js'></script>
    <script type='text/javascript' src='<?php echo $this->config->item('assets_url');?>js/plugins.js'></script>
    
</head>
<body>
    <div class="loginBlock" id="login" style="display: block;">
        <h1>Welcome! Please Sign In</h1>
        <div class="dr"><span></span></div>
        <div class="loginForm">
            <?php $this->load->view('admin/includes/message'); ?>
            <?php echo form_open('admin/session/login', array('class' => 'form-horizontal')); ?>
                
                <div class="control-group">
                    <div class="input-prepend">
                        <span class="add-on"><span class="icon-envelope"></span></span>
                        <input type="text" name="Email" id="Email" placeholder="Email" value="<?php echo set_value('Email') ?>" class="validate[required]"/>
                    </div>                
                </div>
                <div class="control-group">
                    <div class="input-prepend">
                        <span class="add-on"><span class="icon-lock"></span></span>
                        <input type="password" name="Password" id="Password" placeholder="Password" class="validate[required]"/>
                    </div>
                </div>
                <div class="row-fluid">
                    <div class="span8">
                        <div class="control-group" style="margin-top: 5px;">
                            <!--<label class="checkbox"><input type="checkbox"> Remember me</label>-->                                                
                        </div>                    
                    </div>
                    <div class="span4">
                        <button type="submit" class="btn btn-block">Sign in</button>       
                    </div>
                </div>
            <?php echo form_close(); ?>  
            <div class="dr"><span></span></div>
            <div class="controls">
                <div class="row-fluid">
                    <div class="span6">
                        <button class="btn btn-link btn-block" onClick="loginBlock('#forgot');">Forgot your password?</button>
                    </div>
                    <div class="span2"></div>
                    <div class="span4"></div>
                </div>
            </div>
        </div>
    </div>    
    
    <div class="loginBlock" id="forgot">
        <h1>Forgot your password?</h1>
        <div class="dr"><span></span></div>
        <div class="loginForm">            
            <?php echo form_open('admin/session/forgot_password', array('class' => 'form-horizontal')) ?>
                <p>This form help you return your password. Please, enter your password, and send request</p>
                <div class="control-group">
                    <div class="input-prepend">
                        <span class="add-on"><span class="icon-envelope"></span></span>
                        <input type="text" placeholder="Your email" name="Email" value="<?php echo set_value('Email') ?>"/>
                    </div>                
                </div>                
                <div class="row-fluid">
                    <div class="span8"></div>
                    <div class="span4">
                        <button type="submit" class="btn btn-block">Send request</button>       
                    </div>
                </div>
            <?php echo form_close(); ?>  
            <div class="dr"><span></span></div>
            <div class="controls">
                <div class="row-fluid">                    
                    <div class="span12">
                        <button class="btn btn-link" onClick="loginBlock('#login');">&laquo; Back</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
</body>
</html>

this is code for my admin panel login session

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Session extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('employee_model');
        $this->load->model('autoresponder_model');
    }

    public function index()
    {
        if( $this->session->userdata('is_admin_logged_in') === FALSE)
            $this->load->view("admin/login");
        else
            redirect('admin');
    }

    public function login()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('Email', 'Email', 'trim|required|valid_email|min_length[4]');
        $this->form_validation->set_rules('Password', 'Password', 'trim|required|min_length[4]|max_length[32]');

        if ($this->form_validation->run() !== FALSE)
        {
            $result = $this->employee_model->get_where(
                        array(
                            'Email' => $this->input->post('Email'),
                            'Password' => md5($this->input->post('Password')),
                            'Status' => 'Enabled'
                        )
                    );
            
            if (count($result)>0)
            {
                $data = array(
                    'employee_id' => $result[0]["ID"],
                    'full_name' => $result[0]["FirstName"]." ".$result[0]["LastName"],
                    'email' => $result[0]["Email"],
                    'is_admin_logged_in' => TRUE
                );
                $this->session->set_userdata($data);
                
                if($this->input->post('return_url')!="")
                    redirect($this->input->post('return_url'));
                else
                    redirect("admin");
            }
            $this->session->set_flashdata("error", "Invalid Email or Password");
            redirect("admin/session");
        }
        $this->index();
    }

    public function forgot_password()
    {
        $this->load->library('form_validation');    
        $this->form_validation->set_rules('Email', 'Email', 'trim|required|valid_email|min_length[4]');
        if($this->form_validation->run() !== FALSE)
        {
            $email = $this->input->post('Email',TRUE);
            $employee = $this->employee_model->get_where(array('Email'=> $email, 'Status' => 'Enabled'));           
            if(count($employee)>0)
            {
                $token = $employee[0]['ID']."-".rand(12345,54321); 
                $this->employee_model->update(array('Token' => $token), $employee[0]['ID']);
                
                ## Get Issue Email Template ##
                $data = $this->autoresponder_model->get_where(array('Status' => 'Enabled', 'ID' => 4)); // Forgot Password Token Email                  
                ## Send Email with Template ##      
                if(isset($data) && count($data)>0)
                {
                    $from_name = $data[0]['FromName'];
                    $from_email = $data[0]['FromEmail'];
                    $to_email = $data[0]['ToEmail'];
                    $subject = $data[0]['Subject'];
                    $message = html_entity_decode($data[0]['Message']);
                    
                    //Information
                    $post['TOKEN_URL'] = site_url('admin/session/set_password/'.$token);
                    $post['FirstName'] = $employee[0]['FirstName'];
                    $post['LastName'] = $employee[0]['LastName'];
                    $post['Email'] = $employee[0]['Email'];
            
                    $this->fsd->email_template($post, $from_email, $from_name, $to_email, $subject, $message );
                    $this->fsd->sent_email($from_email, $from_name,$to_email, $subject, $message );
                    
                    $this->session->set_flashdata("success","An email has been sent to your account.");
                    redirect('admin/session/login');                        
                }                   
            }           
        }
        $this->session->set_flashdata("error", "Invalid email address.");
        redirect('admin/session/');
    }

    public function set_password($token)
    {
        if(empty($token))
            redirect('admin/session/');
        $data = $this->employee_model->get_where(array('Token'=> $token, 'Status' => 'Enabled'));
        if(count($data) > 0)
        {
            $length = 8;
            $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
            ## Get Issue Email Template ##
            $template = $this->autoresponder_model->get_where(array('Status' => 'Enabled', 'ID' => 5)); // Forgot Password Token Email                  
            ## Send Email with Template ##      
            if(isset($template) && count($template)>0)
            {
                $from_name = $template[0]['FromName'];
                $from_email = $template[0]['FromEmail'];
                $to_email = $template[0]['ToEmail'];
                $subject = $template[0]['Subject'];
                $message = html_entity_decode($template[0]['Message']);
                
                //Information
                $post['Password'] = $password;
                $post['FirstName'] = $data[0]['FirstName'];
                $post['LastName'] = $data[0]['LastName'];
                $post['Email'] = $data[0]['Email'];
        
                $this->fsd->email_template($post, $from_email, $from_name, $to_email, $subject, $message );
                $this->fsd->sent_email($from_email, $from_name,$to_email, $subject, $message );
                
                $userdata = array('Token' => NULL, 'Password' => md5($password) );
                $update = $this->employee_model->update($userdata, $data[0]['ID']);
                $this->session->set_flashdata("success", "Your new password has been sent to your email account.");
                redirect('admin/session/');                     
            }                               
        }
        $this->session->set_flashdata("error","Invalid token URL.");
        redirect('admin/session/');
    }
    
    public function logout()
    {
        $this->session->sess_destroy();
        $this->index();
    }
}

when i want to open the admin panel it bring only blank page i also tried to allow php error option in hosting but it is also not working but in xampp localhost it is working fine can you tell me what is the error in my code

Finding a way to preg_match all special letters

Basically I was trying to preg_match all Letters and special letters for example: ä,â,ã… But I‘ve come across to a problem. Preg_Matching only letters was pretty easy since you only need the following code: preg_match("/^[a-zA-Z]+$/") the hard part was when adding all special letters. I‘ve come across some methods like preg_match("/^[äöü ÄÖÜ a-z-]+$/") to manually preg_match some special letters but isn’t there something like a syntax that can preg_match all of the special letter?

How to check if a web page is open or not?

I have a website where users message each other through another website. My problem is that everytime user click on message item this action opens a new tab.
Having a lot of conversations makes this quite annoying, especially when using on a smartphone.
Is there any way to check if the website for texting is open ???
<< JS >>

PHP setcookie doesnt set a Cookie [duplicate]

Problem:
I got a pretty popular Problem. I want my site to set a Cookie. (with setcookie())
The last Days it was working fine, but now the cookie doesn’t appear.
I Tried everything in the past three hours but no success.

I Tried:

  • setcookie with all parameters
  • setcookie with minimal parameters
  • different parameters
  • with and without ob_start()
  • set it before any outputs or HTML-Elements (before !doctype)
  • I checked, that it’s a document without BOM
  • different browsers
  • I took it out from any brackets
  • I Checked my Browser for Blockers

I would surrender if it wasn’t an important project for me.

My current Code:

<?php
    function generateRandomString($length = 10) 
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++)
        {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }


    $token = generateRandomString(16);

    setcookie("cookiename", $token, time()+(24*3600), '/');

?>

The lines to read the Cookie are on another site. (SAME DOMAIN, OTHER PAGE)
But there, I never manipulate or delete it.
I permanently check my Dev-Tools in the Browser but theres no Cookie.

How to conver string to int in implode combinate with array_filter and array_map

How can i remove text from values ? i like values of array to be numbers only.

        $arr = Array(
            '39' => Array(
                    '0' => '307'
                    ),
            '42' => Array(
                    '0' => '329ds',
                    '1' => '300'
                    )
               );

$result = implode(",", array_filter(array_map(function($v){
  return implode(",", array_filter($v));
}, $arr)));

echo $result;

//result: 307,329ds,300

i tried to add (int) on implode() and its working but returning only 2 numbers instead of 3 numbers

            $arr = Array(
            '39' => Array(
                    '0' => '307'
                    ),
            '42' => Array(
                    '0' => '329ds',
                    '1' => '300'
                    )
               );

$result = implode(",", array_filter(array_map(function($v){
  return (int)implode(",", array_filter($v));
}, $arr)));

echo $result;

//result: 307,329

Need to Add Additional TAX for Shipping in Woocommerce

I am using this plugin in that we already implemented based on weight we have added the shipping charges now in addition to that we need to add the tax for the shipping charges also?

https://wordpress.org/plugins/flexible-shipping/

Now in addition to that, we need to add one more additional Tax for the shipping items

please find the attached link for the reference screenshot

https://nimb.ws/as23CH

so already based on weight we are charging the shipping charge now in addition to that we need to add tax for the shipping charges items also

for ex: the shipping charge is Rs.60 for less than 500kg order items so for the Rs: 60 we need to add additional 18%

Rs. 60 + 18% (Rs.10.8) = Total Rs. 70.80 likewise It has to come.

Also, I need to display that as Shipping Tax on the site also after the shipping charges I need to mention Shipping tax also on the site and the invoice in both areas.

Any suggestion on this will be most welcome to solve this issue.

Also, any other plugin suggestions which you mentioned can you say the plugin names will try those

Thanks in advance