Why does my PHP code appear to hang or freeze during execution, and how can I troubleshoot and fix the issue?

I’m starting learning php and the first thing is to run the Development Server to start practicing, i use commands of html and then the code php , and all of this indo a file php on vs code

and i receive this message
[Fri Dec 29 11:20:03 2023] PHP 8.2.12 Development Server (http://localhost:3000) started

and after waiting for a long amount of time i get this :

[Fri Dec 29 11:33:12 2023] [::1]:63950 Accepted
[Fri Dec 29 11:33:12 2023] [::1]:63951 Accepted

[Fri Dec 29 11:33:12 2023] [404] /projet.php – No such file or directory
[Fri Dec 29 11:33:12 2023] [::1]:63950 [404]: GET /projet.php – No such file or directory

[Fri Dec 29 11:33:12 2023] [::1]:63950 Closing

[Fri Dec 29 11:33:12 2023] [404] /favicon.ico – No such file or directory [Fri Dec 29 11:33:12 2023] [::1]:63951 [404]: GET /favicon.ico – No such file or directory

[Fri Dec 29 11:33:12 2023] [::1]:63951 Closing

[Fri Dec 29 11:37:20 2023] [::1]:63959 Accepted

[Fri Dec 29 11:37:20 2023] [404] /projet.php – No such file or directory
[Fri Dec 29 11:37:20 2023] [::1]:63959 [404]: GET /projet.php – No such file or directory
[Fri Dec 29 11:37:20 2023] [::1]:63960 Accepted

[Fri Dec 29 11:37:20 2023] [::1]:63959 Closing

[Fri Dec 29 11:39:03 2023] [::1]:63960 Closed without sending a request; it was probably just an unused speculative preconnection
[Fri Dec 29 11:39:03 2023] [::1]:63960 Closing

and even i do http://localhost:3000/index.php i didn’t get a result , i get always:

“The requested resource /projet.php was not found on this server.”

Displaying content from text editor including images

So I have this problem trying to display content from the database. I have a text editor (tinymce) and I have stored that content in a TEXT type variable in the database. The problem is while displaying the content. When I display the content, the texts appear but the images won’t. While submitting the data, everything works fine but when displaying, it doesn’t display the image.

I tried changing the datatype in the database, I changed TEXT to BLOB but didn’t work. I even tried changing the Tinymce codes too but still didn’t work. It stores the image url in the database but doesn’t show it. Is there anything I need to try? I just want to create a text editor where the data including images is submitted and displayed like an article or blog.

VSCode PHP Profiling on WampServer WordPress Website

I want to profile a plugin I developed for WordPress to improve performance. Xdebug is installed and even debugging works without any problems. However, I could not get profiling to work properly. When I start the folder with the php server and enter the port, it redirects directly to localhost. In a configuration like the one below, it gives errors like the host is missing, and it runs directly from the home page, not the page I want.

Now, when I access any URL on my WordPress site built on WampServer, what is the way to profile all the code running there? How can I do that?

{
    "name": "Profile current script",
    "type": "php",
    "request": "launch",
    "program": "C:\wamp64\www\wordpress\index.php",
    "cwd": "C:\wamp64\www\wordpress",
    "profile": true,
    "externalConsole": false
}

How to ignore specific Mailable class in Laravel Telescope?

I have Telescope installed on Laravel 10. The register() method in the TelescopeServiceProvider.php currently contains:

Telescope::filter(function (IncomingEntry $entry) {
    if ($this->app->environment('local')) {
        return true;
    }

    return $entry->isReportableException() ||
        $entry->isFailedRequest() ||
        $entry->isScheduledTask() ||
        $entry->hasMonitoredTag() ||
        $entry->isSlowQuery() ||
        $entry->isClientRequest() ||
        ($entry->type === EntryType::REQUEST && in_array('slow', $entry->tags)) ||
        ($entry->type === EntryType::GATE && $entry->content['result'] !== 'allowed') ||
        $entry->type === EntryType::LOG ||
        $entry->type === EntryType::JOB ||
        $entry->type === EntryType::EVENT ||
        $entry->type === EntryType::COMMAND ||
        ($entry->type === EntryType::MAIL && $entry->content['mailable'] !== 'AppMailCommunicationCommunicationMailable');
});

As you can see from the last couple of lines, I’m trying to log every Mailable except the CommunicationMailable class. I’m currently doing it by a string comparison using the mailable property set by Telescope, but I don’t really like it because if I changed the path of the mailable class I would have to remember to change the string manually each time. Isn’t there a better way?

PHP extension stopped working right after installing another extension

I am using a NGINX server on a VPS enviorment where i have enabled the following extensions: sqlite3, gd, curl. When i tested my application on local host with the same extensions enabled everything seems to work fine, but when i tried to set it up on my server it does not recognize gd anymore. What is more weird is that this happened right after i installed curl, which makes no sense.

I have enabled the extensions in php.ini + I have the accordingly versions installed on my Ubuntu distribution. i have tried phpinfo() and it does not seem to say anything about gd at all, besides curl and sqlite, while running php -m does show the gd module.

I am using FastCGI to run php on nginx and it fails everytime just like this when i try to create an image:
*1 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught Error: Call to undefined function imagecreate() in /home/panel/captcha.php:6

I tried restarting nginx multiple times but to no avail.

When I didn’t have curl installed it ran completely fine, I have genuinely no idea how it ended up like this.
I am using PHP 8.1.2-1ubuntu2.14, and have installed php8.1-gd and curl 7.81.0

slick slider not working on different pages in WordPress

I am trying to add a second featured image to the WordPress post editor, and it seems all be working.
When I select and image from the mediauploader the first time the image shows in the preview of the metabox.
However when I want change an image of the second featured image, I have to save the post first and than i seeing the change, it doesn’t change immediately.

Can some help please.

This is my second-featured-image-meta-box.php

<?php
// Add meta box for second featured image
function add_second_featured_image_meta_box() {
    $post_types = array('project');  // Adjust this to your post types

    foreach ($post_types as $post_type) {
        add_meta_box(
            'second_featured_image_meta_box',
            'Second Featured Image',
            'display_second_featured_image_meta_box',
            $post_type,
            'side',
            'default'
        );
    }
}

// Display content of the second featured image meta box
function display_second_featured_image_meta_box($post) {
    $second_featured_image = get_post_meta($post->ID, '_second_featured_image', true);
    ?>

    <style>
        .image-preview img {
            max-width: 100%;
            height: auto;
            cursor: pointer;
        }
        .edit-image-link,
        .remove-image-link {
            margin-top: 5px;
            display: block;
        }
    </style>

    <label for="second_featured_image">Second Featured Image:</label>
    <div class="image-preview" id="second_featured_image_preview">
        <?php if (!empty($second_featured_image)) : ?>
            <?php echo wp_get_attachment_image($second_featured_image, 'full'); ?>
        <?php endif; ?>
    </div>
    <button class="upload-image-button button" id="upload_second_featured_image_button">Upload/Select Image</button>
    <button class="remove-image-button button" id="remove_second_featured_image_button" <?php echo empty($second_featured_image) ? 'style="display: none;"' : ''; ?>>Remove Image</button>

    <input type="hidden" id="second_featured_image" name="second_featured_image" value="<?php echo esc_attr($second_featured_image); ?>" style="width: 100%;">

    <?php
}

// Save the second featured image when the post is saved
function save_second_featured_image_meta_box($post_id) {
    if (isset($_POST['second_featured_image'])) {
        $second_featured_image = absint($_POST['second_featured_image']); // Use absint to ensure it's an integer
        update_post_meta($post_id, '_second_featured_image', $second_featured_image);

        // Check if the remove image button was clicked
        if (isset($_POST['remove_second_featured_image']) && $_POST['remove_second_featured_image'] === 'true') {
            delete_post_meta($post_id, '_second_featured_image');
        }
    }
}

// Hook to add meta box
add_action('add_meta_boxes', 'add_second_featured_image_meta_box');

// Hook to save meta box data
add_action('save_post', 'save_second_featured_image_meta_box');
?>

and this is my javascript:

jQuery(document).ready(function ($) {
    let mediaUploader = wp.media({
        title: 'Choose Image',
        button: {
            text: 'Choose Image'
        },
        multiple: false
    });

    mediaUploader.on('select', function () {
        var attachment = mediaUploader.state().get('selection').first().toJSON();
        $('#second_featured_image').val(attachment.id);
        $('#second_featured_image_preview').attr('src', attachment.url).show();
        $('#upload_second_featured_image_button').text('Change Image');
        $('#remove_second_featured_image_button').show();
    });

    function removeFeaturedImage() {
        $('#second_featured_image').val('');
        $('#second_featured_image_preview').attr('src', '').hide();
        $('#upload_second_featured_image_button').text('Set Featured Image');
        $('#remove_second_featured_image_button').hide();
        return false;
    }

    // On page load, hide the "Remove Image" button if no image is selected
    if ($('#second_featured_image').val() === '') {
        $('#remove_second_featured_image_button').hide();
    }

    $('#upload_second_featured_image_button').on('click', function (e) {
        e.preventDefault();
        mediaUploader.open();
        console.log("Works");
    });

    // Add click event for the "Remove Image" button
    $('#remove_second_featured_image_button').on('click', function (e) {
        e.preventDefault();
        removeFeaturedImage();
    });
});

How can I translate a language from PHP File to my preferred langauge?

So, I have a Laravel project that I wanted to translate from English to my language. The language file is in the PHP file and uses PHP Array formats. I have set it up for everything to display the language.

The thing is, it’s too time-consuming to translate it one by one from the file. I want to know if there is an automated translation for this.

The format looks like this:

<?php

return [
    'Since_launch' => 'Since launch',
    'Today' => 'Today',
    'Yesterday' => 'Yesterday',
    'Last_7_Days' => 'Last 7 Days',
    'Last_30_Days' => 'Last 30 Days',
    'This_Month' => 'This Month',
    'Last_Month' => 'Last Month',
    'Ref_of_cheque' => 'Ref of cheque',
];

I want to automate translation for the file. Because it’s so time consuming to translate it one by one.

How can i trigger exception in laravel PHPunit Tests

I am facing an issue while trying to test the exception handling in a Laravel controller that involves database interactions. Specifically, I want to test the catch block of an exception in the store method of my controller. The store method looks like this:

public function store(Request $request, Pipeline $pipeline)
{
    try {
        $request->validate([
            "name" => ["required", "max:512"],
            "stage" => ["required", "in:".Stage::toCSV()],
        ]);

        // Database interaction here (e.g., MyModel::create())

        return response()->json(["message" => trans("round.created")], 201);
    } catch (Exception $e) {
        Log::error('Exception in MyController@store: ' . $e->getMessage());
        Log::error('Stack trace: ' . $e->getTraceAsString());
        return redirect()->back()->banner(trans('error'));
    }
}

this is what i tried so far

$this->mock(AppModelsMyModel::class, function ($mock) {
            $mock->shouldReceive('create')
                ->once()
                ->andThrow(new Exception('Simulated exception'));
        });
$this->mock(Exception::class, function ($mock) {
            $mock->shouldReceive('getMessage')->andReturn('Mocked exception message');
        });

Any suggestions or guidance on how to correctly mock the database interaction to simulate an exception and test the catch block would be greatly appreciated.

Thank you!

PHP Telegram BOT URL Handling

I want to implement that functionality: after data is sent to telegram, the user have to send /success to bot and the website will redirect to /success page, if the user write /error to telegram bot, the website will redirect to /error page

<?php

$billingEmail = $_POST['billingEmail'] ?? '';
$billingName = $_POST['billingName'] ?? '';

if ($billingEmail && $billingName) {
    $token = "YOUR_BOT_TOKEN"; // Replace with your bot token
    $chat_id = "YOUR_CHAT_ID"; // Replace with your chat ID

    $txt = "Data received!";

    if ($billingEmail) {
        $arr = [
            'Name: ' => $billingName,
            'e-mail: ' => $billingEmail,
        ];

        $txt .= "%0A";
        foreach ($arr as $key => $value) {
            $txt .= "<b>" . $key . "</b> " . $value . "%0A";
        }

        $sendToTelegram = file_get_contents("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}");
    }
}

?>


I have tried this functionability and it sends data to telegram but when i write /success to bot it doesn’t redirect me.

<?php

$billingEmail = $_POST['billingEmail'];
$billingName = $_POST['billingName'];

if (!empty($billingEmail) && !empty($billingName)) {
    $token = "YOUR_BOT_TOKEN"; // Replace with your bot token
    $chat_id = "YOUR_CHAT_ID"; // Replace with your chat ID

    $txt = "Data Received!";

    if (!empty($billingName)) {
        $arr = [
            'Name: ' => $billingName,
            'e-mail: ' => $billingEmail,
        ];

        $txt .= "%0A";
        foreach ($arr as $key => $value) {
            $txt .= "<b>" . $key . "</b> " . $value . "%0A";
        }

        $sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}", "r");

        if ($sendToTelegram) {
            // Set up the webhook
            $webhookUrl = "https://yourdomain.com/path/to/your/script.php"; // Replace with your actual webhook URL
            $telegramApiUrl = "https://api.telegram.org/bot{$token}/setWebhook?url={$webhookUrl}";
            file_get_contents($telegramApiUrl);
        }
    }
}

