Allowed memory size exhausted with Manually Generate Pagination in Laravel

I am in processes to generate an array of numbers from available starting and ending numbers but I am facing Allowed memory size exhausted error while generating 1 million records. I do not want to store any information in the memory. So, Please review and guide that what is the issue or how I can iterate the code below to achieve this.

    $start = "0";
    //$end    = "5000";
    $end    = "16777216";
    for ($i = $start; $i <= $end; $i++) {
        $range[] = "Number $i";
    }
    //$total=count($range);
    $perPage = 25;
    $currentPage = request()->input("page") ?? 1;
    $startingPoint = ($currentPage * $perPage) - $perPage;
    $paginatedItems = array_slice($range, $startingPoint, $perPage, true);
    $paginated = new Paginator(
        $paginatedItems,
        count($range),
        $perPage,
        $currentPage,
        ['path' => request()->url(), 'query' => request()->query()]
    );
    return $paginated;

This code works well and generate the required results and then put these results in Laravel 9 Manual Pagination but when I try to generate a million or more records, it through the PHP default expection which I want to avoid based on the offset. Thank You

Laravel, how to filter records from a custom model method before paginating it?

I have a table called products and variants. They have one to many relationship, product can have multiple variants. The table ‘products’ doesn’t have a price column, that column is within the variants table. The product’s price is represented by the lowest price of its variants in the dashboard.

In the dashboard, I need to make a function that sorts the product’s price from lowest to highest and paginates it. Due to the nature of Eloquent builder and my intentional database design, it’s not that simple. Because I have to use model methods in order to access the lowest price of the variants like this:

protected function price(): Attribute
{
    return new Attribute(get: function(){
        return $this->variants()->get()->min('price');
    }); 
}

I’ve tried a couple of things like using sortBy but that’s only for collection so I can’t paginate it, even if I can, that would be a huge memory loss if the query is big enough because of the nature of collection.

Summary

How can I sort the data by a custom model method (price) in my builder before paginating it?

How to pass a transaction amount to Square payment processing page?

Square has a (new to me) payment system for taking payments. I’m having some trouble with the changes.

The old system was fairly simple – there was an html form, when the form was submitted the default behavior was prevented and data was sent to Square’s servers to generate a token. It was possible to include in the data a transaction amount. When their servers returned a token, it already included transaction approval/disapproval data. Based on that, I could move forward by processing the transaction.

This new system is similar except there’s no way to pass the amount of the transaction to Square’s servers. The token, when generated, is just a reference to the user’s payment method (e.g. a credit card or Google Pay). Every single example provided in their documentation uses a hard-coded amount for the transaction, which in their examples is part of the final state of the process.

I have everything working, except it’s still using hard-coded transaction amounts. I have tried…

A. Storing the transaction amount in local storage… but the final stages of processing are server-side so of course that failed…

B. Storing the transaction amount in a session variable… but when I try to call that variable on the server during processing it’s always empty…

C. Storing the transaction amount in a database table… but then I can’t pass the primary key value for that row…

D. Setting the transaction amount via JavaScript in window.amount because that’s how the sample code passes the idempotencyKey value… but that fails…

E. Setting a hidden form field in the form in the hopes that it will be passed to the server as POST data… and there is POST data sent, but not the hidden form field…

I haven’t tried manipulating the target URL to add GET data because I’m afraid that, even if I try to obfuscate it, it would be too easy a target for tampering.

The code example that I’m using is at https://github.com/square/connect-api-examples/tree/master/connect-examples/v2/php_payment and the example file for final card processing with the hard-coded transaction amount looks like this:

$money = new Money();
// Monetary amounts are specified in the smallest unit of the applicable currency.
// This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
$money->setAmount(100);

Note that the comments in that code are part of the original, not mine.

This same trend of using a hard-coded value is repeated in the documentation at https://developer.squareup.com/reference/square/payments-api/create-payment for the ‘amount_money’ value.

I really feel like the solution should be set into this block of example code from the form input side of the example but I can’t figure out how to do it.

  <script type="text/javascript">
    window.applicationId =
      "<?php
        echo getenv('SQUARE_APPLICATION_ID');
        ?>";
    window.locationId =
      "<?php
        echo getenv('SQUARE_LOCATION_ID');
        ?>";
    window.currency =
      "<?php
        echo $location_info->getCurrency();
        ?>";
    window.country =
      "<?php
        echo $location_info->getCountry();
        ?>";
    window.idempotencyKey =
      "<?php
        echo Uuid::uuid4();
        ?>";
  </script>

