Data chosen from select input isn’t known after uploading on the server but works on normal local host

So, before uploading on the server through cPanel, this code works fine. But on the server, I cannot.

On Server
On localhost

Both the codes are the same. It just doesn’t work on the website server. Please help me.

Here is the code snippet:

PHP CODE (below)

<?php
if(isset($_POST['form1'])) {
    $valid = 1;

    if(empty($_POST['tcat_id'])) {
        $valid = 0;
        $error_message .= "You must have to select a Main Menu<br>";
    }

    if(empty($_POST['mcat_name'])) {
        $valid = 0;
        $error_message .= "Sub Menu can not be empty<br>";
    }

    if($valid == 1) {

        // Saving data into the main table tbl_mid_category
        $statement = $pdo->prepare("INSERT INTO tbl_mid_category (mcat_name,tcat_id) VALUES (?,?)");
        $statement->execute(array($_POST['mcat_name'],$_POST['tcat_id']));
    
        $success_message = 'Sub Menu is added successfully.';
    }
}
?>

HTML FORM BELOW:

<form class="form-horizontal" action="" method="post">

                <div class="box box-info">
                    <div class="box-body">
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label">Main Menu Name <span>*</span></label>
                            <div class="col-sm-4">
                                <select name="tcat_id" class="form-control select2">
                                    <option value="">Select Main Menu</option>
                                    <?php
                                    $statement = $pdo->prepare("SELECT * FROM tbl_top_category ORDER BY tcat_name ASC");
                                    $statement->execute();
                                    $result = $statement->fetchAll(PDO::FETCH_ASSOC);   
                                    foreach ($result as $row) {
                                        ?>
                                        <option value="<?php echo $row['tcat_id']; ?>"><?php echo $row['tcat_name']; ?></option>
                                        <?php
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label">Sub Menu Name <span>*</span></label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" name="mcat_name">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label"></label>
                            <div class="col-sm-6">
                                <button type="submit" class="btn btn-success pull-left" name="form1">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>

            </form>

Why are multiple AJAX requests waiting (hanging) for 1s+ between them?

Whenever I send more than 1 paralel ajax request at a time to my backend, some respond within a reasonable timeframe (<100ms), however some of the requests hang for approximately 1s before returning a response, regardless of which order they are executed in.

I have decided to test this out by creating a very simple HTML+jQuery/PHP (frontend+backend) script which creates 6 paralel ajax requests and running it both on my local server, as well as Digitalocean’s server using the same setup (Debian 10 Apache + PHP 7.4).

The results on local server:

enter image description here

The results on Digitalocean server:

enter image description here

The javascript:

 function ajaxAtOnce() {
        $.get("ajax1.php", function (data) {
            console.log(data);
        });
        $.get("ajax2.php", function (data) {
            console.log(data);
        });
        $.get("ajax3.php", function (data) {
            console.log(data);
        });
        $.get("ajax4.php", function (data) {
            console.log(data);
        });
        $.get("ajax5.php", function (data) {
            console.log(data);
        });
        $.get("ajax6.php", function (data) {
            console.log(data);
        });
    }

PHP endpoints (all equal):

<?php

    // return 100 randomly ordered numbers
    $array = range(1,100);
    shuffle($array);
    echo json_encode($array);

Important notes

  • If I hardcode a large enough “timeout” inbetween ajax requests, I get a response within expected timeframe:
function ajaxWithTimeout() {
        setTimeout(function() {
            $.get("ajax1.php", function (data) {
                console.log(data);
            });
        }, 1000);

        setTimeout(function() {
            $.get("ajax2.php", function (data) {
                console.log(data);
            });
        }, 2200);

        setTimeout(function() {
            $.get("ajax3.php", function (data) {
                console.log(data);
            });
        }, 3500);

        setTimeout(function() {
            $.get("ajax4.php", function (data) {
                console.log(data);
            });
        }, 4700);

        setTimeout(function() {
            $.get("ajax5.php", function (data) {
                console.log(data);
            });
        }, 5900);

        setTimeout(function() {
            $.get("ajax6.php", function (data) {
                console.log(data);
            });
        }, 7100);
    }
  • If I send all the requests to the same endpoint (ajax1.php for example), there is no problem

  • After some research I found 2 server parameters that seem to be mentioned with regards to this issue, but they are set to their default values, and removing the limit does not have an effect:

    RateLimitInterval=30s, RateLimitBurst=1000

As you can imagine, this issue can be very frustrating, especially when developing a SPA in a JS framework like React, which is where I first noticed the issue.

PHP Numeric string comparison wrong resuslts [duplicate]

Hello I have to compare strings with numbers, and I have some issues, I did some dumps to try:

            var_dump((string)$prod->Code);
            echo "<br>";
            var_dump($code);
            var_dump((string)$prod->Code == $code);
            echo "<br>";
            echo "<br>";

I got the following results:

string(4) "0539"
string(5) "00539" bool(true)

Basically “0539” is equal to “00539”

What can I do?

I tried also strcmp, I would expect “0539” to test equal to “0539” but not equal to “00539” AND “00539” to test equal to “00539” but not equal to “0539”

WordPress Customize Page Dose Not Load Completely

I Developed a website with WordPress.
For several hours now, the customize page of the WordPress template doesn’t load completely and only the site title appears and the tabs are not displayed.
I tested it with another computer, it was ok and it loaded completely, but it doesn’t load with my system; I also completely deleted my browser (google chrome latest version) cache.

What do you think is the problem?

Injecting Guzzle client in Symfony project

In the services.yaml file, I added guzzle client as a service:

guzzle:
    class: GuzzleHttpClient

In the service class, I try to inject Guzzle:

/**
 *  @var GuzzleHttpClient $httpClient;
 */
protected $httpClient;

public function __construct(GuzzleHttpClient $httpClient)
{
    $this->httpClient = $httpClient;
}

I get the following error:

Cannot autowire service "AppServiceMyService": argument "$httpClient" of method "__construct()" references class "GuzzleHttpClient" but no such service exists. You should maybe alias this class to the existing "guzzle" service.

What am I missing here?

How to get facebook posts and show in laravel website card [closed]

I’m currently making my own practice project in which I’m willing to show all my facebook page posts/feeds on a website based on laravel 9. Is it possible ? How can I achieve that with laravel 9? How do I connect my facebook account page and show all the posts of my facebook page on a bootstrap card. Can you please share some urls and the steps to achieve this? Would be thankful!

I tried with to see facebook.developer page but got no idea from that. How to Embed the code . how can I achieve it ?

zsh: command not found: php. PHP is installed and working with MAMP

I am trying to use composer to install a google client library, but cannot install composer or use php on the command line.

I am using php 8.0.8 with MAMP and it is working fine, so I know it is installed.
If I type php in the terminal, I receive the command not found message. Thinking it could be an environment variable, I have tried navigating to the php folder /Applications/MAMP/bin/php/php8.0.8/lib/php and tried the php command again, but still get the same error

I am using a Mac running Monterey

return object models in array with PHPStan

Lets say you have 3 models like this

class User extends AbstractModel {
     protected string $name = 'User';
} 

class Car extends AbstractModel {
     protected int $weels = 4;
} 

class House extends AbstractModel {
     protected string $address = 'Some Street 26a';
} 

then you have a fuctions that returns the 3 models like this

protected function generateModels(): array
{
     $user  = new User();
     $car   = new Car();
     $house = new House();

     return [$user, $car, $house]
}

then you have some tests like this

/**
 * @test
 */
public fuction this_is_some_random_test(): void
{
     [
         $user,
         $car,
         $house,
     ] = $this->generateModels();

     $user->name;
     $address->weels;
     $house->address;

     $result1 = some_function_require_user_model($user);

     //some assertions
}

So how do you need to typehint the functions generateModels() that PHPstan understands that It can be multiple models? cause array<int, mixed> doesnt works array<int, AbstractModel> also not cause it will complain like property $name doesnt exist on AbstractModel and the third is like array<int, User|Car|House> what also doenst seem the works cause you will get the same errors and then the functions says that the Car|House types are now allowed. So how can I type hint it propperly?

PHPStan level 9

convert “DateInterval” to string for posetive times work employees

I want get total times of each person at company
for example
08:45
8:40
8:55
total n time
and I get this Error
Date Interval:: create From Date String (): Argument #1 ($datetime) must be of type string, Date Interval given
how can I solve it? Thanks 🙁

`
@if(is set($reports))

                              {{-- @if(is set($request->user id)) --}}
                               @php
                                   $time = 0;
                                    @endphp

                                       @foreach ($reports as $key => $report)

                                       <t r>
                                            <td scope="row">{{ $key + 1  }}</td>
                                               <td>{{ $report->user_ id->user_ name ?? 'خالی' }}</td>

                                                 <td>{{ $report->entry _ time ?? 'خالی' }}</td>
                                         <td>{{ $report->exit _ time ?? 'خالی' }}</td>
                                         <td>{{ $report->project->name ?? 'خالی' }}</td>
                                         <td>
                                         @php

                                            $enter = new Date Time($report->entry _time );
                                            $exit = new Date Time($report->exit_ time );
                                               $interval = $enter->diff($exit);


                                         Date Interval::create From Date String($interval);
                                        $time+=$i;
                                    @endphp

                                    {{ $interval->format("%H") . ':' . $interval->format("%i=") }}

                                    </td>
                                    <td></td>
                                    <td></td>
                                    <td>{{ $report->main _report ?? 'خالی' }}</td>
                                </t r>

                                    @endforeach
                                    {{ $time }}
                            {{-- @endif --}}
                            @endif
                            </t body>`

not redirecting to other file

After clicking the login button It still stay on login.php or redirecting to same file.
I’m new to php language so I couldn’t figure out what’s wrong.

I want to redirect to navbar.php after clicking the login button
can you help me with this? thankyou

here’s the code i have

login.php

<?php
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
  header("location: navbar.php");
  exit;
}

// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";

// Processing form data when form is submitted
  if (isset($_POST['user_login_btn'])) {
    if(isset($_POST['login_btn'])) {
      if($_SERVER["REQUEST_METHOD"] == "POST"){
        // Process the user login form
        $username = mysqli_real_escape_string($con, $_POST['username']);
        $password = mysqli_real_escape_string($con, $_POST['password']);

        $password = md5($password); // Hash the password before storing it in the database
        $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
        $results = mysqli_query($con, $query);

        if (mysqli_num_rows($results) == 1) {
        // If the login is successful, start a new session and redirect to the user dashboard
        session_start();
        $_SESSION['username'] = $username;
        $_SESSION['success'] = "You are now logged in";
        header('location: navbar.php');
        } else {
        // If the login is unsuccessful, display an error message
        array_push($errors, "Wrong username/password combination");
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
</head>
<body>
  <div class="header">
    <h1>Login</h1>
  </div>
  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
    <table>
      <tr>
        <td>Username:</td>
        <td><input type="text" name="username" required></td>
      </tr>
      <tr>
        <td>Password:</td>
        <td><input type="password" name="password" required></td>
      </tr>
      <tr>
        <td></td>
        <td><input type="submit" name="login_btn" value="Login"></td>
      </tr>
    </table>
  </form>
</body>
</html>

Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, string given in

The above error appears in PHP 8.0, pointing to the line of code below:

if ( isset( $attachment_metadata['sizes'] ) && count( $attachment_metadata['sizes'] ) && ( isset( $attachment_metadata['sizes'][ $intermediate_size ] ) ) ) {

Section of code for this function:

function wpsc_product_image( $attachment_id = 0, $width = null, $height = null ) {

// Do some dancing around the image size
if ( ( ( $width >= 10 ) && ( $height >= 10 ) ) && ( ( $width <= 1024 ) && ( $height <= 1024 ) ) ) {
    $intermediate_size = "wpsc-{$width}x{$height}";
}

// Get image url if we have enough info
if ( $attachment_id > 0 && ! empty( $intermediate_size ) ) {

    // Get all the required information about the attachment
    $uploads    = wp_upload_dir();
    $image_meta = get_post_meta( $attachment_id, '' );
    $file_path  = get_attached_file( $attachment_id );

    // Clean up the meta array
    foreach ( $image_meta as $meta_name => $meta_value ) {
        $image_meta[ $meta_name ] = maybe_unserialize( array_pop( $meta_value ) );
    }

    $attachment_metadata = isset( $image_meta['_wp_attachment_metadata'] ) ? $image_meta['_wp_attachment_metadata'] : null;

    // Determine if we already have an image of this size
    if ( isset( $attachment_metadata['sizes'] ) && count( $attachment_metadata['sizes'] ) && ( isset( $attachment_metadata['sizes'][ $intermediate_size ] ) ) ) {
        $intermediate_image_data = image_get_intermediate_size( $attachment_id, $intermediate_size );
        $image_url               = $intermediate_image_data['url'];
    } else {
        $image_url = home_url( "index.php?wpsc_action=scale_image&attachment_id={$attachment_id}&width=$width&height=$height" );
    }
// Not enough info so attempt to fallback
} else {

    if ( ! empty( $attachment_id ) ) {
        $image_url = home_url( "index.php?wpsc_action=scale_image&attachment_id={$attachment_id}&width=$width&height=$height" );
    } else {
        $image_url = false;
    }

}

if ( empty( $image_url ) && ! empty( $file_path ) ) {

    $image_meta = get_post_meta( $attachment_id, '_wp_attached_file' );

    if ( ! empty( $image_meta ) ) {
        $image_url = $uploads['baseurl'] . '/' . $image_meta[0];
    }
}

As still relatively new to php, and still learning, would appreciate any feedback or suggestions on how to overcome this error.

How do I remove ‘.php’ extension from URL without stopping the php from executing?

I have removed the ‘.php’ file extension the URL in the .htaccess file, however, it seems to prevent my php code from running.

Could someone please suggest a way that I can get this to work?

RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]
RewriteCond %{THE_REQUEST} \s/+(.+?)\.html[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]
RewriteCond %{THE_REQUEST} \s/+(.+?)index[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]

strange .htaccess rule malfunction

I have the following data structure in PHP (shortened for brevity) in the array $job:

(
    [jobid] => 33541166
    [country] => South Africa
    [subcounty] => Somerset West
    [position] => Administrator (R7 500 p.m.)
)

I have the following .htacccess rule:

RewriteRule job/(.*)/(.*)/(.*)$ /info.php?jobid=$1&position=$2&city=$3

This rule intermittently works, but the reason why eludes me. Take the examples below:

https://site.co.za/job/33541166/administrator_r_7_500_pm/somerset_west
https://site.co.za/job/33541166/administrator_r_7_500_px/somerset_west

The job structure in the PHP array is the same for both. The URL is purely cosmetic, really, as the only criteria I use to retrieve the job from the database is the job ID (e.g., 33541168).

As you can see, the first URL has “pm” and the second one has “px”, otherwise they are the same. The first link DOES NOT display the job, redirects to homepage, and the second one DOES display the job correctly, yet, the “px” is not in the position string above.

Then there is a completely different job:

https://site.co.za/job/33541168/receptionist_for_general_practitioner/durban_north

And it works 100% with no anomalies.

The code used to construct the URL to be clicked on the page is this ($jobid is used in $position and $city whenever these fields are not present (historical data issues):

if (!empty($v['position'])) {
    $position = preg_replace("/p{P}/", '', trim($v['position']));
    $position = strtolower(str_replace(' ', '_', $position));
} else {
    $position = $jobid;
}
if (!empty($v['subcounty'])) {
    $city = preg_replace("/p{P}/", '', trim($v['subcounty']));
    $city = strtolower(str_replace(' ', '_', $city));
} else {
    if (!empty($v['country'])) {
        $city = preg_replace("/p{P}/", '', trim($v['country']));
        $city = strtolower(str_replace(' ', '_', $city));
    } else {
        $city = $jobid;
    }
}

And the link is structured as follows:

<a style="color: #ffffff !important;"
   href="<?php echo $fullurl; ?>/job/<?php echo $job['jobid']; ?>/<?php echo $position; ?>/<?php echo $city; ?>">
  <?php echo $job['position']; ?>
</a>

Notes, in case needed:

`$job` is the PHP array containing the entire job particulars, as shown in shortened fashion above,
`$position` and `$city` are the modified strings for use in the URL.

I have initially thought maybe a duplicate ID (even though the DB has autoincrement on the jobid column) or a duplicate description, but that does not appear to be the case. I also considered that the . and the ( and ) in the administrator job position might be causing havoc, but I believe it shouldn’t because of the regex I used in my PHP code. To confirm that, I removed these characters in a test, and still does not work consistently.

Every job I have checked shows the URL to click on in the browser in the correct format, so I do not think the PHP code above is fundamentally flawed, except maybe not optimal.

I do not have access to Apache server logs at this time.

Any ideas will be much appreciated.

How to loop through multi dimensional array response from Ajax in Jquery?

I am trying to get the quantity of raw materials along with the raw material id. I send recipe id and in response I am getting array like this

[54,"Vanilla Cake Mix",2000] [126,"Water",1200] [1,"Refined Soyabean Oil",200]

Where 54 is Raw Material ID,
Vanilla Cake Mix is Raw Material Name,
And 2000 is Quantity

How do I access each value of this?

My Jquery code is

      `$.ajax({
        type:"POST",
        url:"api_consumption.php",
        data: "product_recipe_id="+product_recipe_id+"&quantity="+value,
        dataType: "json",
        success: function(html)
        {
          //I want to access the values received in json array format.
        }
      });`

My PHP code is

$array = array($raw_material_id, $raw_material_name, $raw_material_quantity); echo json_encode($array);

I tried the each loop but failed.

php socket not disconnect client with android

i used stream_socket_server() i not receive msg in server with status disconnect form android closing connection

if close google chrome is normal receive disconnect msg

if disable wi-fi and 5g lost disconnect msg

if(strlen($socket) == 8 || strlen($socket) == 0):

is possible resolve problem?

how check status of client for disconnect…
check list of lcients in new handshake one solution?

one solution for check status client ofr disconnect he