Homebrew installation of PHP 8.0 fails

I’m having trouble installing php via Homebrew.

I tried following the guide on https://www.geeksforgeeks.org/how-to-install-php-on-macos/.

It worked the first time, then i uninstalled it and tried reinstalling it again and now I get an dyld[41846]: Library not loaded: error (see picture).enter image description here

Does anyone know how to solve it?

To uninstall php i used the command brew uninstall [email protected].

Then i got the message:

The following may be [email protected] configuration files and have not been removed!
If desired, remove them manually with rm -rf:
/usr/local/etc/php

So i removed them with the command:

rm -rf /usr/local/etc/php

NOTE: the guide also says:

**For compilers to find php8.0 you may need to set:

export LDFLAGS=”-L/opt/homebrew/opt/[email protected]/lib”
export CPPFLAGS=”-I/opt/homebrew/opt/[email protected]/include”**

Which I did. I don’t know if these commands affect the reinstallation somehow.

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

Function sqlsrv_connect() to connect to localhost phpmyadmin error

I try to connect to my localhost database in phpMyAdmin, but I get error:

Fatal error: Uncaught Error: Call to undefined function sqlsrv_connect().

How can I connect by using this code?:

$sqlConnInfo = array("database"=>DBNAME, "UID"=>DBUSER, "password"=>DBPASS);
global $sqlConn;
$sqlConn = sqlsrv_connect( DBHOST, $sqlConnInfo);

SimpleXLSXGen: saved excel file is showing to be corrupted

I am trying to save an excel file in PHP using the SimpleXLSXGen library. This is my code:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    header('Content-Type: text/plain; charset=utf-8');

    require __DIR__.'/vendor/shuchkin/simplexlsxgen/src/SimpleXLSXGen.php';
    use ShuchkinSimpleXLSXGen as SimpleXLSXGen;

    $arr = array();

    /*some logic here to populate my array*/

    $xlsx = new SimpleXLSXGen;
    $xlsx::fromArray($arr)
        ->setDefaultFont('Courier New')
        ->setDefaultFontSize(12)
        ->saveAs("..files/file.xlsx");
?>

This code used to work before, but now when I execute it, I keep getting a corrupted excel file saved at the location. Everytime I open the file, it keeps showing:

Excel cannot open the file ‘file.xlsx’ because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file

I have also debugged the $arr that I am pushing into my excel file, and it has the correct values. So why is the saved excel file showing to be corrupted?

Laravel PHP Imap get message body

I am connection to a mailbox and getting header information for each message like this:

$mailbox = new PhpImapMailbox(
    env('MAIL_IMAP_PATH') . env('MAIL_FOLDER'), // IMAP server and mailbox folder
    env('MAIL_LOGIN'), // Username for the before configured mailbox
    env('MAIL_PASSWORD') // Password for the before configured username
);
$mailsIds = $mailbox->searchMailbox('ALL');
foreach($mailsIds as $mail_elem) {
    $mail = $mailbox->getMail($mail_elem);
}

getMail gives me all the header infos without the body. I have checked now every single method which exists on $mailbox-> and there is no way to get the body. What am I doing wrong here?


Second approach is to use the stream from imap_open() and imap_fetchbody(). This feels more like a workarround because I connect a second time to the mailbox, but is also does not work:

foreach($mailsIds as $mail_elem) {
    $imap_stream = imap_open(env('MAIL_IMAP_PATH') . env('MAIL_FOLDER'),
                        env('MAIL_LOGIN'), env('MAIL_PASSWORD'));
    $message = imap_fetchbody($imap_stream, $mail_elem, 1.1);
}

I am getting an error:

imap_fetchbody(): Bad message number

Someone has an idea what is going on?

translate nodejs codes to php language

The operations done in a code I took as an example are related to the force update. I am not very interested in the post part, but I could not figure out how to do the get part. I am just learning the php language. I would appreciate if anyone can help.I created the necessary tables on mysql.what i want is php code. can anyone have time and help

Nodejs version_controller


var express = require("express");
const { StatusCodes } = require("http-status-codes");
var router = express.Router();
const Version = require("./model/version_model");
require("http-status-codes");
const semver = require("semver");

let iosIndexPath = 0;
let androdIndexPath = 1;

