PHP is popularly used for web application development. Top frameworks in PHP are Symfony and Laravel. But, as most of you already know, Laravel is a full-stack framework, and it has a lot of features and functionalities, which might be not needed by a small website. Symfony is a much more lightweight framework and is more commonly used. Main advantage of using PHP is that it is open source, so you do not have to pay for using it. It is easy to install and use. It is multipurpose, so it can be used for all type of website development.

Popular New Releases in PHP

laravel

v9.1.5

SecLists

2022.1

framework

symfony

v6.0.7

composer

2.3.4

Popular Libraries in PHP

laravel

by laravel doticonphpdoticon

star image 69346 doticon

Laravel is a web application framework with expressive, elegant syntax. We’ve already laid the foundation for your next big idea — freeing you to create without sweating the small things.

SecLists

by danielmiessler doticonphpdoticon

star image 36667 doticonMIT

SecLists is the security tester's companion. It's a collection of multiple types of lists used during security assessments, collected in one place. List types include usernames, passwords, URLs, sensitive data patterns, fuzzing payloads, web shells, and many more.

jQuery-File-Upload

by blueimp doticonphpdoticon

star image 31080 doticonMIT

File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.

framework

by laravel doticonphpdoticon

star image 26780 doticonMIT

The Laravel Framework.

symfony

by symfony doticonphpdoticon

star image 26732 doticonMIT

The Symfony PHP framework

composer

by composer doticonphpdoticon

star image 26405 doticonMIT

Dependency Manager for PHP

Faker

by fzaninotto doticonphpdoticon

star image 26055 doticonNOASSERTION

Faker is a PHP library that generates fake data for you

guzzle

by guzzle doticonphpdoticon

star image 21585 doticonMIT

Guzzle, an extensible PHP HTTP client

DesignPatternsPHP

by DesignPatternsPHP doticonphpdoticon

star image 19861 doticonMIT

sample code for several design patterns in PHP 8

Trending New libraries in PHP

pest

by pestphp doticonphpdoticon

star image 4192 doticonMIT

Pest is an amazing and elegant PHP Testing Framework with a focus on simplicity

expose

by beyondcode doticonphpdoticon

star image 3702 doticonMIT

A beautiful, fully open-source, tunneling service - written in pure PHP

wave

by thedevdojo doticonphpdoticon

star image 3574 doticonMIT

Wave - The Software as a Service Starter Kit, designed to help you build the SAAS of your dreams 🚀 💰

Postman-cn

by hlmd doticonphpdoticon

star image 3332 doticon

Postman汉化中文版

jetstream

by laravel doticonphpdoticon

star image 3281 doticonMIT

Tailwind scaffolding for the Laravel framework.

filament

by laravel-filament doticonphpdoticon

star image 3198 doticonMIT

A collection of tools for rapidly building beautiful TALL stack interfaces, designed for humans.

octane

by laravel doticonphpdoticon

star image 3094 doticonMIT

Supercharge your Laravel application's performance.

baiduwp-php

by yuantuo666 doticonphpdoticon

star image 2703 doticonMIT

PanDownload网页复刻版

sanctum

by laravel doticonphpdoticon

star image 2266 doticonMIT

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.

Top Authors in PHP

1

wp-plugins

12233 Libraries

star icon2299

2

WPPlugins

7838 Libraries

star icon301

3

iuthub

2093 Libraries

star icon50

4

runacode

1269 Libraries

star icon0

5

vikashlogbull

1168 Libraries

star icon1

6

1098 Libraries

star icon413

7

TYPO3-svn-archive

921 Libraries

star icon72

8

wikimedia

910 Libraries

star icon5866

9

spryker

905 Libraries

star icon228

10

franacode

905 Libraries

star icon0

1

12233 Libraries

star icon2299

2

7838 Libraries

star icon301

3

2093 Libraries

star icon50

4

1269 Libraries

star icon0

5

1168 Libraries

star icon1

6

1098 Libraries

star icon413

7

921 Libraries

star icon72

8

910 Libraries

star icon5866

9

905 Libraries

star icon228

10

905 Libraries

star icon0

Trending Kits in PHP

PHP is a popular open-source programming language that is widely used for developing web applications. It helps developers to create dynamic content for websites and mobile apps. PHP Testing is one of the most important parts of PHP development. It allows you to test your code, check the performance of your product, and find bugs. The best PHP testing tools allow developers to run tests in a simple way, from unit tests to functional testing. To make your life easier, we’ve prepared a list of 7 best PHP Testing Open Source libraries in 2022 in our kit, laravel-generator - CRUD Laravel Generator; php-quickcheck - generative testing for PHP; phpunit-skeleton-generator - generate skeleton test classes from production code classes.

You can use these tools to determine the location of website visitors based on their IP address or other location data.


These libraries provide a range of functionalities such as geocoding, reverse geocoding, distance calculations, and mapping. They allow developers to determine website visitors' country, city, region, and latitude/longitude based on their IP address. Google Maps Geolocation API is one of the most widely used PHP geolocation libraries. It provides a simple and reliable way to determine the location of website visitors using data from Google Maps. It allows developers to get the latitude and longitude of a location and its estimated accuracy. These libraries enable developers to provide a more personalized user experience by showing relevant content based on the location of website visitors. They also help you to create custom maps and visualizations based on geospatial data and enable location-based advertising and marketing strategies.


PHP Geolocation Libraries are essential tools for web developers who want to create location-based web applications. We have handpicked the top and trending open-source PHP routing libraries for your next application development project:

GeoIP2 PHP:

  • Used in Web Services, REST applications, etc.
  • Provides an easy-to-use API for working with MaxMind's GeoIP2 and GeoLite2 databases.
  • Allows developers to determine the location of website visitors based on their IP address.

Google Maps Geolocation API:

  • Used to determine the location of website visitors using data from Google Maps.
  • Allows developers to get the latitude and longitude of a location.
  • Also provides the estimated accuracy of the location.

Leaflet:

  • Used to handle dynamic map configurations working in a PHP context.
  • It is lightweight and easy to use for building mobile-friendly interactive maps.
  • Supports a wide range of map providers.

GeoPHP:

  • Used in Geo, Map applications, etc.
  • It’s a native PHP library for geometry operations and provides basic geospatial functionality.
  • Features include point-in-polygon testing, distance calculations, and geometry simplification.

Geocoder:

  • Used in Utilities, Command Line Interface, Laravel applications, etc.
  • Provides geocoding and reverse geocoding services.
  • Supports data from various providers such as Google Maps, OpenStreetMap, and Bing Maps.

IP2Location:

  • Used in Networking, TCP applications, etc.
  • Provides fast lookup and geolocation services based on IP address data.
  • Includes a database of IP address ranges and location data for various countries and regions.

SmartyStreets:

  • Used in Web Services, REST applications, etc.
  • Provides address validation and geocoding services.
  • Uses data from various providers such as Google Maps, OpenStreetMap, and Bing Maps.

Geotools:

  • Used in Manufacturing, Utilities, Aerospace, Defense, Geo, Map applications, etc.
  • Supports accept almost kinds of WGS84 geographic coordinates.
  • Built on top Geocoder and React libraries.

Location:

  • Used in Networking, TCP applications, etc.
  • Helps retrieve a user's location from their IP address using various services.
  • Works with PHP >= 7.3 and Laravel >= 5.0.

Judge Yvonne Gonzalez Rogers ordered that iOS apps must be allowed to support non Apple payment options in the Epic v. Apple case. In this case, Apple also scored a partial victory as the judge stopped short of calling it a monopoly. The judge also ordered Epic Games to pay Apple 30% of its revenue through the direct payment system. Epic is fighting a similar lawsuit against Google. Countries like South Korea have passed laws requiring Apple and Google to offer alternative payment systems to their users in the country. While the jury is still out on the Epic v. Apple case, it brings out two aspects. Is what is often referred to by developers as the "Apple Tax" of 30% indeed justified? For this reason, Epic launched the Epic Games Store to demonstrate that they could operate at a lower revenue cut of 12%. The second aspect is platform and payments interoperability. When platform interoperability becomes mandated or a global best practice, developers should be ready to bring in payment gateways of their choice. The kandi kit for App Store Payment Alternatives showcases the popular open source payment gateways such as Omnipay, Active Merchant, and CI Merchant and libraries available to connect with leading payment platforms such as Stripe, Braintree, and Razorpay.

Omnipay

Core libraries and samples from Omnipay, a framework agnostic, multi-gateway payment processing library for PHP.

Active Merchant

Libraries on Active Merchant, a simple payment abstraction library extracted from Shopify.

CI Merchant

Though no longer actively supported use the library to build and support your own gateway. If you are not looking to build but to use, then leverage other frameworks.

Braintree

Libraries for Braintree integration.

Razorpay

Libraries for Razorpay integration.

Stripe

Libraries for Stripe integration.

Build automated sanitization robots that can be employed in hospitals and other public and private premises using open-source libraries and frameworks.


Today, sanitization is much needed in every place including hospitals, offices, homes, public places, and whatnot. The Covid-19 pandemic has made sanitization a buzzword even though it existed for ages. In this modern era, robots are playing a vital role in reducing human efforts and helping to get the job done by saving time and money.


We can use these robots to sanitize the hospitals, that would eventually help in saving precious human life. The main purpose of these robots is to minimize person-to-person contact and to ensure cleaning, support in hospitals, and quarantine. This will help in reducing threats to medical staff and doctors taking an active role in pandemic for managing health care systems. You can use open-source libraries and components while building such robots.


Listed below are the best libraries that can be reused by developers in their projects for building hospital sanitizing robots:

Data scraping is used to gather valuable insights, conduct market research, monitor competitor prices, or build price comparison websites. 


In this digital world, the internet has changed the way we do our shopping. Online shopping is the act of purchasing products or services over the internet. It gathers all the information that will make all your internal and external recommendation processes, sales, and distribution based on the chronology of what you have been buying and bought earlier. Some of the libraries below can help you to achieve this as DIY.

Data Collection

Ecommerce Websites

Ecommerce Services

Blood is a vital liquid for the human body. Blood can be extracted and donated to various individuals based on clinical screening to identify the potential match. Around the world, blood banks operate. A system is required to manage multiple blood bank operations effectively. The details needed are blood type, storage area, storage date, patient name, and contacts. These details can help in maintaining and monitoring the blood banks. You can create your own customized blood bank management system.