As I mentioned above in list item D., I’ve tried setting a value for window.amount because of the documenation (c.f. https://developer.squareup.com/reference/sdks/web/payments/objects/Money) but that doesn’t work.

Anyone have any ideas? This seems like such a basic thing, I can’t help but think I’m missing the forest for the trees.

Thanks.

(Edited for clarity)

unable to recover ftp files

I have been trying for several days to retrieve the list of folders on my ftp servers, despite the various posts consulted I still cannot resolve an error.

I get this error: Warning: ftp_nlist() expects parameter 1 to be resource, bool given in D:WebwwwDesignindex.php on line 10

My code:

<?php
$serveur = '***';
$login = '***';
$pass = '***';

$ftp = ftp_connect($serveur, 21) or die('error connect');
$ftp_login = ftp_login($ftp,$login, $pass) or die('error login');

ftp_nlist($ftp_login, '.');
?>

Has anyone already encountered this problem?

The connection to the server is done well, $ftp & $ftp_login returns true

Thanks!

How to correct error 500 on IIS web server?

Im having trouble with a randomly appearing error 500 on a web app hosted on an IIS web server, the error shows up only on a specific page and rebooting the server seems to be the only thing fixing it.

The page is used to send mails so it can send large POST requests and take some time to execute.
The error is never showing up while executing requests, it shows up when I stop using the page and come back after some time.

On a local instance of apache2 and Php there is no problem.

Also I dont know where to look in order to find logs or more details about the error.

Thanks for your help.

What i’ve tried :

-Increase php memory limit.
-Increase php execution time limit.
-Increase POST and UPLOAD limit.

Laravel Route [login] not defined

api.php file:-

<?php

use AppHttpControllersUserController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/


Route::post('login', [UserController::class,'login']);

Route::prefix('user')->middleware('auth:sanctum')->controller(UserController::class)->group(function () {

   Route::get('/user', function (Request $request) {
    return $request->user();
});

   Route::post('/create','create'); 



});

Result of php artisan route:list :-

POST       api/login .................................................. generated::ZbCPv6PYuv5EbuXE › UserController@login
  POST       api/user/create ........................................... generated::FVy5Q2BuwMm8p22P › UserController@create
  GET|HEAD   api/user/user .................................................... generated::6FyVEOXSKZ88144C › UserController
  GET|HEAD   sanctum/csrf-cookie ......................... sanctum.csrf-cookie › LaravelSanctum › CsrfCookieController@show

Kernel.php file:-

protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            // LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
             LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
    IlluminateRoutingMiddlewareThrottleRequests::class.':api',
    IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
    ];

The solution i tried :-

php artisan route:cache

How to use an Iframe Login to hide certain pages from users that are not logged in

Working on a project in wordpress, some pages run on iframes that come from a different login they provided me an iframe script to use.

<script src='https://batouwe.e-golf4u.nl/leden/iframe/js/resizehandler.js'></script>
<iframe id='egolf4u_iframe' frameborder='0' src='https://batouwe.e-golf4u.nl/leden/iframe/wedstrijd' style='width: 100%;'></iframe>
<script>
  jQuery('#egolf4u_iframe').on("load", function() {
        jQuery('#egolf4u_iframe').height(function (index, height) {
            return (height + 40);
        });
  });
</script>