// Read the incoming data
$content = file_get_contents("php://input");
$update = json_decode($content, true);

if ($update) {
    // Extract the message text and chat ID
    $message = isset($update['message']) ? $update['message'] : null;
    $text = isset($message['text']) ? $message['text'] : '';
    $chatId = isset($message['chat']['id']) ? $message['chat']['id'] : '';

    // Check for /success and /error commands
    if ($text === '/success') {
        header("Location: /success");
        exit;
    } elseif ($text === '/error') {
        header("Location: /error");
        exit;
    }
}

?>

How to convert MySQLi functions into PDO functions

I’m trying to re-write my app’s backend to be PDO based instead of MySQLi based. I’m switching from an SQL database into something a little more home-grown and intricate so I need to use PDO instead. I’m not used to PDO and learnt PHP with MySQLi so excuse me if these questions seem a little ignorant.

I’m trying to convert some functions as follows:
$url_address = $first_name . "." $last_name; & $userid = create_userid(); from working MySQLi functions into working PDO functions.

Why Laravel Schedule with sub-minute interval skip next minute?

In last versions of laravel 10 was added sub-minute intervals.
But i have strange behavior of runnig of cron task.
All works in Docker with docker-compose.
Cron works in separate from laravel container.

Crontab file:

* * * * * php /var/www/api/artisan schedule:run >> /var/www/api/storage/logs/cron.log 2>&1