PHP form validation libraries provide popular PHP-based form components that can be used for building beautiful and efficient forms. You can also enable form validation, debugging, and lots more with this. An HTML form works with various input fields such as text boxes, checkboxes, radio buttons, checklists, submit buttons, and so on. These forms are used to input data from users and submit it to the web server for processing. They can be built using HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, etc. PHP validates entries at the server end, like the empty string, validate numbers, input length, validate URL, and so on. Validation rules also include checking whether all required fields have been filled and if the information is valid. Form validation has many uses to gather user information in any form of a website. Below are our 45 best PHP form validation libraries that are open source in 2021. jQuery-File-Upload is a file upload widget that enables multiple file selection, drag and drop, progress bar, validation and preview images, audio and video for jQuery, etc. It supports cross-domain, chunked, and resumable file uploads, and works with any server, like PHP, Ruby on Rails, Java, Node.js, Python, etc. Config, on the other hand, helps you find, load, autofill, combine, and validate configuration values from any source, be it YAML, XML, INI files, or a database. Another library, Form, is a component that allows you to create, process, and reuse HTML forms with ease.

The Trump Media and Technology Group is being investigated by Software Freedom Conservancy for non-compliance with copyleft licensing. The issue stems from President Donald Trump’s new social network, Truth Social appearing to be forked from Mastodon. While Mastodon is open source and available to use, it is licensed under Affero General Public License (or AGPLv3) that requires The Trump Media and Technology Group to share its source code with all who used the site. If they fail to do this within 30 days, their rights and permissions in the software are automatically and permanently terminated, making their platform inoperable. So if you are just a developer or a former POTUS, copyleft provisions apply to all. If you want to use open source, use kandi.openweaver.com. All libraries are matched to SPDX license definitions and highlighted clearly for appropriate use. Privacy, regulation, bias, and many other issues are weighing down popular social networks. Users are seeking self-hosted social platforms that can be governed by themselves. But do use them with the appropriate licenses. The kandi kit on Opensource Social Platforms lists popular opensource libraries that you can use to host private social channels.

A payment processing library can help make your eCommerce application-independent and well-equipped to handle multiple payment gateways. A PHP payment processing software enables multiple features like payment methods, secure authentication, integration with third-party software, etc. With this, you can add popular platforms like PayPal, Apple Pay, Google Pay, Stripe, UnionPay, and more to your web application. PHP allows developers to build fast and scalable applications that provide risk-free solutions to payment woes. With the help of these libraries, you can enable several online payment options like integration with the shopping cart, faster processing, multiple payment platforms, charge back prevention, fraud management, recurring billing, etc.

Below are our 20 best PHP payment processing open source libraries in 2021. Omnipay is a framework agnostic, multi-gateway payment processing library built for PHP 5.6+. Its consistent API is fully unit tested and comes with an example application for beginners. Here, you can learn an API and use it in multiple projects without rewriting the code. Another library, InvoicePlane is a self-hosted open-source application that manages invoices, clients, and payments. Payum Bundle, on the other hand, is an MIT-licensed open-source project that offers all payment-related solutions. It supports both simple use cases as well as very advanced ones.

You will need to use an external library or service to translate text from Greek to English because SpaCy lacks built-in machine translation capability. The Google Translate API is one tool that can be used to achieve this.  


Using Google Translate API, developers can include machine translation features in their applications. The API supports many languages and can translate text across them.  


The use of SpaCy to translate text from Greek to English has several potential uses.  

  • Machine Translation: In natural language processing and machine learning, translating text from one language to another is a common task.  
  • Language Modeling: The training and testing of language models can also be done using text translation.  
  • Sentiment Analysis: Text translation enables sentiment analysis by examining text written in many languages.  
  • Document Summarization: By maintaining only the most crucial material in the original language, text translation can assist in creating a summary of a lengthy document.  
  • Chatbot: Text translation might be helpful in customer service and chatbot applications.  


Here is how you can translate text using SpaCy:  

Preview of the output that you will get on running this code from your IDE

Code

In this solution we have used Translator function of python

  1. Copy the code using the "Copy" button above, and paste it in a Python file in your IDE.
  2. Enter the Text that need to transalate
  3. Run the code get the Output


I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for "Translate text using Spacy" in kandi. You can try any such use case!


Note


In this snippet we are using a Language model (en_core_web_sm)

  1. Download the model using the command python -m spacy download en_core_web_sm .
  2. paste it in your terminal and download it.


Check the user's spacy version using pip show spacy command in users terminal.

  1. if its version 3.0, you will need to load it using nlp = spacy.load("en_core_web_sm")
  2. if its version is less than 3.0 you will need to load it using nlp = spacy.load("en")

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.


  1. The solution is created in Python 3.7.15 Version
  2. The solution is tested on Spacy 3.4.3 Version
  3. The solution is tested on translate 3.6.1 Version


Using this solution, we can Translate the greek words to english with the help of function in spacy . This process also facilities an easy to use, hassle free method to create a hands-on working version of code which would help us Translate the words in python.

Dependent Library

If you do not have SpaCy and translation that is required to run this code, you can install it by clicking on the above link and copying the pip Install command from the Spacy page in kandi.

You can search for any dependent library on kandi like SpaCy and translation

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page

Here are the best PHP Static analysis libraries, which can be utilized to debug software programs that involve examining the code without running the application.  


The automatic source code analysis done without running the application is known as static analysis. Dynamic analysis refers to analysis carried out while a program is being executed. Static analysis frequently finds security flaws, performance problems, standard-compliance violations, and outdated programming structures. All static analysis tools share the fundamental idea of examining source code for coding patterns marked with a warning or other information. By customizing the static analysis tool to measure portions of the code and only report on a subset of rules, some programmers use static analysis as an objective indicator of the quality of their code.  


The top-of-the-board libraries are mentioned below to cause static analysis of PHP source code to be straightforward for developers. 

phpstan- 

  • Without running your code, PHPStan concentrates on locating problems in it.  
  • Finds entire classes of errors even before you write code tests.  
  • Brings PHP closer to compiled languages in that the validity of each line of code can be tested before running it. 

phan- 

  • Prefers to minimize false positives. 
  • Attempts to prove incorrectness rather than correctness. 
  • Can verify type compatibility on various operations. 
  • The most straightforward way to use Phan is via Composer.

psalm- 

  • Takes care of taint analysis, type inference, and security analysis.  
  • Tends to find errors in PHP applications. 
  • It helps to maintain a wide variety of codebases. 

PhpMetrics- 

  • Provides metrics about PHP projects and classes. 
  • Generates beautiful and readable HTML reports. 
  • Understandable static analysis tool. 

noverify- 

  • Can analyze changes in git and show only new reports. 
  • Has PHP 7 and PHP 8 support. 
  • It is fast and can analyze 100k LOC/s. 

PhpDependencyAnalysis- 

  • Finds violation in a dependency graph. 
  • Extendable static code analysis for object-oriented PHP-Projects. 
  • Generate dependency graph from abstract classes.

Mondrian- 

  • Uses graph theory for static analysis. 
  • Helps to add abstraction into concrete classes. 
  • The generated HTML file does not require any dependencies or a connection. 

Exakat- 

  • Smart engine for static code analysis. 
  • Automated code review is possible. 
  • Is a great review tool and an analysis framework. 

Vulny-Code-Static-Analysis- 

  • It is a python script-based static analysis tool. 
  • Works based on regular expressions or regex. 
  • Can detect vulnerabilities in PHP source code.

progpilot- 

  • A tool specialized in static analysis in security. 
  • Is possible to use progpilot inside PHP code. 
  • The taint analysis configuration is customizable. 

These are the best libraries for web scraping using PHP. You can use these libraries for extracting large volumes of data from various sources, and those data can be used for many purposes and applications.  


Online scraping is a computerized technique for gathering enormous volumes of information from sites. Most of this data is unstructured in HTML format and is transformed into structured data in a database or spreadsheet for use in multiple applications. Web scraping can be done through various methods to collect data from websites. Using their APIs, you may access the structured data on many huge websites, including Google, Twitter, Facebook, Stack Overflow, and others. Other options include leveraging specific APIs, online services, or even writing your code from scratch for web scraping.   


To transform this web scraping process into an easier one, we have carefully handpicked a set of libraries in the language - PHP. 

panther- 

  • A practical standalone framework for web page scraping and running end-to-end tests with actual browsers. 
  • Enables taking a screenshot. 
  • Can wait for components that are loaded asynchronously to appear. 
  • Supports custom Selenium server installations. 
  • Supports remote browser testing services, including SauceLabs and BrowserStack. 

core- 

  • Inspired by Scrapy package for python. 
  • A comprehensive PHP web scraping toolbox. 
  • It includes a pipeline to clean, persist, and process extracted data. 

Goutte- 

  • A web crawling and screen scraping library for PHP. 
  • It has an impressive API to crawl websites. 
  • It can extract data from HTML/XML responses.

PHPScraper- 

  • All scraping functionalities can be accessed as a function or property call. 
  • Uses League/URI to process URLs. 
  • Uses donatello-za/rake-php-plus to extract and analyze keywords.

laravel- 

  • Laravel adapter for Roach. 
  • A package can be installed via composer. 
  • Registers a few Artisan commands for easier development. 

Grawler- 

  • Automates the task of using google dorks, scrapes the outputs, and stores them in a file. 
  • Supports both automatic and manual modes. 
  • API keys for proxies are first validated and added to the file. 

crawler- 

  • Can assist in building our own scrapers. 
  • Can load URLs and get absolute links from HTML documents. 
  • Can keep memory usage low by using PHP generators. 

ultimate-web-scraper- 

  • Makes RFC-compliant web requests that are indistinguishable from a real web browser. 
  • Has a web browser-like state engine for handling cookies and redirects. 
  • Tag filtering library TagFilter is included to extract the desired content from each retrieved document easily. 
  • Easy to emulate various web browser headers. 

Here are some of the famous PHP Micro Frameworks Libraries. The use cases of these libraries include:   

  • Rapid Prototyping  
  • RESTful APIs  
  • Single Page Applications  
  • Minimalistic Development  


PHP Micro Frameworks are libraries that provide minimalistic frameworks for developing web applications. These libraries provide a basic structure for organizing code, including routing, request handling, and other essential components. They are often used for small web applications or projects without a full-featured framework.  


Let us look at some of these famous libraries. 