we have some pages that they generate the data too and also the login form so the users can see the data (the users have an existing account with the iframe provider, they appear to have an auth key on the client side sinds users can switch to different iframes and not have to login again.

My question is i want to be able to lock not logined users from certain pages on the client side aswel. how do i do this. is it possible to edit the iframe script to change a certain block to hidden when they are not logged in and to visable when they are logged in.

the site is https://debatouwe.yeps.site/

if you want to see what i mean,

Any help appreaciated this is a project for school and it needs to be done asap this is all that im missing!

for users not to be able to access certain client side pages while logged into the iframe api login

Query not inputting data into the database using Unity Engine, C#, SQL, and PHP

I was bored and messing around doing random tutorials like I do. Stumbled onto a Unity and MySQL tutorial that basically went into making a basic database for storing login data for users. I thought it was interesting and went along with it and seemed to have no issues until it came together in the most base form. Only issue is no entry is made in the database.

C# Code

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
//using static UnityEngine.Rendering.DebugUI;

public class Registration : MonoBehaviour
{

    public MainMenu mainMenu;

    public TMP_InputField nameField;
    public TMP_InputField passwordField;
    public TMP_InputField confPasswordField;
    public TextMeshProUGUI errorField;

    public Button registerButton;

    public void CallRegister()
    {
        StartCoroutine(Register());
        Debug.Log(nameField.text);
        Debug.Log(passwordField.text);
    }

    IEnumerator Register()
    {
        WWWForm form = new WWWForm();
        form.AddField("Username", nameField.text);
        form.AddField("Password", passwordField.text);
        using (UnityWebRequest www = UnityWebRequest.Post("http://localhost/sqlconnect/register.php", form))
        {
            yield return www.SendWebRequest();
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.downloadHandler.text);
                mainMenu.GoToMenu();
            }
            else
            {
                Debug.Log("User Creation Failed. Error #" + www.result);
                errorField.text = ("User Creation Failed. Error #" + www.result);
            }

            www.Dispose();
        }

    }

    public void VerifyInputs()
    {
        registerButton.interactable = (nameField.text.Length >= 8 && passwordField.text.Length >= 8 && confPasswordField.text == passwordField.text);
    }

}

PHP Code

<?php

    $con = mysqli_connect('localhost', 'root', 'root', 'mantleonline');

    //Check connection occured
    if(mysqli_connect_errno())
    {
        echo "1: Connection Failed"; //Error Code #1 = Connection Failed
        exit();
    }

    $username = mysqli_real_escape_string($con, $_POST['Username']);
    $password = mysqli_real_escape_string($con, $_POST['Password']);

    //Check if username unique
    $namecheckquery = "SELECT username FROM players WHERE username='" . $username . "';";

    $namecheck = mysqli_query($con, $namecheckquery) or die("2: Name Check Query Failed") //Error Code #2 = Username Query Check Fail

    if(mysqli_num_rows($namecheck) > 0)
    {
        die("3: Name Already Taken"); //Error Code #3 = Username not unique. Cannot register.
    }

    if(mysqli_num_rows($namecheck) < 0)
    {
        echo "69: Bullshit"; //Error Code #3 = Username not unique. Cannot register.
    }

    //Add user to table
    $salt = "$5$rounds=5000$" . "eternull" . $username . "$";
    $hash = crypt($password, $salt);

    $insertuserquery = "INSERT INTO players (username, hash, salt) VALUES ('". $username . "', '". $hash ."', '" . $salt . "');";
    $mysqli_query($con, $insertuserquery) or die("4: Insert Player Data Query Failed"); //Error Code #4: Insert Player Data Query Failed

    echo("0");

?>

I’ve tried stitching in what I could learn from a few other places such as swapping from Unity’s WWW to UnityWebRequest. Honestly I suspect that the error springs somewhere within there as I am not receiving any error messages on running, but I wouldn’t be surprised if I’m just saving these values and then dumping them or not passing them along somewhere and thus running blank queries every time.

How to get the value of a select input in Phalcon?

I have a small form with a select input and a textarea for commenting. I want to make the textarea required only if the value of the select input is 1, for example, otherwise, it shouldn’t be required. How can I accomplish this, is there a way to get the value of the select input once the user has clicked on one of the options ? Here’s my CommentForm.php :

       $this->add(new Select(
            'active',
            [
                1 => 'Something',
                0 => 'Something else'
            ],
        ));


        
        $comment = new TextArea('comment', [
            'placeholder' => 'comment ...'
        ]);
        $comment->addValidators([
            new PresenceOf([
                'message' => 'Comment is required'
            ])
        ]);
        $this->add($comment);

This is how I render it in the volt file :

{{ form() }}
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Select</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-comment-alt"></i></span>
                                </div>
                                {{ formComment.render("active", ["class": "form-control"]) }}
                                
                            </div>
                        </div>
      
                        <div class="form-group">
                            <label>Comment</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-comment-alt"></i></span>
                                </div>
                                {{ formComment.render("comment", ["class": "form-control"]) }}
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <input type="hidden" name="typeID" value="13">
                        {{ submit_button("addComment", 'name':'addComment', "class": "btn btn-success", 'value':'submit') }}
                        {{ formComment.render('csrf', ['value': security.getToken()]) }}
                    </div>
{{ end_form() }}