const versionPath = "/version";

router.post(versionPath, async (req, res) => {
  const versionModel = new Version(req.body);

  const headerValue = req.headers.authorization;

  if (headerValue == null) {
    return res
      .status(StatusCodes.UNAUTHORIZED)
      .json({ message: "Header Key Not Found" });
  }

  if (
    versionModel.platform == iosIndexPath ||
    versionModel.platform == androdIndexPath
  ) {
    const model = await versionModel.save({});
    if (model != null) {
      return res.json(model);
    } else {
      return res.status(StatusCodes.NOT_FOUND).send({ err: model.message });
    }
  } else {
    return res
      .status(StatusCodes.NOT_FOUND)
      .json({ message: "Platform is not valid value" });
  }
});

router.get(versionPath, async (req, res) => {
  const version = req.query.version;
  const platform = req.query.platform;

  if (version == null || platform == null) {
    return res
      .status(StatusCodes.NOT_FOUND)
      .json({ message: "Platform is not valid value" });
  }
  if (semver.valid(platform)) {
    return res
      .status(StatusCodes.NOT_FOUND)
      .json({ message: "Semantic Value Doesn not valid" });
  }

  const databaseVersion = await Version.findOne({ platform: platform });

  const diff = semver.diff(databaseVersion.version, version);
  const isForce = semver.gt(databaseVersion.version, version);

  return res.json({
    isForceUpdate: isForce,
    type: diff,
    currentVersion: databaseVersion.version,
  });
});

router.delete(versionPath, async (_, res) => {
  await Version.remove();
  return res.json();
});

module.exports = {
  router,
};

Nodejs Model

const mongoose = require("mongoose"); // Erase if already required

// Declare the Schema of the Mongo model
var userSchema = new mongoose.Schema({
  version: {
    type: String,
    required: true,
  },
  platform: {
    type: Number,
    required: true,
  },
  createdDate: {
    type: Date,
    default: Date.now(),
  },
});

//Export the model
module.exports = mongoose.model("Version", userSchema);

I haven’t tried anything because I can’t control the get part

What’s the downside of a login session?

Using the following simplified login form:

// login_form.php
<?php session_start(); ?>
<?php if ($_SESSION['isLoggedIn'] === false) : ?>
   <form action="login.php" method="post">
      <input type="password" name="password" />
      <input type="submit" value="Login" />
   </form>
<?php else: ?>
   You're logged in!
<?php endif; ?>
// login.php
<?php
session_start();
$_SESSION['isLoggedIn'] = htmlspecialchars($_POST['password']) == "my secret";
header("Location: login_form.php");

I want to understand, if there is a downside using this “type” of login and I want to understand why the following is not working:

  • Navigate to login_form.php with a cleared session
  • Open devtools and create a session isLoggedIn=true manually
  • Refresh the page
  • Result is not logged in

Symfony 6 : how to import bundle translations?

I’m using Symfony 6 and don’t understand how I should enable translation for dependency messages.
For example: I just installed SymfonyCasts/verify-email-bundle which provides translations in its directory (src/Resources/translations)

To enable them, I have:

  • installed the translation bundle with: composer require symfony/translation
  • set the default_locale to fr in my config/packages/translation.yaml
  • cleared the cache with bin/console cache:clear
  • also tried to manually clear translation cache as stated in other related posts : rm -rf var/log/translations

Then, all messages that should be handled by the provided translations are still in English.

I have also tried to force translation by calling myself the $translator->trans() method on the string returned by the bundle. The profiler then says the translation is missing and fallbacks to en as configured.

I have tried to copy the bundle VerifyEmailBundle.fr.xlf file into my own /translations directory but got the same error. bin/console debug:translation fr shows me the needed translations but all are marked as unused.

I encounter the same issue with multiple bundles and don’t see anything in the offical documentation about this.

What am I missing?

Symfony 6.2 API & Postman: return status code 200 on HttpException with different status code

When i throw an Http exception in my crud API, to avoid that symfony returns the complete error stack trace, i handle the exception with this listener:

class ExceptionListener implements EventSubscriberInterface
{
    public function onKernelException(ExceptionEvent $event): void
    {
        // You get the exception object from the received event
        $exception = $event->getThrowable();
        $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        // Customize your response object to display the exception details
        $response = new JsonResponse(['error' => $message]);

        // HttpExceptionInterface is a special type of exception that
        // holds status code and header details
        if ($exception instanceof HttpExceptionInterface) {
            $response->setStatusCode($exception->getStatusCode());
            $response->headers->set( 'X-Status-Code', $exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());
        } else {
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        // sends the modified response object to the event
        $event->setResponse($response);
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::EXCEPTION => ['onKernelException', 256],
        ];
    }
}

So on Postman i can see

{
    "error": "My Error says: Invalid body format with code: 0"
}

instead of the error stacktrace in html, but the status code remains 200.

Response on postman

Can you help me?

With xdebug i’ve seen that $response->statusCode is correctly setted to 400.

My service.yaml

  AppEventListenerExceptionListener:
    tags:
      - { name: kernel.event_listener, event: kernel.exception,  method: onKernelException }

Loop through array in object value Twig

Very simple yet I’m not familiar with the syntax. This is my array:

{
    "products": [
        {
            "title": "product",
            "ID": "1",
            "price": "€ 85,00 ",
            "discount": "€ 59,50 ",                
            "discountperc": "30 %",
            "stars": "2",
            "prodnew" : "",
            "images": "http://127.0.0.1/image.png"
        },
        {
            "title": "product"
            "ID": "2",
            "price": "€ 180,00 ",
            "discount": "",
            "discountperc": "",
            "stars": "",
            "prodnew" : "",
            "images": "http://127.0.0.1/image.png"
        },

I’m trying to achieve the following

{% for item in dummy.products %}
{{item.title}}
{
  "@type": "Product",
  "name": "{{item.title}}",
  "price": "item.price",
  "image": "item.images"
},
{% endfor %}

It’doesnt render anything and it doesn’t give me errors it’s wrong the approach with the array

Laravel 8.x realationship – Use HasMany in HasOne

I’m trying to use a HasMany relation in a HasOne.

I have following Models:

class Auction extends Model
{
    //...
    public function bids(): HasMany
    {
        return $this->hasMany(Bid::class, 'auction_id');
    }

    public function approvedBids(): HasMany
    {
        return $this->bids()->approved();
    }

    public function topBids(): HasMany
    {
        return $this->approvedBids()->orderByDesc('offered_token_price')->take(10);
    }

    public function topBid(): HasOne
    {
        //return $this->topBids()->firstOfMany(); // Not Working
        //return $this->hasOne(Bid:class, 'auction_id)->ofMany('price','max')->approved(); // not working
        //return $this->hasOne(Bid:class, 'auction_id)->approved()->ofMany('price','max'); // not working
        //return $this->hasOne(Bid::class, 'auction_id')->ofMany('price', 'max'); // working but not as I expecting
    }

}

class Bid extends Model
{
    //...
    public function scopeApproved(Builder $query): Builder
    {
        return $query->where('state', BidState::STATE_APPROVED);
    }
    //...
}

As you can see in the source, I’m looking for a way to make a relation that retrieve the Top Bid (ONE BID) from topBids() relation, but I don’t know how, and none of my approaches works:

$this->topBids()->firstOfMany(); // Not Working
$this->hasOne(Bid:class, 'auction_id')->ofMany('price','max')->approved(); // not working
$this->hasOne(Bid:class, 'auction_id')->approved()->ofMany('price','max'); // not working

non-ascii characters + curly brackets don’t match regex [duplicate]

I’m trying to match strings like this one: {Изберете_цвят}

What I did is this regex, which according to regex101 should work: https://regex101.com/r/s3u7Op/1. But what’s weird is that on actual php 8.1.14 it doesn’t work:

var_dump(preg_match('/{([p{L}-_]+)}/', '{Изберете_цвят}', $matches)); // 0

If I remove the brackets it works:

var_dump(preg_match('/([p{L}-_]+)/', '{Изберете_цвят}', $matches)); // 1

enter image description here

If I put ascii characters instead of Cyrillic it also works:

var_dump(preg_match('/{([p{L}-_]+)}/', '{test}', $matches)); // 1

Tried also to escape the brackets, nothing changed.

What’s wrong here? It looks like the closing brackets got included in the catching group, buy why that doesn’t happen if there are only ascii chars? Also } doesn’t sound like a p{L} matches any kind of letter from any language to me…

Simpler example:

php > var_dump(preg_match('/{([p{L}]+)}/', '{бa}'));
int(0)
php > var_dump(preg_match('/{([p{L}]+)}/', '{aa}'));
int(1)

strtotime miscalculates date when adding days that cross year

I need to add days to a date. I have been happily using the following and it’s worked up until the end of the year:

date('o-m-d', strtotime("{$start_date} +6 days"));

As an example, when $start_date equals 2022-12-19, the result is 2022-12-25:

date('o-m-d', strtotime("2022-12-19 +6 days")); // 2022-12-25

This falls to pieces when the number of days lands on the first day of the year – so for 2022-12-26 the result is 2022-01-01 (2022, rather than 2023!)

date('o-m-d', strtotime("2022-12-26 +6 days")); // 2022-01-01, which is incorrect!

Playing around I found it’s only if the date lands on the first day of the year – here are some examples:

date('o-m-d', strtotime("2022-12-30 +1 days")); // 2022-12-31, correct
date('o-m-d', strtotime("2022-12-30 +2 days")); // 2022-01-01, incorrect!
date('o-m-d', strtotime("2022-12-30 +3 days")); // 2023-01-02, correct

date('o-m-d', strtotime("2023-01-03 -1 days")); // 2023-01-02, correct
date('o-m-d', strtotime("2023-01-03 -2 days")); // 2022-01-01, incorrect!
date('o-m-d', strtotime("2023-01-03 -3 days")); // 2022-12-31, correct

I’ve seen when I include the h:m:s, I get a weird time of day, but that would surely impact all the date calculations. Anyone have an idea what’s going on here? (I’m using [email protected])

I’ve tried all sorts of variations, like adding the base date as the second parameter to strtotime, even trying relative to today (-11 days at time of writing) and always the same error..

To be clear, adding two days to 2022-12-30 should result in 2023-01-01, not 2022-01-01.

I’ve looked through other answers to similar questions, such as using

$date = new DateTime('2022-12-26');
$end_date = date_add($date, date_interval_create_from_date_string("6 days"))->format('o-m-d');

which results in exactly the same error.

why does my $stmt -> execute return as false? [closed]

// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($firstname_err) && empty($lastname_err) && empty($email_err)){
    
    // Prepare an insert statement
 //   $sql = "INSERT INTO users (firstname, lastname, username, email, password) VALUES (?, ?, ?, ?, ?)";
     
   // if($stmt = $mysqli->prepare($sql))
    if($stmt = $mysqli->prepare("INSERT INTO users (firstname, lastname, username, email, password) VALUES (?, ?, ?, ?, ?)")){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("sssss", $param_firstname, $param_lastname, $param_username, $param_email, $param_password);
        
        // Set parameters
        $param_firstname = $firstname;
        $param_lastname = $lastname;
        $param_username = $username;
        $param_email = $email;
        $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
        
        // Attempt to execute the prepared statement
        if($stmt->execute()){
            // Redirect to login page
            header("location: login.php");
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }

        // Close statement
        $stmt->close();
    }
}

I wanted to put the input data into my database but its not working I’m not sure why. Please help me.

Codeigniter v4:Custom View Does Not Return

I’m using Codeigniter v4 and wanted to show a custom view to users, so I made a Controller named Test:

<?php

namespace AppControllers;

class Test extends BaseController
{
    public function index()
    {
        $this->load>model('Usermodel');
        $data['users'] = $this->Usermodel->getusers();
        return view('custom');
    }
}

And a Model named Usermodel:

<?php

namespace AppModels;

class Usermodel extends CI_Model
{
    public function getusers()
    {
        return [
            ['firstmame'=>'Mohd','lastname'=>'Saif'],
            ['firstname'=>'Syed','lastname'=>'Mujahid'],
            ['firstname'=>'Mohd','lastname'=>'Armaan']
        ];
    }
}

And the view custom.php already exists in the Views folder.

But when I load the url http://localhost/ci4/public/index.php/test I get 404 Not Found error message.

Also I tried http://localhost/ci4/public/index.php/test/index but shows the same message.

So how to load this method from the custom controller class in Codeigniter v4 properly?