slim

  • Supports multiple request and response formats, including JSON, XML, and HTML.
  • Provides a customizable logging system that can be used to log messages from your application.
  • Provides a built-in error handler that can be used to provide detailed information about errors that occur in your application.

lumen

  • Supports robust routing for various HTTP verbs, like GET, POST, PUT, PATCH, and more.  
  • Supports a variety of database backends, including MySQL, PostgreSQL, SQLite, and MongoDB.  
  • Provides various security features, including strong password hashing, CSRF protection, and form input sanitization. 

wave

  • Supports the PSR-7 specification for HTTP messages.  
  • Supports many popular template engines, such as Twig, Smarty, and Blade.  
  • Supports asynchronous programming, i.e., developers can write code that can run in parallel. 

Silex

  • Is highly extensible, with many available extensions.  
  • Supports both traditional and modern web development, making it suitable for beginners and experienced developers.  
  • Is open source, so it is free to use and can be easily modified to suit specific needs. 

fractal

  • Provides a built-in authentication system, allowing developers to manage user authorization and authentication easily.  
  • Allows developers to create custom transformers.  
  • Provides a caching system, allowing developers to cache data for a certain period. 

flight

  • Provides a simple routing system for mapping URLs to callback functions.
  • Provides a built-in support for sessions, flash messages, and authentication.
  • Provides tools for handling request data, including GET and POST parameters, files, and cookies.

kohana

  • Provides a simple and powerful ORM (Object Relational Mapping) system, allowing developers to quickly and easily create and manipulate data in their database.  
  • Allows developers to structure the application modularly, making it easier to maintain and extend.   
  • Its powerful and flexible routing system allows developers to create and configure routes for their applications easily.

Project

  • Allows developers to use an object-oriented approach, making it easier to develop complex applications.  
  • Provides a powerful template engine that helps developers create dynamic, user-friendly applications.   
  • Provides a built-in unit testing framework, making it easier to ensure applications function properly. 

limonade

  • Supports full RESTful API development.
  • Is designed to be easily extended with custom components.
  • Provides dependency injection for easy testing and mocking.

micromvc

  • Provides easy integration with third-party libraries. 
  • Provides a powerful URL routing system that allows developers to create and manage URLs for their applications easily.   
  • Is designed to be modular, allowing developers to add and remove features as needed easily. 

PHP Map Libraries are designed to help developers display and manipulate maps on web pages using PHP. All PHP libraries offer ways to display maps on web pages. They provide different map styles, like satellite, terrain, and street views. These libraries offer customization options like changing map styles, adding custom data overlays, and customizing markers.  


Most PHP map libraries will let developers place markers on the map, which will indicate points of interest or for identifying locations. We can customize those markers with different labels or icons. Geocoding will help convert addresses into latitude and longitude coordinates, and these libraries offer these features for developers to pinpoint locations on the map. These libraries offer functionality for helping users in planning trips and getting directions. They offer support when you want to add layers to the map. They offer APIs for developers to integrate the map functionality into their applications.  


Here is the list of the top 7 PHP Map Libraries handpicked to help developers integrate their maps with their applications.  

GeoIP2-php: 

  • Is a PHP library that offers an easy-to-use and simple interface for MaxMind’s GeoIP2 database. 
  • Offers accurate and detailed information about the geographic location of IP addresses. 
  • Allows PHP developers to easily integrate MaxMind’s GeoIP2 databases directly into their web applications.  

phpgeo: 

  • Is a PHP library that offers an easy-to-use interface to work with geographic coordinates like latitude and longitude.  
  • Includes classes for working with bounding boxes, polygons, points, and conversion between coordinate systems and distance calculation.  
  • Is designed to be lightweight and easy to use, making it an excellent choice for developers who need to work with geographic coordinates in their PHP applications.  

geotools: 

  • Is a PHP library that offers various tools for working with geographic data like geographic projections, geometrics, and coordinates. 
  • Includes classes for workings with polygons, points, lines, and other geometric shapes and methods for transforming between different coordinate projections and systems. 
  • Is a useful tool for PHP developers who want to work with geographic data in their applications.  

Valinor: 

  • Is a PHP library that offers various tools for working with geographic spatial databases and data.  
  • Includes support for spatial data types and functions and integration with popular spatial databases like PostGIS.  
  • Includes classes for working with lines, points, polygons, and other shapes and methods for calculating areas, the intersection between shapes, and distances.  

geoPHP: 

  • Is a PHP library that offers tools to work with geographic data like geographic geometrics, projections, and coordinates.  
  • Support for different coordinate projections and systems, including popular systems like UTM, Lambert Conformal Conic, and WGS84.  
  • Supports various coordinate projections and systems and their geometry transformation and class methods, making it a powerful tool for working with geographic data. 

GeocoderLaravel: 

  • Is a PHP library that offers geocode and reverse geocoding services to Laravel applications. 
  • Uses popular geocoding services like Bing Maps, OpenStreetMap, and Google Maps for converting place names or addresses into geographic coordinates and vice versa. 
  • Includes caching functionality that helps improve the performance of geocoding requests by caching the results of previous requests.  

google-maps: 

  • Is a PHP client library for the Google Maps API, making it easy to integrate into your application.  
  • Offers a straightforward way to access different services offered by Google Maps, like directions, distance matrix, and geocoding.  
  • Offers support for directions that allows developers to retrieve directions between two or more locations.  

Here are the top PHP Telegram Bot libraries you can use to implement message bot, command bot, inline bot, poll bot, payment bot, game bot, news bot, weather bot, reminder bot, and music bot.  


Telegram Bot is a software application that interacts with the Telegram Bot API to perform various tasks and functions. These bots can perform various tasks, from sending and receiving messages to processing commands and managing updates. They are easy to set up and can be customized to suit the user's specific needs.  


The top PHP Telegram bot libraries are shown below. Here is a detailed review of libraries. 

botman: 

  • Simple and easy-to-use PHP library for creating Telegram bots. 
  • Supports multiple messaging platforms and has a modular architecture. 
  • Has a fluent interface and built-in support for dialogs and message conversations. 

core: 

  • Is a pure PHP Telegram Bot that is fully extensible using plugins.  
  • Allows integrations of all sorts for bringing automated interactions to the mobile platform.   
  • Aims to provide a platform where one can write a simple bot and make interactions within minutes.   

freenom: 

  • Used to renew your domain name automatically.  
  • Choose any of the sending methods for configuring and directly jump to the corresponding document you want to view.  
  • Is not recommended to use Server sauce for sending letters as the number of daily message deliveries is limited.   

telegram-bot-sdk: 

  • Let's develop Telegram Bots using PHP quickly and supports Laravel.  
  • Is an HTTP-based interface that is created for developers who are keen on building bots for Telegram.  
  • Offers a flexible architecture that allows developers to include new features and adjust their bots as needed. 

Api: 

  • A low-level library for building bots with the Telegram Bot API. 
  • Supports all features of the Telegram Bot API and has a clean, easy-to-use interface. 
  • Is actively maintained and has a large user community. 

TelegramBotPHP: 

  • Is a simple PHP telegram bot API that helps in sending messages.  
  • Can get one simply using the Bot Father using simple commands once you have created your bot.  
  • To enable error logging files, we can copy TelegramErrorLogger.php to the same directory as Telegram.php. 

telegram-api: 

  • Is a PHP7 Telegram bot API implementation. 
  • Enables you to support any Telegram Bot APIs like stickers, inline bots, messages, location, and other supported techniques via PHP to a Telegram user. 
  • Implements and respects the default methods and types that are made by Telegram.  

PHP Language Detection Libraries are designed to detect languages and support different language options depending on the developer’s requirements. They use different methods and algorithms for identifying the language, like n-gram models, stopword detection, statistical analysis, and character frequency analysis. This library's primary feature is detecting a certain text's language. 


PHP Language Detection Libraries support different languages and detect languages like English, Japanese, French, Chinese, German, Spanish, and others. These libraries are fast and efficient with low memory consumption and create minimal impact on the application's performance. Many PHP Language Detection libraries include character encoding detection capabilities that can detect the character encoding of the text and help improve the language detection accuracy. This is easy to use, can be integrated into applications easily, and offers simple APIs for detecting text language.  


Here is the list of the top 8 PHP Language Detection Libraries handpicked to help developers identify different languages in their applications. 

google-translate-php: 

  • A simple PHP library for the Google Translate API offers a simple interface for translating text and supports different languages.  
  • Allows customization of the translation parameters, like the target and source languages and the format of the translated text.  
  • Offers a caching mechanism that can improve the translation service's performance by reducing the number of requests to the Google Translate API. 

language-detection: 

  • Is a popular PHP language detection library for language detection which offers a simple interface for detecting the text language. 
  • Uses a combination of methods and algorithms for identifying the language, like n-gram models, stopword detection, character frequency, and statistical analysis.  
  • Can be integrated with popular PHP libraries like Symfony and Laravel, making it easier to use language detection frameworks.  

yii2-localeurls: 

  • Is a Yii2 extension that offers localized URLs for multilingual web applications.  
  • Allows developers to create URLs that include the language code, making it easier for search engines to index and rank the pages accordingly. 
  • Offers a simple API for generating localized URLs and handling language switching. 

php-google-translate-for-free: 

  • Is a PHP library that offers a simple interface for using the Google Translate API for translating text between languages.  
  • Is designed to be easy to use and supports multiple languages.  
  • Supports automatic language detection that can automatically detect the source text's language and translate it to the target language. 

detectlanguage-php: 

  • Is a PHP library that offers a simple interface for language detection using the Detect Language API.  
  • Is designed to be easy to use and integrate into applications to offer simple APIs for detecting the text language.  
  • Supports automatic language detection, which can detect the source text's language and translate it to the target language automatically. 

laravel-nlp: 

  • Is a Laravel package that offers Natural Language Processing features to Laravel applications.  
  • Is built on top of the Standford CoreNLP library and offers a simple and easy-to-use interface to perform NLP tasks like named entity recognition, part-of-speech tagging, and sentiment analysis.  
  • Can perform sentiment analysis on the text that involves determining the emotion or sentiment conveyed by the text, like negative, positive, and neutral.  

GoogleTranslateBundle: 

  • Is a Symfony bundle that offers integration with the Google Cloud Translation API.  
  • Can translate text from one language to another and support various languages. 
  • Allows customization of the translation parameters, like the number of translations for performing and the confidence threshold for translation.  

