Loading in script tag from seperate php file does not work

Part of Main php-file:

    <script>
        let current_effect;

        function getRandomEffect() {
            let effect;
            do {
                effect = Math.floor(Math.random() * 3);
            } while (effect === current_effect);
            return effect;
        }

        function updateEffectContainer(effect) {
            // Construct the filename of the PHP file for the specified effect
            const filename = 'effect' + effect + '.php';

            // Load the HTML content from the PHP file using AJAX
            fetch(filename)
                .then(response => response.text())
                .then(html => {
                    // Update the effect container with the HTML content
                    document.getElementById("effect-container").innerHTML = html;
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }

        document.getElementById("changeEffectButton").addEventListener("click", function () {
            current_effect = getRandomEffect();
            updateEffectContainer(current_effect);
        });

        current_effect = getRandomEffect();
        updateEffectContainer(current_effect);
    </script>

effect0.php:

<p>test</p>
<script type="text/javascript">
    alert(test-alert);
</script>

The main PHP file selects an effect [0||1||2] when the site is loaded and when the “changeEffectButton” button is pressed. I can see “test” being displayed (in the case that effect0.php is chosen), but no alert window pops up.

Any idea why and how to fix it?

Thanks for every input! ^^

Pub/Sub between PHP server and React client using FCM

I have been trying to set up a messaging system between my PHP server and React front end. I managed to publish messages from the PHP server as can be seen in the Metrics:
FCM API metrics showing API requests from PHP server

The issue I am facing is that I can not receive the messages from React, as per the documentation for the client SDK, there are functions for messaging. But the same page also mentions that I need to use the admin SDK instead??

As for the admin SDK I can not use it since it requires me to upgrade React in my project which can lead to issues.

Modsecurity shared hosting false positive – input form with POST

I have simple HTML POST form with text input which is triggering modsecurity deny rule remote file inclusion for following input:

https://wa.me/111111111?text=Olá Katarina, tudo bem?

The end question mark is problematic. If I delete it – it’s not blocked. Basically if the input ends with question mark – is denied. If I add space it will pass.

It’s a shared webhosting.
What can I do? Can I do something with headers to prevent being blocked by firewall? (The only thing I have in my mind is to use double URL encoding.

ModSecurity: Access denied with code 429 (phase 2). Operator GE matched 5 at TX:anomaly_score. [file "/usr/share/modsecurity-crs-new/rules/REQUEST-949-BLOCKING-EVALUATION.conf"] [line "93"] [id "949110"] [msg "Inbound Anomaly Score Exceeded (Total Score: 5)"] [severity "CRITICAL"] [ver "OWASP_CRS/3.3.2"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-generic"]

ModSecurity: Warning. Operator GE matched 5 at TX:inbound_anomaly_score. [file "/usr/share/modsecurity-crs-new/rules/RESPONSE-980-CORRELATION.conf"] [line "91"] [id "980130"] [msg "Inbound Anomaly Score Exceeded (Total Inbound Score: 5 - SQLI=0,XSS=0,RFI=5,LFI=0,RCE=0,PHPI=0,HTTP=0,SESS=0): individual paranoia level scores: 5, 0, 0, 0"] [ver "OWASP_CRS/3.3.2"] [tag "event-correlation"]

<!DOCTYPE html>
<html>
<head>
  <title>My Form</title>
</head>
<body>
  <form action="test2.php" method="post">
    <input type="text" name="my_text">
    <input type="submit" value="Submit">
  </form>
</body>
</html>

Examples of when PHP calls the function set by set_exception_handler with an Error object? And is it always fatal? Can it be caught? [duplicate]

I’m trying to write a handler for exceptions. I’ve noticed that sometimes it’s passed an Error object. (As opposed to an Exception object). I’d like to know:

  1. Some examples of what triggers this to happen
  2. Whether when an Error object is passed to the exception handler, is it always fatal?
  3. Can the Error object being thrown be caught, stopping it from being fatal? And if it isn’t caught, is it always fatal?

Thanks

How to resend those emails which fails to dispatch from Laravel?

In my laravel server mail sometimes fails to deliver to recipients and I want to resend those emails until they send successfully to them, I want to manage it globally for whole app without using database help.

P.S. I’m using Laravel default Mail helper function in Laravel 6.2

I’ve tried with using try catch everywhere Mail helper function has been used, but this is something long and weird from code perspective.

laravel unique validation with both singular and plural words

I want laravel to check for uniqueness of words in the database table for both singular and plural of a word. That is only one instance of either singular or plural word should exist. For example If user enters chocolate and if database has chocolates or chocolate then the validation should fail. The reason for this is that the data is stored in database as a plural of word.So when user enters singular word then validation passes but it actually gets stores as plural. Here is my code.

 public function update(Request $request, Category $category)
        {
            if (!$request->hasAny('category_status')){
                $this->validate($request, [
                    'category_name' => [
                    'required','max:255',
    
                    Rule::unique('categories', 'category_name')->where(function ($query) {
                    $categoryName = Str::plural(request()->category_name);
                    return $query->where('category_name', $categoryName);
                })->ignore($category)
    
                ],
                ]);
            }
    
       
    
         $category->update($request->all());
            return response()->json(['response'=>__('message.update',['name'=>'category'])]);
        }

The above code only works for exact unique and ignore current model instance. For example if user enters chocolate and database has chocolate than it fails but if it has chocolates only than it passes. I want it to fail for both singular and plural. Thank you

laravel ErrorException Trying to get property ‘image_one’ of non-object

ErrorException
Trying to get property ‘image_one’ of non-object (View: C:xampphtdocsecommerceresourcesviewslayoutsslider.blade.php)

IlluminateFoundationBootstrapHandleExceptions::handleError
C:xampphtdocsecommerceresourcesviews/layouts/slider.blade.php:15

image_one )}}” alt=”” style=”height: 450px;” >

IlluminateViewEnginesPhpEngine::evaluatePath
C:xampphtdocsecommercevendorlaravelframeworksrcIlluminateViewEnginesPhpEngine.php:43

include $__path;

IlluminateViewEnginesCompilerEngine::get
C:xampphtdocsecommercevendorlaravelframeworksrcIlluminateViewEnginesCompilerEngine.php:59

$results = $this->evaluatePath($compiled, $data);

how can I escape from this problem
ErrorException
Trying to get property ‘image_one’ of non-object (View: C:xampphtdocsecommerceresourcesviewslayoutsslider.blade.php)

PHP Measure function memory usage

I want to measure how much memory my function is using. As I want to do 10 iterations I’m using for loop for this. The problem is that after first iteration memory usage is always the same. What should I do that memory is calculated as first iteration to calculate averages?

My code snippet:

for ($i = 0; $i < 10; $i++) {
    $memoryStart = memory_get_usage();
    $basketsWithFilter = $customer->getBasketsExceedTotal(total: 5);
    $memoryEnd = memory_get_usage() - $memoryStart;
    $memoryWithFilter[] = round($memoryEnd / 1024);
}

In the array results are the following
17, 2, 2, 2, 2, 2, 2, 2, 2, 2

How to get exact search results using query, including the searching length and the data length from database?

Route::any ( '/search', function () {
    $q = Input::get ( 'q' );
    if($q != "" ){
        $user = Customer::where ( 'email', 'LIKE', '%' . $q . '%' )->orWhere ( 'remarks', 'LIKE', '%' . $q . '%' )->get ();
        if (count ( $user ) > 0)
            return view ('search')->withDetails ( $user )->withQuery ( $q );
        else
            return view ('search')->withMessage ( 'Oops' );
    };
    return view ('search')->withMessage ( 'Oops' );
} );

How can I get the exact search results? For example, if the database consists of multiple phone numbers, the search results will only return the results for my data input (e.g. when I search for “1”, a single number, the database should display “Oops” if no ‘1’ is found and yes if ‘1’ is found. It should not include “x1xxxxx”,”1x”,”xxxxx1″ and so on as the search results. Currently my search results returned me a various data consists of ‘1’. Please help!Thank you!

PHP Scaping data from a webpage

I have tried a couple of things for trying to scrape data from the following page https://app.hotspotty.net/hotspots/11euSptu1Ee3HgDCMfepYELwWMGMqkNdD9DQJqKbzPkasFebGne/rewards i am interested in fetching the rewards for yesterday so i can set an alert if it reach zero like it is now…

due to then the hotspot might be offline due to low power or something else that needs an operators attention.

i have tried curl, simple_html_dom and file_get_contents(‘https://app.hotspotty.net/hotspots/11euSptu1Ee3HgDCMfepYELwWMGMqkNdD9DQJqKbzPkasFebGne/rewards’);

For some reason i havent been able to fetch any data from that page…

So now i ask you experts for some help and guidance, what is the best way to monitor the activity yesterday for that webpage?

Tried curl, file_get_contents and simple_html_dom

Upload Image with php and database

I try to upload image in my database. I write these code, but it’s not update my database. it move the image in folder. but there is no data in database. anybody can help me with this problem?

<?php
// Include the database configuration file

$msg = "";

// If upload button is clicked ...
if (isset($_POST['upload'])) {

    $filename = $_FILES["uploadfile"]["name"];
    $tempname = $_FILES["uploadfile"]["tmp_name"];
    $folder = "./image/" . $filename;

    $db = mysqli_connect("localhost", "root", "", "madrasadb");

    // Get all the submitted data from the form
    $sql = "INSERT INTO `smash` (`stuimage`) VALUES ('$filename')";

    // Execute query
    mysqli_query($db, $sql);

    // Now let's move the uploaded image into the folder: image
    if (move_uploaded_file($tempname, $folder)) {
        echo "<img src=" . $folder . " height=200 width=300 />";
    } else {
        echo "<h3> Failed to upload image!</h3>";
    }
}
?>

<!DOCTYPE html>
<html>

<head>
    <title>Image Upload</title>
</head>

<body>
    <div id="content">
        <form method="POST" action="" enctype="multipart/form-data">
            Select Image File to Upload:
            <input type="file" name="file">
            <input type="submit" name="submit" value="Upload">
        </form>
    </div>

</body>

</html>

What’s the wrong with this code?

Circular reference when already using groups annotations?

I’m building an API with the MongoDBbundle. I have a document “Ingredient” that looks like that :

    #[MongoDBId]
    #[Groups(["getIngredients"])]
    private string $id;

    #[MongoDBField(type: 'string')]
    #[Groups(["getUnits","getUserSources","getIngredients"])]
    private string $name;

    #[MongoDBField(type: 'string')]
    private string $slug;

    #[MongoDBReferenceOne(targetDocument: IngredientCategorie::class)]
    #[MaxDepth(1)]
    private IngredientCategorie $categorie;

    #[MongoDBReferenceOne(targetDocument: User::class)]
    #[MaxDepth(1)]
    private User $owner;

    #[MongoDBField(type: 'string')]
    private string $privacy;

    #[MongoDBField(type: 'collection')]
    private $instructions;

I’m trying to build a route to get the list of every ingredients so I did this :

#[Route('/ingredients', name:'getAllIngredients', methods:['GET'])]
    public function getAllIngredients(DocumentManager $dm, SerializerInterface $serializer, Request $request, TagAwareCacheInterface $cachePool): JsonResponse
    {
        $idCache = "getAllIngredients";
        $jsonList = $cachePool->get($idCache,function(ItemInterface $item) use ($page,$limit,$serializer,$dm){
            $item->tag("ingredientsCache");
            $ingredients = $dm->getRepository(Ingredient::class)->findAll();
            return $serializer->serialize($ingredients, 'json',["group"=>"getIngredients"]);
        });
        
        return new JsonResponse($jsonList, Response::HTTP_OK,[],true);
    }

I’m already using groups annotations to avoir circular reference, here I’m only suppose to serialize $id and $name from the “Ingredient.php” class. But I still get a circular reference :

“A circular reference has been detected when serializing the object of class “MongoDBODMProxiesPMAppDocumentUserGenerateda24e9e269e70a012aa0eb80f98d12805″ (configured limit: 1).”

My “User.php” class as two fields with EmbedMany relation, $sources and $actives. Both Sources class and Actives class have one field like this :

#[MongoDBReferenceOne(targetDocument: Ingredient::class)]
private Ingredient $ingredient;

But I’m not serializing it, how to get rid of that circular reference ?

I tried to use #[MaxDepth(1)] annotation but without success. Already restarted the server and cleared the cache.

Laravel auth:api middleware is not working on newly create route file

I’ve a web app with Laravel 7. On that application I recently created a new api.php file under a folder named api/v2 (routes/api/v2/api.php). The problem I’m facing is that on the newly created api.php file ‘auth:api’ middleware is not working.

I’ve checked the request headers and found out that authorization header is coming as empty for those routes. Everything works fine for older route file.

I’ve registered new api file inside RouteServiceProvider.php like this

Route::prefix('api/v2')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api/v2/api.php'));

all routes are working fine without any issues except the auth problem. due to that I cannot call ‘$request->user()’ method inside my controller.

PS: I’m using apache 2.4+

Anyone know why this is happening?