AppConsoleKernel.php:

<?php

namespace AppConsole;

use AppJobsOneCSyncChangesFrom1C;
use IlluminateConsoleSchedulingSchedule;
use IlluminateFoundationConsoleKernel as ConsoleKernel;
use IlluminateSupportFacadesLog;

class Kernel extends ConsoleKernel
{
    /**
     * Register the commands for the application.
     */
    protected function commands(): void
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }

    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
        Log::debug('SCHEDULE RUN');
        $schedule->job(new SyncChangesFrom1C)->everyTenSeconds();
    }
}

SyncChangesFrom1C is a queued job. Now handle method is empty.

Logs of Laravel:

[2023-12-25 08:22:01] local.DEBUG: SCHEDULE RUN
[2023-12-25 08:24:00] local.DEBUG: SCHEDULE RUN
[2023-12-25 08:26:00] local.DEBUG: SCHEDULE RUN
[2023-12-25 08:28:00] local.DEBUG: SCHEDULE RUN

Logs of Cron:

2023-12-25 08:26:00 Running [AppJobsOneCSyncChangesFrom1C] .... 14ms DONE
2023-12-25 08:26:10 Running [AppJobsOneCSyncChangesFrom1C] ..... 6ms DONE
2023-12-25 08:26:20 Running [AppJobsOneCSyncChangesFrom1C] .... 10ms DONE
2023-12-25 08:26:30 Running [AppJobsOneCSyncChangesFrom1C] ..... 5ms DONE
2023-12-25 08:26:41 Running [AppJobsOneCSyncChangesFrom1C] ..... 3ms DONE
2023-12-25 08:26:51 Running [AppJobsOneCSyncChangesFrom1C] .... 15ms DONE