Thanks in advance!

Detach php process in that way can cause performance problem in server? [duplicate]

During execution of a php webservice, i need to detach a “time consuming function” to maintain a quick response to the user. That’s an example of the flow :

enter image description here

I know that php does not manage multi-thread operation by itself, but anyway there are some other methods to works in async way.
Googling and here on stackoverflow i have found a possible solution in the shell_exec command.

i have create this example to simulate the flow:

service.php

$urlfile=dirname(__FILE__)."/timefile.php";
$cmd = 'nohup nice -n 10 php -f '.$urlfile.' > log/file.log & printf "%u" $!';
$pid = shell_exec($cmd);

echo $pid;

timefile.php

 sleep(10);
 $urlfile=dirname(__FILE__)."/logfile.txt";
 $myfile = fopen($urlfile, "a");
 $txt = time()."n";
 fwrite($myfile, $txt);
 fclose($myfile);

The code is only an example ( it writes into a txt file ) and it works asynchronous.

The flow will be upload on a Centos server with php and mysql installed. In real life timefile.php will execute from 3 to 6 curl call, i can estimate an execution time (for the entire file) of 30 seconds. Timefile.php will not act as a daemon, it will executed without only one time when it is called, so it will not remain open with a infinite while loop for instance.

Obviously the performance will depends on the server details, but my question is a little bit different. The webservice ( i hope ) will be call many times ( i can estimate 1000 times each hour ) and maybe there will be also concurrency troubles.

So my question is :

Using this approach ( with shell_exec as the example shows ) i will have performance trouble in server caused by the high number of detached process opened ?

TYPO3 ActionController without authentication

I am implementing a TYPO3 plugin with actions in an ActionController class.
However, the ActionController base class seems to enforce authentication.
In my use case, I, however, do not want authentication, since that particular controller renders a page that should be publicly accessible.
How can I deactivate authentication in such a controller?

<?php

namespace HomeinfoSysMon2Controller;

use TYPO3CMSCoreUtilityGeneralUtility;
use TYPO3CMSExtbaseMvcControllerActionController;
use TYPO3CMSExtbaseObjectObjectManager;
use TYPO3CMSExtbaseUtilityDebuggerUtility;
use TYPO3CMSCoreDatabaseConnectionPool;

use Generator;

use HomeinfohwdbDomainModelDeployment;
use HomeinfohwdbDomainRepositoryDeploymentRepository;
use HomeinfohwdbDomainRepositorySystemRepository;

use HomeinfoSysMon2DomainRepositoryCheckResultsRepository;
use HomeinfoSysMon2SystemWithCheckResults;

class UnauthenticatedAccess extends ActionController
{
    public function systemDetailsAction()
    {
        //$customerId = $this->request->getArgument('customer');
        $customerId = 1030020;
        $deploymentRepository = GeneralUtility::makeInstance(ObjectManager::class)
            ->get(DeploymentRepository::class);
        $deployments = iterator_to_array($deploymentRepository->findByCustomerId($customerId));
        $systemRepository = GeneralUtility::makeInstance(ObjectManager::class)
            ->get(SystemRepository::class);
        $deploymentIds = [];
        
        foreach ($deployments as &$deployment)
            $deploymentIds[] = $deployment->id;

        $systems = iterator_to_array($systemRepository->findByDeploymentIds($deploymentIds));
        $checkResultsRepository = GeneralUtility::makeInstance(ObjectManager::class)
            ->get(CheckResultsRepository::class);
        $systemIds = [];
            
        foreach ($systems as $system)
            $systemIds[] = $system->id;

        $checkResults = iterator_to_array($checkResultsRepository->findLastMonthBySystems($systemIds));
        $systemsWithCheckResults = iterator_to_array(
            SystemWithCheckResults::fromSystemsDeploymentsAndCheckResults($systems, $deployments, $checkResults)
        );
        $this->view->assign('systemsWithCheckResults', $systemsWithCheckResults);
    }
}

Multiple Line Graph by using SQL query (Yearly Comparison Graph)

I am trying to generate a multiple line graph with Highcharts, where each line represents data from a different year, and the x-axis displays the date while the y-axis displays the price.