Text_LanguageDetect: 

  • Is a PHP library that offers language detection features to PHP applications to detect given text with high accuracy. 
  • Allows customization of the language detection parameters like the confidence threshold for translation and the number of translations for performing.  
  • Supports Unicode text allowing it to detect the language of the text in various scripts and writing systems.  

Here is the top collection of PHP Security Libraries for developers. PHP Security Libraries will offer the developers a comprehensive security framework for writing applications. It also provides the administrator or user with various tools for securely managing those applications. 


PHP Security Libraries include large tools, APIs, and implementations commonly used for security protocols, algorithms, and mechanisms. The PHP Security APIs span various areas like public key infrastructure, authentication, cryptography, access control, and secure communication. 


We have handpicked the top 10 PHP Security Libraries for developers in 2024 for your reference: 

SecLists: 

  • Known as the security tester's companion.  
  • Is a collection of several types of lists used during security assessments collected in a single place.  
  • This might include passwords, usernames, sensitive data patterns, website URLs, web shells, fuzzing payloads, etc. 

awesome-appsec: 

  • Is a curated set of resources which helps to learn about application security. 
  • Contains websites, self-assessment quizzes, books, and blog posts. 
  • Helps in understanding the importance of end-to-end network-layer encryption and secure encryption for idle data. 

phpseclib: 

  • Takes in strings and not file paths.  
  • Does not need a public key; private keys have the public key embedded within them, which will be extracted when required.  
  • Can take in any standardized format of keys like XML signature keys, PXKS#1 formatted keys, and PuTTY keys. 

security-bundle: 

  • Provides a tight integration of the Security Component into the Symfony full-stack framework.  
  • Offers advanced options like firewalls, role_hierarchy, access_control, providers, and hashers. 
  • Also provides options to erase credentials, hide users who are not found, and access denied messages.  

security-core: 

  • Provides an infrastructure for sophisticated authorization systems that makes it possible to separate the actual authorization logic from user providers who hold the user credentials. 
  • Some HTTP-related security tools like CSRF protection and secure session cookies are provided. 
  • Offers all authentication and authorization features required for securing your application. 

security-core: 

  • Provides an infrastructure for sophisticated authorization systems that makes it possible to separate the actual authorization logic from user providers who hold the user credentials. 
  • Some HTTP-related security tools like CSRF protection and secure session cookies are provided. 
  • Offers all authentication and authorization features required for securing your application. 

security-csrf: 

  • Provides a class CsrfTokenManager to generate and validate CSRF tokens. 
  • Offers many tools for securing your application, like HTTP-related security tools like CSRF protection and secure session cookies. 
  • Provides authorization and authentication features for securing your application. 

security-http: 

  • The Security HTTP component will offer an HTTP integration of the core security component. 
  • Allows securing your application with the help of firewalls. 
  • Provides authenticators for authenticating users who visit your application. 

iniscan: 

  • Is a tool designed for scanning the php.ini file for common security practices and reporting the results.  
  • Used only in the command line and reports the results for displaying the passed and failed test cases.  
  • Offers a few commands for checking and showing the contents of your php.ini. 

PHP User Authentication Libraries help add user authentication capabilities to a website or application. It implements a secure authentication system. 


These use cases include Creating a secure user login system, allowing users to reset their passwords securely, storing user information in a secure database, etc.  


PHP User Authentication Libraries are libraries of code that allow developers to quickly and easily add user authentication capabilities to a website or application. These libraries provide functions and tools to help developers implement a secure authentication system, such as user registration, password hashing, session management, and access control.  


Let us have a look at these Libraries in Detail below. 

jwt-auth 

  • Offers a high degree of flexibility. 
  • Supports multiple authentication methods, such as OAuth2 and Basic Authentication. 
  • Supports multiple authorization methods, such as role-based authorization. 

hybridauth 

  • Works on multiple platforms such as PHP, Java, .NET, etc.  
  • Provides advanced security features such as OAuth 2.0, OpenID, etc.  
  • Provides high performance and is optimized for scalability. 

php-graph-sdk 

  • Provides industry-standard authentication and authorization protocols. 
  • Designed to be scalable and can handle thousands of users at once. 
  • Allows you to customize your authentication implementation. 

laravel-auth 

  • Supports token-based authentication. 
  • Provides database seeding. 
  • Supports authorization two-factor authentication. 

sanctum 

  • Allows you to define multiple authentication guards. 
  • Refresh and revoke authentication tokens. 
  • Helpful features such as token expiration, device limitation, and token revocation. 

CodeIgniter-Ion-Auth

  • Built with security in mind. 
  • Supports several different login methods. 
  • Easy to set up role-based permissions. 

HWIOAuthBundle 

  • Ensures secure authentication and authorization using the OAuth protocol. 
  • Highly customizable and allows developers to add new OAuth providers easily.  
  • Open source means developers can contribute to the project and access the source code. 

huge 

  • Cross-site request forgery (CSRF) protection. 
  • Password management with hashing, salting, and configurable complexity requirements. 
  • User session management with encrypted session data. 

opauth 

  • Supports a wide range of providers, including popular social media sites like Facebook. 
  • Built on a modular approach, which makes it flexible and extensible. 
  • Provides a secure authentication solution that helps keep users data safe. 

laravel-impersonate 

  • Secure and Reliable. 
  • Comprehensive Logging. 
  • Flexible Permissions. 

security-core 

  • Stores user data securely and can be used to store passwords. 
  • Provides advanced security features such as password hashing. 
  • Easy to use due to its intuitive and well-documented API. 

google2fa 

  • Uses TOTP, which generates a unique one-time code for each login. 
  • Provides an easy-to-navigate setup process. 
  • Allows users to generate backup codes in case they lose access to the device they use for two-factor authentication. 

UserFrosting 

  • Includes a powerful templating engine. 
  • Uses a modern web development stack, including Bootstrap etc. 
  • Allow developers to integrate user authentication and authorization into their applications easily. 

sentinel 

  • Easy integration with popular frameworks. 
  • A robust security framework. 
  • Role-based authorization. 

security-guard 

  • Provides user account management features such as password reset, password expiration, and account lockout.  
  • Offers secure authentication with two-factor authentication via Google Authenticator or YubiKey. 
  • Provides an out-of-the-box authentication system with password hashing, authentication rules, and access control lists. 

fortify 

  • Designed to be simple and intuitive for developers to use. 
  • Allows developers to customize the authentication process to their specific needs. 
  • Comes with extensive documentation to help developers get started quickly. 

google-auth-library-php 

  • Secure Authentication. 
  • Multi-Platform Support. 
  • Easy Integration. 

confide 

  • Role-Based Access Control. 
  • Uses bcrypt hashing algorithm to store a user's password securely. 
  • Allows developers to customize and configure the authentication system. 

yii2-admin 

  • Built-in protection from malicious attacks. 
  • Easy-to-use interface for administering user accounts. 
  • Mobile-friendly and has been optimized for use on mobile devices. 

halite 

  • Includes features such as brute-force protection, two-factor authentication, and password reset functionality. 
  • Uses modern cryptography techniques to protect user accounts. 
  • Used in most web frameworks, including Laravel, Symfony, and Slim.

FAQ

1. What are the main PHP user authentication libraries available?  

Here are the main PHP User Authentication libraries available:  

  • Laravel Sanctum  
  • Laravel Jetstream  
  • Symfony Security Component  
  • Auth0 PHP SDK  
  • Firebase Authentication  
  • PHP League OAuth2 Server  
  • Sentinel  
  • HybridAuth  
  • SimpleAuth  
  • Bouncer  
  • Aura.Auth  

  

2. How does one create a secure authentication system with PHP?  

Creating a secure authentication system with PHP involves many key practices and considerations. It ensures the protection of user data and prevents unauthorized access. Here is a step-by-step guide for helping you create a secure authentication system:  

  • Use Password Hashing  
  • Salting  
  • Strong Password Policies  
  • Secure Communication  
  • Authentication Tokens  
  • Session Management  
  • Account Lockout and Brute Force Protection  
  • Password Reset Mechanism  
  • Two-Factor Authentication (2FA)  
  • SQL Injection Prevention  
  • Input Validation and Sanitization  
  • Least Privilege Principle  
  • Secure Coding Practices  
  • User Education  
  • Logging and Monitoring  

  

3. What information does the OAuth consent screen show when you log into an application?  

The info shown on the consent screen when you log in to an app can vary. How you use the PHP User Authentication libraries, and the OAuth providers affects it. Here is a brief explanation of what you might see on an OAuth consent screen: 

  • Application Name and Logo  
  • Requested Permissions/Scopes  
  • Description  
  • User Information  
  • Authentication Provider  
  • Authorization Confirmation  
  • Option to Deny  
  • Remember Consent  
  • Third-Party Disclosure  
  • Legal Information  

  

4. Can one use different PHP User Authentication libraries in one login system?  

Yes. You can use many PHP User Authentication libraries in one login system. To ensure the libraries work well, we must carefully plan, integrate, and test them. This avoids conflicts and security problems. When using many authentication libraries together, remember these important things. You should also follow some steps: 

  • Compatibility  
  • Clear Use Cases  
  • User Data Consistency  
  • Authentication Flow  
  • Session and Token Management  
  • Security  
  • UI and User Experience  
  • Testing  
  • Documentation  
  • Maintainability  
  • Fallback Strategies  
  • Compliance and Regulations  

  

5. Is there a benefit to using a certain library for Laravel apps with user authentication?  

Choosing the right library is important when creating a user authenticated Laravel application. Laravel is a powerful PHP framework. It provides built-in authentication functionality, but there are also third-party libraries. It can enhance or extend this functionality. Using a specific library for Laravel applications with user authentication has benefits. 

  • Leverage Laravel’s Ecosystem  
  • Simplicity and Consistency  
  • Customization  
  • Socialite Integration  
  • Testing and Security  
  • Laravels Fortify and Jetstream  
  • Community and Documentation  
  • Rapid Development  
  • Simplicity for Small to Medium Projects  

  

6. Can we confirm users without using popular PHP User Authentication Libraries?  

Aside from PHP User Authentication Libraries, there are ways to check if users are real. These alternative methods can offer unique features or cater to specific use cases. Here are a few alternative methods:  

  • Biometric Authentication  
  • Physical Security Tokens  
  • Time-based One-time Passwords (TOTP)  
  • FIDO2/WebAuthn  
  • Client Certificate Authentication  
  • Blockchain-based Authentication  
  • Decentralized Identity (DID)  
  • OAuth 2.0 and OpenID Connect  
  • Smartphone-based Authentication  
  • Magic Links  
  • Behavioral Biometrics  
  • Risk-Based Authentication  
  • Voice Recognition  
  • Passwordless Authentication  
  • Adaptive Authentication 

