Question

I want to remove all customers that have the following string in their first name: 'http://' (spam customers that have links in their first names).

Is there a good way to remove these programmatically using a setup script in Magento 2?

There must be a better way than to get the filtered customer collection and delete them one by one right?

--------- UPDATE -----------

I am currently using the following method. It works, but it takes quite some time:

/**
 * Remove Customers with links (http:// or https://) in their names
 */
private function removeFakeCustomers()
{
    $this->registry->register('isSecureArea', true);
    $customers = $this->customerFactory->create();
    $customers->addFieldToFilter(
        'firstname',
        [
            ['like' => '%http://%'],
            ['like' => 'http://%'],
            ['like' => '%https://%'],
            ['like' => 'https://%']
        ]
    );

    if (!$customers) {
        return;
    }

    echo 'Start removing fake customers...';

    foreach ($customers as $customer) {
        $customer->delete();
    }

    echo 'Fake Customers removed...';
}
Was it helpful?

Solution

create one script file test.php in magento root folder.

<?php 
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

try
{
    $OM = \Magento\Framework\App\ObjectManager::getInstance();
    $collectionobj = $OM->create('\Magento\Customer\Model\Customer');
    $customercollection = $collectionobj->getCollection()
            ->addAttributeToSelect("*")
            ->addAttributeToFilter("firstname", array("like" => "%http%"));
    foreach($customercollection as $customer)
    {
       $customer->delete();
    }

}
catch(\Exception $e)
{
    echo $e->getMessage();
    exit;
}

Run these file from browser like www.domain.com/test.php

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top