I have a MySQL database table from which I’m fetching data, and I’m grouping that data by year using PHP. The $chart_data array holds the data grouped by year, and the name key holds the year value while the data key holds an array of timestamp and price pairs.

I’ve included the PHP code I’m using to generate the chart, and it successfully generates the graph, but the data is not displaying correctly. The graph shows all the years on the same line instead of each year on its own line.

I’m expecting the graph to look like the one in this reference image Demo Graph Screenshot, with each year displayed on its own line.

I’m new to Highcharts and not sure how to adjust the code to display the graph correctly. Can anyone help me with this issue? Thank you in advance!

Here is the code I’m using to generate the chart:

// SQL Query…

<?php
$chart_record = $wpdb->get_results($SQL_ALL_TBL_FOR_CHART);

$chart_title = '';
if ($chart_record){
    $row = $chart_record[0];
    $chart_title = $row->var_name . ' | ' . $row->type_name;
    $chart_data = array();

    $grouped_data = array();
    foreach ($chart_record as $row) {
        $year = $row->year;
        if (!isset($grouped_data[$year])) {
            $grouped_data[$year] = array();
        }

        $date = new DateTime($row->rptl_date);
        $timestamp = $date->getTimestamp() * 1000;

        $grouped_data[$year][] = array(
            'x' => $timestamp,
            'y' => (int) $row->rptl_price
        );
    }

    foreach ($grouped_data as $year => $year_data) {
        $chart_data[] = array(
            'name' => $year,
            'data' => $year_data
        );
    }
}
?>

<script src="https://code.highcharts.com/highcharts.js"></script>

<div class="container">
    <div id="chart-container"></div>
</div>

<script>
Highcharts.chart('chart-container', {
    chart: {
        type: 'line'
    },
    title: {
        text: '<?php echo $chart_title; ?>'
    },
    xAxis: {
        type: 'datetime',
        title: {
            text: 'Date'
        }
    },
    yAxis: {
        title: {
            text: 'Price'
        }
    },
    series: [
        <?php foreach ($chart_data as $year_data): ?> {
            name: '<?php echo $year_data["name"]; ?>',
            data: [
                <?php foreach ($year_data["data"] as $data): ?>[<?php echo $data["x"]*1000; ?>,
                    <?php echo $data["y"]; ?>],
                <?php endforeach; ?>
            ]
        },
        <?php endforeach; ?>
    ]
});
</script>

The output of this code is:

Chart Screenshot which I made by SQL query

I was expecting this code to generate the graph as I have provided the reference image Demo Graph Screenshot
But the issue is clear to you. Please help me with this problem. Thank you!

How can I give www-data permissions to run a .sh script with sudo from an index.php?

I have a script in /var/www/Web-EvilBlock/ejecuta_py.sh

What that script does is run a .py file ( sudo python3 /var/www/Web-Evilblock/EvilBlock.py )
(From what I saw, there are problems trying to run a .py from php, so I made a .sh file that will run that .py)

My problem is that from my web page in php, I have a button that executes that bash script, but it doesn’t work.(Need sudo permissions)

The only way I’ve gotten it to work is in visudo by adding the line:
www-data ALL=(ALL) NOPASSWD: ALL
But I would like to make it a little more secure. Is there any other way? I am new to linux.

www-data is the owner of /var/www/Web-EvilBlock and have execution permission

automatically select the first in stock variation on woocommerce variable products

I need a code for woocommerce variable products that:

  • Automatically selects the first variation that appears;
  • But if the first variation is out of stock, automatically selects the variation that appears next, and so on;
  • If all variations are out of stock, automatically selects the first variation.

I tried this snippet:

add_filter( 'woocommerce_dropdown_variation_attribute_options_args', 'filter_woocommerce_dropdown_variation_attribute_options_args', 10, 1 );
function filter_woocommerce_dropdown_variation_attribute_options_args( $args ) {
if ( count( $args['options'] ) > 0 ) {
$option_key = '';
$product = $args['product'];
if ( is_a( $product, 'WC_Product_Variable' ) ) {
foreach ( $product->get_available_variations() as $key => $variation ) {
$is_in_stock = $variation['is_in_stock'];
if ( $is_in_stock ) {
$option_key = $key;
break;
}
}
}
if ( is_numeric( $option_key ) ) {
$args['selected'] = $args['options'][$option_key];
}
}
return $args;
}

but doesn’t work in some products, like:

Anyone can help me? Thank you