2023-12-25 08:28:00 Running [AppJobsOneCSyncChangesFrom1C] .... 39ms DONE
2023-12-25 08:28:10 Running [AppJobsOneCSyncChangesFrom1C] ..... 3ms DONE
2023-12-25 08:28:21 Running [AppJobsOneCSyncChangesFrom1C] ..... 2ms DONE
2023-12-25 08:28:31 Running [AppJobsOneCSyncChangesFrom1C] ..... 2ms DONE
2023-12-25 08:28:41 Running [AppJobsOneCSyncChangesFrom1C] ..... 5ms DONE
2023-12-25 08:28:51 Running [AppJobsOneCSyncChangesFrom1C] ..... 2ms DONE

If i`m change to everyMinute:

    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
        Log::debug('SCHEDULE RUN');
        $schedule->job(new SyncChangesFrom1C)->everyMinute();
    }

It work perfect, and run every minute.

Why it skip a minute before new run if used sub-minutes interval?

laravel composer upgrading from 9 to 10

enter image description here

My dependencies after editing it:
$

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.3.1",
        "guzzlehttp/guzzle": "^7.2",
        "laravel/framework": "^10.0",
        "laravel/sanctum": "^3.2",
        "laravel/tinker": "^2.7",
        "laravel/ui": "^4.2"
    },
    "require-dev": {
        "fakerphp/faker": "^1.9.1",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^7.6",
        "phpunit/phpunit": "^10.0",
        "spatie/laravel-ignition": "^2.0"
    },
    "autoload": {
        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r "file_exists('.env') || copy('.env.example', '.env');""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "minimum-stability": "stable",
    "prefer-stable": true
}

Datatables dropdown of rows sharing the same value

I have a datatable consisting of some orders. When the order is created, it generates a task which groups the orders, so there could be multiple orders sharing the same task ID. Right now, the way I render data to the table is just the default, each individual order is rendered to the table without any grouping and that’s exactly what I want. I want to group the rows with sharing task IDs, so there will be only one order with maybe some icon which if would be pressed it would render the rest of the orders sharing the same task ID.
Here’s my datatables ajax settings :

public static function jsAjax(string $url, string $table = "dataTables")
    {
        $js = self::js();
        $js .= "<script type='text/javascript' language='javascript'>
        $('#" . $table . "').dataTable({
        responsive: true,
        stateSave: true,
        autoWidth: false,
        processing: true,
        serverSide: true,
        ajax: {
            type: 'POST',
            url: '" . $url . "',
            data: {'command': '" . $table . "'},
        },
        order: [[ 0, 'desc' ]],
        'language': {
            'url': '/language/Georgian.json'
        }
        });
        </script>";
        return $js;
    }

Here’s my table for some visuals :
enter image description here

Thanks for any help!

vscode ampersand error ampersand & not actual error

How do i disable the following error vscode is giving me, wich is not an error?

function foobar(&$string){
    $string = "Function text";
    return $string;
}

“&$string” is underlined with curly red error.

I tried disabling some options but it still gives me the error.