Here are the best open-source PHP API libraries for your applications. You can use these collections of pre-written code that provide a set of functions, classes, and methods to access web APIs.

 

Web APIs are interfaces that allow software applications to communicate with each other over the internet. They are commonly used to integrate different systems, allowing developers to build more complex applications. Open-source libraries are available in PHP for many APIs, including social media platforms, payment gateways, and messaging platforms. They are designed to make it easier for developers to access and use APIs without writing code from scratch. Developers can quickly and easily integrate an API into the applications using a PHP API library. They can easily authenticate with the API, make requests, and handle responses. Many PHP API libraries also include additional features, such as caching and error handling, which can help improve the performance and reliability of the application.

 

In summary, PHP API libraries provide developers with a fast and easy way to access web APIs. They simplify the process of integrating APIs into applications and help to improve their functionality and reliability. We have handpicked the top and trending open-source PHP API libraries for your next application development project.

Guzzle:

  • Used to simplify the process of making HTTP requests.
  • Provides an easy-to-use interface for making requests.
  • Supports a wide range of HTTP methods.

Symfony HTTP Client:

  • Used for both synchronous and asynchronous requests.
  • Provides a high-level API for making HTTP requests.
  • Designed to be flexible and easy to use.

PHP League OAuth2 Client:

  • Used to add authentication to any PHP application.
  • It’s a simple and easy-to-use OAuth2 client for PHP.
  • Provides a common API for authenticating with OAuth2 services.

Google API PHP Client:

  • Used for making API requests and handling responses.
  • Offers a Client for accessing Google APIs.
  • Provides a simple and easy-to-use interface.

Facebook PHP SDK:

  • Used for accessing the Facebook API.
  • Provides a set of classes and methods.
  • Makes easy to generate API requests and handle responses.

Twitter API PHP:

  • Used for making API requests and handling responses.
  • It’s a wrapper for the Twitter API.
  • Provides an easy-to-use interface.

Mailchimp API:

  • Used for accessing the Mailchimp API.
  • Offers various classes and methods for making API requests and handling responses.
  • Allows you to get directly from the MailChimp API docs to the code.

Stripe PHP:

  • Used in Web Services, REST applications, etc.
  • It’s a wrapper for the Stripe API.
  • Includes a pre-defined set of classes for API resources.

Twilio PHP:

  • Used in Web Services, REST, Twilio applications, etc.
  • Allows communicating with the Twilio REST API.
  • Provides an easy-to-use interface for making API requests and generating TwiML.

GitHub API:

  • Used for making API requests and handling responses with an easy-to-use interface.
  • Offers a simple Object-oriented wrapper for GitHub API.
  • Uses GitHub API v3 & supports GitHub API v4. 

Here are the best open-source PHP routing libraries for your applications. You can use these tools in PHP web development to manage and direct user requests to appropriate controllers or actions.


These libraries allow developers to easily define routes that map URL patterns to specific PHP functions or methods. This simplifies handling HTTP requests and enables creation of complex web applications with clean and organized code. They provide a powerful routing system with a simple and intuitive API. Allowing developers to define routes using various methods, including regular expressions, placeholders, and custom conditions. While supporting advanced features like route caching and generating URLs based on route names, these libraries enable developers to:

  • Organize their code more effectively,
  • Reduce the complexity of handling HTTP requests, and
  • Provide a more intuitive user experience for website visitors.


Overall, PHP routing libraries are essential for web developers to create scalable and maintainable web applications. We have handpicked the top and trending open-source PHP routing libraries for your next application development project:

Symfony Routing:

  • Used to define routes using a variety of methods.
  • It’s a powerful routing system with a simple and intuitive API.
  • Features include regular expressions, placeholders, and custom conditions.

Laravel Routing:

  • Used in Networking, Router applications, etc.
  • Provides a clean, expressive syntax for defining routes.
  • Features include middleware, route groups, and named routes.

Slim Routing:

  • Used for building RESTful APIs.
  • It’s a lightweight and fast routing library.
  • Features include route caching, route groups, and route middleware.

FastRoute:

  • Used in Networking, Router applications, etc.
  • It’s a high-performance routing library optimized for speed and flexibility.
  • Supports multiple HTTP methods, placeholders, and regular expressions.

Phroute:

  • Used in Web Services, REST applications, etc.
  • It’s a simple and fast routing library with a straightforward API.
  • Features include route groups, before and after filters, and route caching.

Flight Routing:

  • Used for named routes, HTTP method support, URL parameters, and other features.
  • It’s a micro-framework that includes a simple routing system.
  • Offers a fast PHP router that can easily integrate with other routers.

Aura Router:

  • Used due to its powerful and flexible web routing for PSR-7 requests.
  • Supports multiple HTTP methods, placeholders, and named routes.
  • Others features include route middleware, subdomain routing, and route caching.

AltoRouter:

  • Used in Web Services, REST applications, etc.
  • It’s a lightweight and fast routing library heavily inspired by klein.php.
  • Supports regular expressions, named routes, and HTTP method filtering.

Klein Routing:

  • Used in Networking, Router, Framework applications, etc.
  • It’s a micro-framework with a fast & flexible router for PHP 5.3+.
  • Offers a simple routing system with route caching, before and after filters, and URL parameters.

Frame:

  • Used in Server, Application Framework, Framework applications, etc.
  • It’s a super simple PHP framework that uses Klein for routing.
  • Supports regular expressions and named routes.

Trending Discussions on PHP

Constant FILTER_SANITIZE_STRING is deprecated

Error: While updating laravel 8 to 9. Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Reference: Return type of ... should either be compatible with ..., or the #[\ReturnTypeWillChange] attribute should be used

"env: php: No such file or directory" on new mac OS Monterey

zsh: command not found: php

Message: Return type of CI_Session_files_driver::open($save_path, $name) should either be compatible with

What is never return type in PHP 8.1

Efficient summation in Python

Error: php@7.3 has been disabled because it is a versioned formula

Wrong PHP version used when installing composer with Alpine's apk command

QUESTION

Constant FILTER_SANITIZE_STRING is deprecated

Asked 2022-Mar-30 at 13:01

I have installed PHP 8.1 and I started testing my old project. I have used the filter FILTER_SANITIZE_STRING like so:

1$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
2

Now I get this error:

Deprecated: Constant FILTER_SANITIZE_STRING is deprecated

The same happens when I use FILTER_SANITIZE_STRIPPED:

Deprecated: Constant FILTER_SANITIZE_STRIPPED is deprecated

What can I replace it with?

ANSWER

Answered 2022-Jan-15 at 14:59

This was a filter of dubious purpose. It's difficult to say what it was meant to accomplish exactly or when it should be used. It was also confused with the default string filter, due to its name, when in reality the default string filter is called FILTER_UNSAFE_RAW. The PHP community decided that the usage of this filter should not be supported anymore.

The behaviour of this filter was very unintuitive. It removed everything between < and the end of the string or until the next >. It also removed all NUL bytes. Finally, it encoded ' and " into their HTML entities.

If you want to replace it, you have a couple of options:

  1. Use the default string filter FILTER_UNSAFE_RAW that doesn't do any filtering. This should be used if you had no idea about the behaviour of FILTER_SANITIZE_STRING and you just want to use a default filter that will give you the string value.

  2. If you used this filter to protect against XSS vulnerabilities, then replace its usage with htmlspecialchars(). Don't call this function on the input data. To protect against XSS you need to encode the output!

  3. If you knew exactly what that filter does and you want to create a polyfill, you can do that easily with regex.

1$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
2function filter_string_polyfill(string $string): string
3{
4    $str = preg_replace('/\x00|&lt;[^&gt;]*&gt;?/', '', $string);
5    return str_replace([&quot;'&quot;, '&quot;'], ['&amp;#39;', '&amp;#34;'], $str);
6}
7

Source https://stackoverflow.com/questions/69207368

QUESTION

Error: While updating laravel 8 to 9. Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Asked 2022-Mar-29 at 06:51

Nothing to install, update or remove Generating optimized autoload files Class App\Helpers\Helper located in C:/wamp64/www/vuexylaravel/app\Helpers\helpers.php does not comply with psr-4 autoloading standard. Skipping. > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi

1   Error 
2
3  Undefined constant Illuminate\Http\Request::HEADER_X_FORWARDED_ALL
4  at C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php:48
5     44▕      * - 'HEADER_X_FORWARDED_AWS_ELB' (If you are using AWS Elastic Load Balancer)
6     45▕      *
7     46▕      * @link https://symfony.com/doc/current/deployment/proxies.html
8     47▕      */
9  ➜  48▕     'headers' =&gt; Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
10     49▕
11     50▕ ];
12     51▕
13
14  1   C:\wamp64\www\vuexylaravel\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138
15      require()
16
17  2   C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\src\TrustedProxyServiceProvider.php:28
18      Illuminate\Support\ServiceProvider::mergeConfigFrom(&quot;C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php&quot;, &quot;trustedproxy&quot;)
19Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
20

ANSWER

Answered 2022-Feb-13 at 17:35

If you are upgrading your Laravel 8 project to Laravel 9 by importing your existing application code into a totally new Laravel 9 application skeleton, you may need to update your application's "trusted proxy" middleware.

Within your app/Http/Middleware/TrustProxies.php file, update use Fideloper\Proxy\TrustProxies as Middleware to use Illuminate\Http\Middleware\TrustProxies as Middleware.

Next, within app/Http/Middleware/TrustProxies.php, you should update the $headers property definition:

// Before...

protected $headers = Request::HEADER_X_FORWARDED_ALL;

// After...

1   Error 
2
3  Undefined constant Illuminate\Http\Request::HEADER_X_FORWARDED_ALL
4  at C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php:48
5     44▕      * - 'HEADER_X_FORWARDED_AWS_ELB' (If you are using AWS Elastic Load Balancer)
6     45▕      *
7     46▕      * @link https://symfony.com/doc/current/deployment/proxies.html
8     47▕      */
9  ➜  48▕     'headers' =&gt; Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
10     49▕
11     50▕ ];
12     51▕
13
14  1   C:\wamp64\www\vuexylaravel\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138
15      require()
16
17  2   C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\src\TrustedProxyServiceProvider.php:28
18      Illuminate\Support\ServiceProvider::mergeConfigFrom(&quot;C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php&quot;, &quot;trustedproxy&quot;)
19Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
20protected $headers =
21    Request::HEADER_X_FORWARDED_FOR |
22    Request::HEADER_X_FORWARDED_HOST |
23    Request::HEADER_X_FORWARDED_PORT |
24    Request::HEADER_X_FORWARDED_PROTO |
25    Request::HEADER_X_FORWARDED_AWS_ELB;
26

then run composer update

Make sure you are using PHP 8.0

Source https://stackoverflow.com/questions/71103241

QUESTION

Reference: Return type of ... should either be compatible with ..., or the #[\ReturnTypeWillChange] attribute should be used

Asked 2022-Mar-21 at 12:51

In PHP 8.1, the following code, which worked in previous versions:

1class Example implements Countable {
2    public function count() {
3        return 42;
4    }
5}
6

Raises a deprecation notice:

Deprecated: Return type of Example::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

What does this mean, and how should I fix it?

ANSWER

Answered 2022-Mar-21 at 12:51
Background: Return types and covariance

Since PHP 7.0, it has been possible to specify the return type of a function or method, such as function example(): string to indicate a function that returns a string. This forms a contract that other code can rely on.

For instance, this class promises that the getList method will return some kind of Iterator:

1class Example implements Countable {
2    public function count() {
3        return 42;
4    }
5}
6class Base {
7    public function getList(): Iterator {
8       // ...
9    }
10}
11

Calling code can be written knowing that if $foo instanceOf Base is true, then $foo->getList() instanceOf Iterator will also be true.

If you extend the class, you can specify the same return type, or a more specific return type (a rule known as "covariance"), and the calling code's assumption will still be true:

1class Example implements Countable {
2    public function count() {
3        return 42;
4    }
5}
6class Base {
7    public function getList(): Iterator {
8       // ...
9    }
10}
11class SubClass extends Base {
12    public function getList(): DirectoryIterator {
13        // ...
14    }
15}
16$foo = new SubClass;
17var_dump($foo instanceOf Base); // true
18var_dump($foo-&gt;getList() instanceOf Iterator); // true
19

But if you specify a different return type, or no return type at all, the assumption breaks, so PHP won't allow you to do it:

1class Example implements Countable {
2    public function count() {
3        return 42;
4    }
5}
6class Base {
7    public function getList(): Iterator {
8       // ...
9    }
10}
11class SubClass extends Base {
12    public function getList(): DirectoryIterator {
13        // ...
14    }
15}
16$foo = new SubClass;
17var_dump($foo instanceOf Base); // true
18var_dump($foo-&gt;getList() instanceOf Iterator); // true
19class NotPossible extends Base {
20    public function getList(): bool {
21        return false;
22    }
23}
24// Fatal error: Declaration of NotPossible::getList(): bool must be compatible with Base::getList(): Iterator
25// If the error didn't happen...
26$foo = new NotPossible;
27var_dump($foo instanceOf Base); // would be true
28var_dump($foo-&gt;getList() instanceOf Iterator); // would be false!
29
Backwards compatibility and deprecation

If you add a return type to an existing class or interface, every class extending or implementing must also be changed, or it will give the same error as in the NotPossible example above.

With the addition of Union Types in PHP 8.0, the return types of most internal functions and methods can be specified; but specifying it for any class or interface method not marked final would have immediately broken a lot of code.

So, instead, the concept of a "tentative" return type was added: the correct return types were documented, but what would normally be an error is instead the deprecation notice shown in the question.

The #[\ReturnTypeWillChange] attribute

The extra problem is that a lot of code needs to be able to run on multiple versions of PHP, and some of the added return types aren't valid in versions before 8.0. So, to indicate a planned change to the returned type in your code, you can add the special attribute #[\ReturnTypeWillChange]. This looks like a comment to older versions of PHP, but tells PHP 8.1 not to raise the deprecation notice. Then, once you don't need to support older versions of PHP, you can fix the return type.

What should you do now?

Firstly, read the message carefully to find out which method you need to change, and what the correct return type is. In the example above:

Return type of Example::count() ...

This says the count method on the Example class needs changing ...

... should either be compatible with Countable::count(): int ...

... and the expected return type is int, as defined on the Countable interface

Next, decide what you can do:

  • Is the code that needs to change in a library or extension written be someone else? Check if there is a new version available. Since this is only a deprecation, it's OK to ignore it and give the author time to fix it.
  • Does your class already return the correct type? In our example, yes, 42 is valid for a return type of int.
  • Can you safely change the return type of the method? If you're working on your own application, the answer is probably "yes", as long as you update classes that extend this one. If you're working on library code where users might have extended this class, you will need to consider the impact on them.

If you decide it's safe, you can simply add the return type as shown in the notice:

1class Example implements Countable {
2    public function count() {
3        return 42;
4    }
5}
6class Base {
7    public function getList(): Iterator {
8       // ...
9    }
10}
11class SubClass extends Base {
12    public function getList(): DirectoryIterator {
13        // ...
14    }
15}
16$foo = new SubClass;
17var_dump($foo instanceOf Base); // true
18var_dump($foo-&gt;getList() instanceOf Iterator); // true
19class NotPossible extends Base {
20    public function getList(): bool {
21        return false;
22    }
23}
24// Fatal error: Declaration of NotPossible::getList(): bool must be compatible with Base::getList(): Iterator
25// If the error didn't happen...
26$foo = new NotPossible;
27var_dump($foo instanceOf Base); // would be true
28var_dump($foo-&gt;getList() instanceOf Iterator); // would be false!
29class Example implements Countable {
30    public function count(): int {
31        return 42;
32    }
33}
34

If you need to support older versions of PHP, or users who won't have updated their code yet, you can temporarily suppress the notice:

1class Example implements Countable {
2    public function count() {
3        return 42;
4    }
5}
6class Base {
7    public function getList(): Iterator {
8       // ...
9    }
10}
11class SubClass extends Base {
12    public function getList(): DirectoryIterator {
13        // ...
14    }
15}
16$foo = new SubClass;
17var_dump($foo instanceOf Base); // true
18var_dump($foo-&gt;getList() instanceOf Iterator); // true
19class NotPossible extends Base {
20    public function getList(): bool {
21        return false;
22    }
23}
24// Fatal error: Declaration of NotPossible::getList(): bool must be compatible with Base::getList(): Iterator
25// If the error didn't happen...
26$foo = new NotPossible;
27var_dump($foo instanceOf Base); // would be true
28var_dump($foo-&gt;getList() instanceOf Iterator); // would be false!
29class Example implements Countable {
30    public function count(): int {
31        return 42;
32    }
33}
34class Example implements Countable {
35    #[\ReturnTypeWillChange]
36    public function count() {
37        return 42;
38    }
39}
40

It's important to note that the internal return types will probably be enforced in PHP 9.0, so make sure you have a solid plan to change methods you mark with this attribute.

Source https://stackoverflow.com/questions/71133749

QUESTION

&quot;env: php: No such file or directory&quot; on new mac OS Monterey

Asked 2022-Mar-09 at 14:19

i've updated my mac os to Monterey (12) and then I can not use composer command or php command and get this error

1env: php: No such file or directory
2

ANSWER

Answered 2021-Oct-28 at 08:10

PHP has been removed from MacOS since v12 (Monterey), so you first need to install it on your own to use it. From my POV, the easiest way to do this is using Homebrew

Source https://stackoverflow.com/questions/69749160

QUESTION

zsh: command not found: php

Asked 2022-Feb-16 at 18:52

I have been using php with mamp on mac for a year even with old versions of MacOS, since I installed MacOS Monterrey if I type php on the terminal I get a message:zsh: command not found: php

Using older versions of MacOS I have never had this problem.

How can I solve the problem?

ANSWER

Answered 2021-Oct-31 at 12:03

You probably need to fix it in the .bashrc file.

Do this:

Open the terminal and run this command:

1nano ~/.bashrc 
2

Then add this line in the .bashrc file:

1nano ~/.bashrc 
2export PATH=$PATH:/usr/share/php/bin
3

Save and exit (ctrl + x)

Source https://stackoverflow.com/questions/69786222

QUESTION

Message: Return type of CI_Session_files_driver::open($save_path, $name) should either be compatible with

Asked 2022-Feb-16 at 14:37

I got this error after install a new xampp version (php8). and clone my codeigniter project.

1Message: Return type of CI_Session_files_driver::open($save_path, $name)
2should either be compatible with SessionHandlerInterface::open(string $path, string $name):
3bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice
4

Filename: drivers/Session_files_driver.php

Line Number: 132

ANSWER

Answered 2022-Feb-16 at 14:37

For anyone else that comes across this error, I also experienced it after upgrading to PHP 8.1. The only way I could find to "fix" it was by adding #[\ReturnTypeWillChange] before the open, read, write, close, destroy and gc functions in /system/libraries/Session/drivers/Session_files_driver.php. For example:

1Message: Return type of CI_Session_files_driver::open($save_path, $name)
2should either be compatible with SessionHandlerInterface::open(string $path, string $name):
3bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice
4#[\ReturnTypeWillChange]
5public function open($save_path, $name)
6{
7...
8

Source https://stackoverflow.com/questions/70508122

QUESTION

What is never return type in PHP 8.1

Asked 2022-Feb-14 at 09:32

PHP 8.1 introduces never return type, what is it? and what is the difference between never and void?

ANSWER

Answered 2022-Feb-14 at 09:32

never type declaration introduced to be used as a return type hint for functions that never have return statement neither implicit nor explicit. And must be terminated by throwing an exception or exiting using exit/die functions.

1function redirect(string $uri): never 
2{
3    header('Location: ' . $uri);
4    exit();
5}
6

Here redirect is called a never-returning function, because:

1) It has no return statement defined explicitly.

1function redirect(string $uri): never 
2{
3    header('Location: ' . $uri);
4    exit();
5}
6function redirect(string $uri): never 
7{
8    exit();
9    return 'something';
10}
11

Will prodcue:

PHP Fatal error: A never-returning function must not return

2) It has no return statement defined implicitly.

1function redirect(string $uri): never 
2{
3    header('Location: ' . $uri);
4    exit();
5}
6function redirect(string $uri): never 
7{
8    exit();
9    return 'something';
10}
11function redirect(string $uri): never
12{
13    if (false) {
14        header('Location: ' . $uri);
15        exit();
16    }
17}
18

Since the condition here is never satisfied, the execution jump over the if statement returning an implicit NULL which will result in:

PHP Fatal error: Uncaught TypeError: redirect(): never-returning function must not implicitly return

3) It ends it's execution with an exit function

void vs never
  • void can have return; but never can't.
  • never enforces that a function throws or is terminated with exit/die but void does not.
  • never is a subtype of every other type in PHP’s type system, including void (this allows return type covariance).
  • Both don't allow returning a value.
  • Both can't be used as a parameter or a property type.
  • Both can't be used as a return type of an arrow function.
  • Both can only be used as a standalone type (no union or intersection is allowed).
When to choose void over never and vice versa?

You should declare a function return type void when you expect PHP to execute the next statement after the function call. And you should declare it never when you don't expect PHP to execute the next statement after that function call.

Source https://stackoverflow.com/questions/68529614

QUESTION

Efficient summation in Python

Asked 2022-Jan-16 at 12:49

I am trying to efficiently compute a summation of a summation in Python:

WolframAlpha is able to compute it too a high n value: sum of sum.

I have two approaches: a for loop method and an np.sum method. I thought the np.sum approach would be faster. However, they are the same until a large n, after which the np.sum has overflow errors and gives the wrong result.

I am trying to find the fastest way to compute this sum.

1import numpy as np
2import time
3
4def summation(start,end,func):
5    sum=0
6    for i in range(start,end+1):
7        sum+=func(i)
8    return sum
9
10def x(y):
11    return y
12
13def x2(y):
14    return y**2
15
16def mysum(y):
17    return x2(y)*summation(0, y, x)
18
19n=100
20
21# method #1
22start=time.time()
23summation(0,n,mysum)
24print('Slow method:',time.time()-start)
25
26# method #2
27start=time.time()
28w=np.arange(0,n+1)
29(w**2*np.cumsum(w)).sum()
30print('Fast method:',time.time()-start)
31

ANSWER

Answered 2022-Jan-16 at 12:49

(fastest methods, 3 and 4, are at the end)

In a fast NumPy method you need to specify dtype=np.object so that NumPy does not convert Python int to its own dtypes (np.int64 or others). It will now give you correct results (checked it up to N=100000).

1import numpy as np
2import time
3
4def summation(start,end,func):
5    sum=0
6    for i in range(start,end+1):
7        sum+=func(i)
8    return sum
9
10def x(y):
11    return y
12
13def x2(y):
14    return y**2
15
16def mysum(y):
17    return x2(y)*summation(0, y, x)
18
19n=100
20
21# method #1
22start=time.time()
23summation(0,n,mysum)
24print('Slow method:',time.time()-start)
25
26# method #2
27start=time.time()
28w=np.arange(0,n+1)
29(w**2*np.cumsum(w)).sum()
30print('Fast method:',time.time()-start)
31# method #2
32start=time.time()
33w=np.arange(0, n+1, dtype=np.object)
34result2 = (w**2*np.cumsum(w)).sum()
35print('Fast method:', time.time()-start)
36

Your fast solution is significantly faster than the slow one. Yes, for large N's, but already at N=100 it is like 8 times faster:

1import numpy as np
2import time
3
4def summation(start,end,func):
5    sum=0
6    for i in range(start,end+1):
7        sum+=func(i)
8    return sum
9
10def x(y):
11    return y
12
13def x2(y):
14    return y**2
15
16def mysum(y):
17    return x2(y)*summation(0, y, x)
18
19n=100
20
21# method #1
22start=time.time()
23summation(0,n,mysum)
24print('Slow method:',time.time()-start)
25
26# method #2
27start=time.time()
28w=np.arange(0,n+1)
29(w**2*np.cumsum(w)).sum()
30print('Fast method:',time.time()-start)
31# method #2
32start=time.time()
33w=np.arange(0, n+1, dtype=np.object)
34result2 = (w**2*np.cumsum(w)).sum()
35print('Fast method:', time.time()-start)
36start=time.time()
37for i in range(100):
38    result1 = summation(0, n, mysum)
39print('Slow method:', time.time()-start)
40
41# method #2
42start=time.time()
43for i in range(100):
44    w=np.arange(0, n+1, dtype=np.object)
45    result2 = (w**2*np.cumsum(w)).sum()
46print('Fast method:', time.time()-start)
47
1import numpy as np
2import time
3
4def summation(start,end,func):
5    sum=0
6    for i in range(start,end+1):
7        sum+=func(i)
8    return sum
9
10def x(y):
11    return y
12
13def x2(y):
14    return y**2
15
16def mysum(y):
17    return x2(y)*summation(0, y, x)
18
19n=100
20
21# method #1
22start=time.time()
23summation(0,n,mysum)
24print('Slow method:',time.time()-start)
25
26# method #2
27start=time.time()
28w=np.arange(0,n+1)
29(w**2*np.cumsum(w)).sum()
30print('Fast method:',time.time()-start)
31# method #2
32start=time.time()
33w=np.arange(0, n+1, dtype=np.object)
34result2 = (w**2*np.cumsum(w)).sum()
35print('Fast method:', time.time()-start)
36start=time.time()
37for i in range(100):
38    result1 = summation(0, n, mysum)
39print('Slow method:', time.time()-start)
40
41# method #2
42start=time.time()
43for i in range(100):
44    w=np.arange(0, n+1, dtype=np.object)
45    result2 = (w**2*np.cumsum(w)).sum()
46print('Fast method:', time.time()-start)
47Slow method: 0.06906533241271973
48Fast method: 0.008007287979125977
49

EDIT: Even faster method (by KellyBundy, the Pumpkin) is by using pure python. Turns out NumPy has no advantage here, because it has no vectorized code for np.objects.

1import numpy as np
2import time
3
4def summation(start,end,func):
5    sum=0
6    for i in range(start,end+1):
7        sum+=func(i)
8    return sum
9
10def x(y):
11    return y
12
13def x2(y):
14    return y**2
15
16def mysum(y):
17    return x2(y)*summation(0, y, x)
18
19n=100
20
21# method #1
22start=time.time()
23summation(0,n,mysum)
24print('Slow method:',time.time()-start)
25
26# method #2
27start=time.time()
28w=np.arange(0,n+1)
29(w**2*np.cumsum(w)).sum()
30print('Fast method:',time.time()-start)
31# method #2
32start=time.time()
33w=np.arange(0, n+1, dtype=np.object)
34result2 = (w**2*np.cumsum(w)).sum()
35print('Fast method:', time.time()-start)
36start=time.time()
37for i in range(100):
38    result1 = summation(0, n, mysum)
39print('Slow method:', time.time()-start)
40
41# method #2
42start=time.time()
43for i in range(100):
44    w=np.arange(0, n+1, dtype=np.object)
45    result2 = (w**2*np.cumsum(w)).sum()
46print('Fast method:', time.time()-start)
47Slow method: 0.06906533241271973
48Fast method: 0.008007287979125977
49# method #3
50import itertools
51start=time.time()
52for i in range(100):
53    result3 = sum(x*x * ysum for x, ysum in enumerate(itertools.accumulate(range(n+1))))
54print('Faster, pure python:', (time.time()-start))
55
1import numpy as np
2import time
3
4def summation(start,end,func):
5    sum=0
6    for i in range(start,end+1):
7        sum+=func(i)
8    return sum
9
10def x(y):
11    return y
12
13def x2(y):
14    return y**2
15
16def mysum(y):
17    return x2(y)*summation(0, y, x)
18
19n=100
20
21# method #1
22start=time.time()
23summation(0,n,mysum)
24print('Slow method:',time.time()-start)
25
26# method #2
27start=time.time()
28w=np.arange(0,n+1)
29(w**2*np.cumsum(w)).sum()
30print('Fast method:',time.time()-start)
31# method #2
32start=time.time()
33w=np.arange(0, n+1, dtype=np.object)
34result2 = (w**2*np.cumsum(w)).sum()
35print('Fast method:', time.time()-start)
36start=time.time()
37for i in range(100):
38    result1 = summation(0, n, mysum)
39print('Slow method:', time.time()-start)
40
41# method #2
42start=time.time()
43for i in range(100):
44    w=np.arange(0, n+1, dtype=np.object)
45    result2 = (w**2*np.cumsum(w)).sum()
46print('Fast method:', time.time()-start)
47Slow method: 0.06906533241271973
48Fast method: 0.008007287979125977
49# method #3
50import itertools
51start=time.time()
52for i in range(100):
53    result3 = sum(x*x * ysum for x, ysum in enumerate(itertools.accumulate(range(n+1))))
54print('Faster, pure python:', (time.time()-start))
55Faster, pure python: 0.0009944438934326172
56

EDIT2: Forss noticed that numpy fast method can be optimized by using x*x instead of x**2. For N > 200 it is faster than pure Python method. For N < 200 it is slower than pure Python method (the exact value of boundary may depend on machine, on mine it was 200, its best to check it yourself):

1import numpy as np
2import time
3
4def summation(start,end,func):
5    sum=0
6    for i in range(start,end+1):
7        sum+=func(i)
8    return sum
9
10def x(y):
11    return y
12
13def x2(y):
14    return y**2
15
16def mysum(y):
17    return x2(y)*summation(0, y, x)
18
19n=100
20
21# method #1
22start=time.time()
23summation(0,n,mysum)
24print('Slow method:',time.time()-start)
25
26# method #2
27start=time.time()
28w=np.arange(0,n+1)
29(w**2*np.cumsum(w)).sum()
30print('Fast method:',time.time()-start)
31# method #2
32start=time.time()
33w=np.arange(0, n+1, dtype=np.object)
34result2 = (w**2*np.cumsum(w)).sum()
35print('Fast method:', time.time()-start)
36start=time.time()
37for i in range(100):
38    result1 = summation(0, n, mysum)
39print('Slow method:', time.time()-start)
40
41# method #2
42start=time.time()
43for i in range(100):
44    w=np.arange(0, n+1, dtype=np.object)
45    result2 = (w**2*np.cumsum(w)).sum()
46print('Fast method:', time.time()-start)
47Slow method: 0.06906533241271973
48Fast method: 0.008007287979125977
49# method #3
50import itertools
51start=time.time()
52for i in range(100):
53    result3 = sum(x*x * ysum for x, ysum in enumerate(itertools.accumulate(range(n+1))))
54print('Faster, pure python:', (time.time()-start))
55Faster, pure python: 0.0009944438934326172
56# method #4
57start=time.time()
58for i in range(100):
59    w = np.arange(0, n+1, dtype=np.object)
60    result2 = (w*w*np.cumsum(w)).sum()
61print('Fast method x*x:', time.time()-start)
62

Source https://stackoverflow.com/questions/69864793

QUESTION

Error: php@7.3 has been disabled because it is a versioned formula

Asked 2022-Jan-08 at 14:32

I try to install php@7.3 using brew. But, it return error because it is versioned formula. What is it?

command: brew install php@7.3

result: Error: php@7.3 has been disabled because it is a versioned formula!

ANSWER

Answered 2021-Dec-21 at 06:24

You can only install supported versions of PHP with brew. However, there is the tap shivammathur/php which can be used to install unsupported version of PHP.

  1. brew tap shivammathur/php
  2. brew install shivammathur/php/php@7.3

The first step only needs to be done once. After adding the tap, you can install PHP version 5.6 - 8.2.

Source https://stackoverflow.com/questions/70417377

QUESTION

Wrong PHP version used when installing composer with Alpine's apk command

Asked 2021-Dec-23 at 11:20

I've got a docker image running 8.0 and want to upgrade to 8.1. I have updated the image to run with PHP 8.1 and want to update the dependencies in it.

The new image derives from php:8.1.1-fpm-alpine3.15

I've updated the composer.json and changed require.php to ^8.1 but ran into the following message when running composer upgrade:

1Root composer.json requires php ^8.1 but your php version (8.0.14) does not satisfy that requirement.
2

What I find dazzling is that the composer incorrectly identifies PHP version. I used two commands to determine that:

1Root composer.json requires php ^8.1 but your php version (8.0.14) does not satisfy that requirement.
2which php # returns only /usr/local/bin/php
3/usr/local/bin/php -v # returns PHP 8.1.1 (cli) (built: Dec 18 2021 01:38:53) (NTS)
4

So far I've tried:

  • Checking php -v
  • Clearing composer cache
  • Rebuilding image

Composer version 2.1.12 2021-11-09 16:02:04

1Root composer.json requires php ^8.1 but your php version (8.0.14) does not satisfy that requirement.
2which php # returns only /usr/local/bin/php
3/usr/local/bin/php -v # returns PHP 8.1.1 (cli) (built: Dec 18 2021 01:38:53) (NTS)
4composer check-platform-reqs | grep php
5# returns:
6# ...
7# php                   8.0.14  project/name requires php (^8.1)                   failed  
8

All of the commands above (excluding docker commands) are being ran in the container

Dockerfile:

1Root composer.json requires php ^8.1 but your php version (8.0.14) does not satisfy that requirement.
2which php # returns only /usr/local/bin/php
3/usr/local/bin/php -v # returns PHP 8.1.1 (cli) (built: Dec 18 2021 01:38:53) (NTS)
4composer check-platform-reqs | grep php
5# returns:
6# ...
7# php                   8.0.14  project/name requires php (^8.1)                   failed  
8FROM php:8.1.1-fpm-alpine3.15
9
10ENV TZ=Europe/London
11
12# Install php lib deps
13RUN apk update &amp;&amp; apk upgrade
14RUN apk add --update libzip-dev \
15        zip \
16        unzip \
17        libpng-dev \
18        nginx \
19        supervisor \
20        git \
21        curl \
22        shadow \
23        composer \
24        yarn &amp;&amp; rm -rf /var/cache/apk/*
25
26RUN usermod -u 1000 www-data
27RUN usermod -d /var/www www-data
28
29RUN mkdir -p /run/nginx &amp;&amp; chown www-data:www-data /run/nginx
30
31ENV SUPERCRONIC_URL=https://github.com/aptible/supercronic/releases/download/v0.1.9/supercronic-linux-amd64 \
32    SUPERCRONIC=supercronic-linux-amd64 \
33    SUPERCRONIC_SHA1SUM=5ddf8ea26b56d4a7ff6faecdd8966610d5cb9d85
34
35RUN curl -fsSLO &quot;$SUPERCRONIC_URL&quot; \
36 &amp;&amp; echo &quot;${SUPERCRONIC_SHA1SUM}  ${SUPERCRONIC}&quot; | sha1sum -c - \
37 &amp;&amp; chmod +x &quot;$SUPERCRONIC&quot; \
38 &amp;&amp; mv &quot;$SUPERCRONIC&quot; &quot;/usr/local/bin/${SUPERCRONIC}&quot; \
39 &amp;&amp; ln -s &quot;/usr/local/bin/${SUPERCRONIC}&quot; /usr/local/bin/supercronic
40
41# Install and enable php extensions
42RUN docker-php-ext-install sockets mysqli pdo_mysql zip gd bcmath &gt; /dev/null
43
44ARG ENV=&quot;development&quot;
45# Xdebug install
46RUN if [ $ENV = &quot;development&quot; ] ; then \
47        apk add --no-cache $PHPIZE_DEPS; \
48        pecl install xdebug &gt; /dev/null; \
49        docker-php-ext-enable xdebug; \
50        echo &quot;error_reporting = E_ALL&quot; &gt;&gt; /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
51        echo &quot;display_startup_errors = On&quot; &gt;&gt; /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
52        echo &quot;display_errors = On&quot; &gt;&gt; /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
53        echo &quot;xdebug.remote_enable=1&quot; &gt;&gt; /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
54    fi ;
55
56# Setup working directory
57RUN chown -R www-data:www-data /var/www
58WORKDIR /var/www
59USER www-data
60
61
62# Install dependencies
63#RUN if [ $ENV = &quot;development&quot; ] ; then \
64##        composer install -n; \
65#    else \
66##        composer install -n --no-dev; \
67#    fi ;
68
69# Generate doctrine proxies
70

ANSWER

Answered 2021-Dec-23 at 11:20

Huh. This surprised me a bit.

composer is correctly reporting the PHP version it's using. The problem is that it's not using the "correct" PHP interpreter.

The issue arises because of how you are installing composer.

Apparently by doing apk add composer another version of PHP gets installed (you can find it on /usr/bin/php8, this is the one on version 8.0.14).

Instead of letting apk install composer for you, you can do it manually. There is nothing much to install it in any case, no need to go through the package manager. Particularly since PHP has not been installed via the package manager on your base image.

I've just removed the line containing composer from the apk add --update command, and added this somewhere below:

1Root composer.json requires php ^8.1 but your php version (8.0.14) does not satisfy that requirement.
2which php # returns only /usr/local/bin/php
3/usr/local/bin/php -v # returns PHP 8.1.1 (cli) (built: Dec 18 2021 01:38:53) (NTS)
4composer check-platform-reqs | grep php
5# returns:
6# ...
7# php                   8.0.14  project/name requires php (^8.1)                   failed  
8FROM php:8.1.1-fpm-alpine3.15
9
10ENV TZ=Europe/London
11
12# Install php lib deps
13RUN apk update &amp;&amp; apk upgrade
14RUN apk add --update libzip-dev \
15        zip \
16        unzip \
17        libpng-dev \
18        nginx \
19        supervisor \
20        git \
21        curl \
22        shadow \
23        composer \
24        yarn &amp;&amp; rm -rf /var/cache/apk/*
25
26RUN usermod -u 1000 www-data
27RUN usermod -d /var/www www-data
28
29RUN mkdir -p /run/nginx &amp;&amp; chown www-data:www-data /run/nginx
30
31ENV SUPERCRONIC_URL=https://github.com/aptible/supercronic/releases/download/v0.1.9/supercronic-linux-amd64 \
32    SUPERCRONIC=supercronic-linux-amd64 \
33    SUPERCRONIC_SHA1SUM=5ddf8ea26b56d4a7ff6faecdd8966610d5cb9d85
34
35RUN curl -fsSLO &quot;$SUPERCRONIC_URL&quot; \
36 &amp;&amp; echo &quot;${SUPERCRONIC_SHA1SUM}  ${SUPERCRONIC}&quot; | sha1sum -c - \
37 &amp;&amp; chmod +x &quot;$SUPERCRONIC&quot; \
38 &amp;&amp; mv &quot;$SUPERCRONIC&quot; &quot;/usr/local/bin/${SUPERCRONIC}&quot; \
39 &amp;&amp; ln -s &quot;/usr/local/bin/${SUPERCRONIC}&quot; /usr/local/bin/supercronic
40
41# Install and enable php extensions
42RUN docker-php-ext-install sockets mysqli pdo_mysql zip gd bcmath &gt; /dev/null
43
44ARG ENV=&quot;development&quot;
45# Xdebug install
46RUN if [ $ENV = &quot;development&quot; ] ; then \
47        apk add --no-cache $PHPIZE_DEPS; \
48        pecl install xdebug &gt; /dev/null; \
49        docker-php-ext-enable xdebug; \
50        echo &quot;error_reporting = E_ALL&quot; &gt;&gt; /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
51        echo &quot;display_startup_errors = On&quot; &gt;&gt; /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
52        echo &quot;display_errors = On&quot; &gt;&gt; /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
53        echo &quot;xdebug.remote_enable=1&quot; &gt;&gt; /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
54    fi ;
55
56# Setup working directory
57RUN chown -R www-data:www-data /var/www
58WORKDIR /var/www
59USER www-data
60
61
62# Install dependencies
63#RUN if [ $ENV = &quot;development&quot; ] ; then \
64##        composer install -n; \
65#    else \
66##        composer install -n --no-dev; \
67#    fi ;
68
69# Generate doctrine proxies
70 RUN php -r &quot;copy('https://getcomposer.org/installer', 'composer-setup.php');&quot; &amp;&amp; \
71     php -r &quot;if (hash_file('sha384', 'composer-setup.php') === '906a84df04cea2aa72f40b5f787e49f22d4c2f19492ac310e8cba5b96ac8b64115ac402c8cd292b8a03482574915d1a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;&quot; &amp;&amp; \
72     php composer-setup.php &amp;&amp; \
73     php -r &quot;unlink('composer-setup.php');&quot; &amp;&amp; \
74     mv composer.phar /usr/local/bin/composer;
75

You could also simply download the latest composer PHAR file from here, and add it to the image, depending on how you want to go.

Now there is a single PHP version, and composer will run correctly on PHP 8.1.1.

Source https://stackoverflow.com/questions/70439028

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in PHP

Share this Page

share link

Get latest updates on PHP