#php (int)
Explore tagged Tumblr posts
infoanalysishub · 4 days ago
Text
PHP Casting Tutorial with Examples – Type Conversion in PHP
Learn PHP type casting with real examples. Understand how to convert data types using (int), (float), (string), (bool), and more in PHP. PHP Casting: Complete Guide with Examples Type casting is an essential concept in PHP that allows you to convert a variable from one data type to another. PHP is a loosely typed language, which means it does automatic type conversion based on the context.…
0 notes
codingquill · 2 years ago
Text
SQL Fundamentals #1: SQL Data Definition
Last year in college , I had the opportunity to dive deep into SQL. The course was made even more exciting by an amazing instructor . Fast forward to today, and I regularly use SQL in my backend development work with PHP. Today, I felt the need to refresh my SQL knowledge a bit, and that's why I've put together three posts aimed at helping beginners grasp the fundamentals of SQL.
Understanding Relational Databases
Let's Begin with the Basics: What Is a Database?
Simply put, a database is like a digital warehouse where you store large amounts of data. When you work on projects that involve data, you need a place to keep that data organized and accessible, and that's where databases come into play.
Exploring Different Types of Databases
When it comes to databases, there are two primary types to consider: relational and non-relational.
Relational Databases: Structured Like Tables
Think of a relational database as a collection of neatly organized tables, somewhat like rows and columns in an Excel spreadsheet. Each table represents a specific type of information, and these tables are interconnected through shared attributes. It's similar to a well-organized library catalog where you can find books by author, title, or genre.
Key Points:
Tables with rows and columns.
Data is neatly structured, much like a library catalog.
You use a structured query language (SQL) to interact with it.
Ideal for handling structured data with complex relationships.
Non-Relational Databases: Flexibility in Containers
Now, imagine a non-relational database as a collection of flexible containers, more like bins or boxes. Each container holds data, but they don't have to adhere to a fixed format. It's like managing a diverse collection of items in various boxes without strict rules. This flexibility is incredibly useful when dealing with unstructured or rapidly changing data, like social media posts or sensor readings.
Key Points:
Data can be stored in diverse formats.
There's no rigid structure; adaptability is the name of the game.
Non-relational databases (often called NoSQL databases) are commonly used.
Ideal for handling unstructured or dynamic data.
Now, Let's Dive into SQL:
Tumblr media
SQL is a :
Data Definition language ( what todays post is all about )
Data Manipulation language
Data Query language
Task: Building and Interacting with a Bookstore Database
Setting Up the Database
Our first step in creating a bookstore database is to establish it. You can achieve this with a straightforward SQL command:
CREATE DATABASE bookstoreDB;
SQL Data Definition
As the name suggests, this step is all about defining your tables. By the end of this phase, your database and the tables within it are created and ready for action.
Tumblr media
1 - Introducing the 'Books' Table
A bookstore is all about its collection of books, so our 'bookstoreDB' needs a place to store them. We'll call this place the 'books' table. Here's how you create it:
CREATE TABLE books ( -- Don't worry, we'll fill this in soon! );
Now, each book has its own set of unique details, including titles, authors, genres, publication years, and prices. These details will become the columns in our 'books' table, ensuring that every book can be fully described.
Now that we have the plan, let's create our 'books' table with all these attributes:
CREATE TABLE books ( title VARCHAR(40), author VARCHAR(40), genre VARCHAR(40), publishedYear DATE, price INT(10) );
With this structure in place, our bookstore database is ready to house a world of books.
2 - Making Changes to the Table
Sometimes, you might need to modify a table you've created in your database. Whether it's correcting an error during table creation, renaming the table, or adding/removing columns, these changes are made using the 'ALTER TABLE' command.
For instance, if you want to rename your 'books' table:
ALTER TABLE books RENAME TO books_table;
If you want to add a new column:
ALTER TABLE books ADD COLUMN description VARCHAR(100);
Or, if you need to delete a column:
ALTER TABLE books DROP COLUMN title;
3 - Dropping the Table
Finally, if you ever want to remove a table you've created in your database, you can do so using the 'DROP TABLE' command:
DROP TABLE books;
To keep this post concise, our next post will delve into the second step, which involves data manipulation. Once our bookstore database is up and running with its tables, we'll explore how to modify and enrich it with new information and data. Stay tuned ...
Part2
112 notes · View notes
cerulity · 3 months ago
Text
Common Things Vulnerable to Y2K38 (+ Explanation)
I want to compile a list of things I find that are vulnerable to the Y2K38 bug. If you find any I don't know about, I can add them to the list. But first, an explanation...
What is Y2K38?
For those that aren't aware, past January 19, 2038 at 3:14:07 UTC (2038-01-19T03:14:07Z), the number of seconds since midnight of January 1, 1970 (1970-01-01T00:00:00Z) will surpass 2^31 - 1.
So what are the implications of this? It has to do with how computers store time.
The Unix epoch is defined as the number of seconds since January 1, 1970, and this is universal to both Unix and Windows systems (so virtually every single computer that doesn't have a homemade operating system). The issue is what specific types of numbers are used to store the epoch.
There are two properties to an integer type: size and sign. The size dictates how many bits a number can hold, and the sign dictates whether or not the integer can store negative numbers. If the number is unsigned, it will be able to store numbers ranging from zero to 2^n - 1, where n is the size of the integer in bits. This means that an 8-bit unsigned number can hold numbers ranging from 0 to 255, because 2^8 - 1 is 255. If a number is signed, the positive range is cut in half. Signed numbers range from -2^(n - 1) to 2^(n - 1) - 1. This means that an 8-bit signed integer can hold numbers ranging from -128 to 127, as -2^7 is -128, and 2^7 - 1 is 127. As integers are used to store the Unix epoch, this means that the epoch is limited to the range of the integer type you use to store it.
If you decide to use a 32-bit signed integer to store the Unix epoch, then once the epoch reaches 2^31 - 1 (which is the upper limit of 32-bit signed integers and is around 2.1 billion), the epoch won't be able to increase anymore. So what happens when we try to increase it anyways? We get an integer overflow.
Due to how CPUs add numbers together, when the result of an operation is larger than the range of the integer type, the result is wrapped around. For example, if you have the number 127 in an 8-bit signed integer, adding one will wrap around to -128! This is a problem for the epoch, because now, instead of storing 2.1 billion seconds past January 1, 1970, it will now be storing 2.1 billion seconds before 1970, which goes all the way back to December 1901!
So why not just use a bigger number? Well, it's not really that simple. There has been an effort to switch over to 64-bit integers, which has an overwhelmingly generous range of around 21 times the estimated age of the universe. However, there are some systems that just can't change or haven't changed for a variety of reasons, and this is what the list will be about. There are two main causes for the Y2K38 bug, and most vulnerabilities stem from them:
32-bit representation of of time_t: time_t is the integer type that time is stored in. When a C program calls the time() function, it will receive a time_t. If time_t is 32-bits long, then the time() function will be vulnerable.
Downcasting the result of time(): There's a pattern in programming I like to call "int-defaultness". C's primitive types are not named with sizes. Instead, they are called 'char', 'short', 'int', and 'long'. These types are standardised to be at least 8 bits, 16 bits, 32 bits, and 64 bits respectively, but most platforms just use those sizes exactly. Usually, you would use exact-sized types like int16_t, uint64_t, and so on, or if it's a function like time(), you would use time_t. However, it is a common pattern to default to int as an integer type, and someone who isn't careful may just convert the result of the time() function into an int. This is known as downcasting, which is the conversion from one integer type to a smaller one. Regardless of whether or not time_t is 32 bits or 64 bits, this downcast will always convert the time to 32 bits, and the overflow behaviour will apply, leaving PHP vulnerable.
As you can see, the time() function is the root cause of the bug, and due to its popularity, usages and mimics of time() can be left vulnerable.
So, without further ado, here is...
The List of Vulnerabilities
PHP time() function: PHP has a time() function that acts very similar to C's, and if the size of a PHP int is 32 bits, PHP is left vulnerable.
pcap file format: The pcap file format (used by libpcap, which is used by utilities like tcpdump and Wireshark) is a format for storing captured packets, and the specification states that the timestamps of packets must stored in a 32-bit unsigned integer. Luckily, since it is unsigned, this will overflow in the year 2106, but there is still some vulnerability here. The PcapNG file format uses 64-bit timestamps, which prevents the vulnerability.
Embedded systems: Smaller computers have a tendency towards lower bit-widths, and 32 bits is common. Embedded systems control things like radios, elevators, GPSes, and more things that don't require heaps of computation power. These systems commonly define time_t to be 32 bits, making them vulnerable.
2 notes · View notes
om-kumar123 · 2 days ago
Text
PHP array_slice() Function
The array_slice() function is an inbuilt function of PHP. The array_slice() function is used to extract a slice of an array. This function was introduced in 4.0.
Syntax
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] );  
Tumblr media
0 notes
saeedmohammed025 · 14 days ago
Text
Essential Skills Every Aspiring Web Developer Should Master
Tumblr media
In today’s digital landscape, having a powerful online presence is no longer a luxury but a necessity. Businesses in Oman are rapidly embracing digital transformation, and the demand for proficient web developers has skyrocketed. Whether you're looking to join a Web Development Company in Oman or start your freelance journey, mastering a specific set of skills can set you apart in this competitive industry.
This blog explores the essential skills every aspiring web developer should acquire to thrive in the dynamic field of web development.
1. Proficiency in HTML, CSS, and JavaScript
These three foundational technologies form the backbone of web development:
HTML (HyperText Markup Language) structures the content on the web page.
CSS (Cascading Style Sheets) styles and layouts the content.
JavaScript makes websites interactive and dynamic.
Mastering these languages is the first step in becoming a competent web developer. They are essential whether you are developing a simple landing page or a complex e-commerce website.
2. Understanding of Front-End Frameworks
Frameworks speed up development time and ensure consistency in coding. For front-end development, aspiring developers should become familiar with:
React.js – A powerful JavaScript library for building user interfaces.
Vue.js – An adaptable framework that seamlessly integrates into projects.
Angular – A comprehensive front-end framework by Google.
Most modern websites developed by a Web Development Company in Oman are built using one or more of these frameworks, thanks to their scalability and performance.
3. Back-End Development Skills
While front-end development deals with user interfaces, back-end development powers the server side of a website. Essential back-end skills include:
Server-side languages like PHP, Python, Node.js, or Ruby.
Databases such as MySQL, MongoDB, and PostgreSQL.
Understanding RESTful APIs and how to integrate them.
Back-end development ensures that a website functions correctly, manages data, and provides a seamless experience to users.
4. Responsive Web Design
In a mobile-first world, ensuring your website works flawlessly on all devices is critical. Responsive design involves using flexible layouts, grids, and media queries to ensure a consistent user experience across desktops, tablets, and smartphones.
Knowledge of Bootstrap or Tailwind CSS can greatly assist in building responsive web applications. Any reputable Web Development Company in Oman will prioritise responsive design for all their projects.
5. Version Control Systems
Keeping track of code changes is vital, especially when collaborating with teams. Version control systems such as Git enable developers to:
Track and revert changes.
Collaborate efficiently.
Manage multiple versions of a project.
Platforms like GitHub or GitLab are widely used in the industry and are essential tools for modern web development.
6. Basic SEO Knowledge
Search Engine Optimization (SEO) isn't just for marketers. Web developers need to understand the basics of SEO to ensure the websites they build are search engine-friendly. This includes:
Optimising page load speed.
Proper use of header tags.
Clean and semantic HTML.
Mobile optimisation.
SEO-friendly websites rank better, attract more traffic, and are often the standard in projects undertaken by a Web Development Company in Oman.
7. Problem-Solving and Debugging Skills
No project is without challenges. Being able to troubleshoot, debug, and solve coding issues efficiently is a hallmark of a great developer. Familiarity with browser developer tools and debugging practices can save hours of frustration and ensure smoother development cycles.
8. Understanding Web Hosting and Deployment
Knowing how to take a website live is as important as building it. Web developers should understand:
How hosting services work.
Domain name system (DNS) settings.
FTP/SFTP protocols.
Deployment tools and Continuous Integration/Continuous Deployment (CI/CD) pipelines.
A Web Development Company in Oman often requires developers to handle deployment or assist in launching client websites.
9. Security Best Practices
Cybersecurity is a growing concern. Developers must adopt secure coding practices to protect websites from common vulnerabilities such as:
SQL injection.
Cross-site scripting (XSS).
Cross-site request forgery (CSRF).
Understanding HTTPS protocols, secure authentication, and data encryption is vital for any developer aiming to work in a professional environment.
10. Communication and Team Collaboration
Technical skills alone aren’t enough. Developers often work in teams and must interact with clients, designers, project managers, and other stakeholders. Strong communication skills can improve team productivity and ensure that the final product aligns with client expectations.
Why These Skills Matter in Oman’s Growing Tech Industry
As Oman continues to invest in digital infrastructure and smart technology, the need for professional web developers is on the rise. Businesses, government entities, and startups are all seeking reliable partners to help them build robust online platforms.
By mastering these essential skills, you not only enhance your employability but also position yourself to contribute meaningfully to a Web Development Company in Oman. Whether it's building user-friendly websites, optimising performance, or ensuring security, your skills can play a pivotal role in shaping the digital future of the Sultanate.
Final Thoughts
Web development is a continuously evolving field. To remain relevant, aspiring developers must commit to lifelong learning and staying updated with the latest technologies and industry best practices.
If you're looking to enter the workforce or join a Web Development Company in Oman, focus on mastering both the technical and soft skills outlined in this blog. With dedication, practice, and a passion for innovation, you can carve a successful career in web development right here in Oman.
0 notes
pentesttestingcorp · 20 days ago
Text
API Vulnerabilities in Symfony: Common Risks & Fixes
Symfony is one of the most robust PHP frameworks used by enterprises and developers to build scalable and secure web applications. However, like any powerful framework, it’s not immune to security issues—especially when it comes to APIs. In this blog, we’ll explore common API vulnerabilities in Symfony, show real coding examples, and explain how to secure them effectively.
Tumblr media
We'll also demonstrate how our Free Website Security Scanner helps identify these vulnerabilities before attackers do.
🚨 Common API Vulnerabilities in Symfony
Let’s dive into the key API vulnerabilities developers often overlook:
1. Improper Input Validation
Failure to sanitize input can lead to injection attacks.
❌ Vulnerable Code:
// src/Controller/ApiController.php public function getUser(Request $request) { $id = $request->query->get('id'); $user = $this->getDoctrine() ->getRepository(User::class) ->find("SELECT * FROM users WHERE id = $id"); return new JsonResponse($user); }
✅ Secure Code with Param Binding:
public function getUser(Request $request) { $id = (int)$request->query->get('id'); $user = $this->getDoctrine() ->getRepository(User::class) ->find($id); return new JsonResponse($user); }
Always validate and sanitize user input, especially IDs and query parameters.
2. Broken Authentication
APIs that don’t properly verify tokens or allow session hijacking are easy targets.
❌ Insecure Token Check:
if ($request->headers->get('Authorization') !== 'Bearer SECRET123') { throw new AccessDeniedHttpException('Unauthorized'); }
✅ Use Symfony’s Built-in Security:
# config/packages/security.yaml firewalls: api: pattern: ^/api/ stateless: true jwt: ~
Implement token validation using LexikJWTAuthenticationBundle to avoid manual and error-prone token checking.
3. Overexposed Data in JSON Responses
Sometimes API responses contain too much information, leading to data leakage.
❌ Unfiltered Response:
return $this->json($user); // Might include password hash or sensitive metadata
✅ Use Serialization Groups:
// src/Entity/User.php use Symfony\Component\Serializer\Annotation\Groups; class User { /** * @Groups("public") */ private $email; /** * @Groups("internal") */ private $password; } // In controller return $this->json($user, 200, [], ['groups' => 'public']);
Serialization groups help you filter sensitive fields based on context.
🛠️ How to Detect Symfony API Vulnerabilities for Free
📸 Screenshot of the Website Vulnerability Scanner tool homepage
Tumblr media
Screenshot of the free tools webpage where you can access security assessment tools.
Manual code audits are helpful but time-consuming. You can use our free Website Security Checker to automatically scan for common security flaws including:
Open API endpoints
Broken authentication
Injection flaws
Insecure HTTP headers
🔎 Try it now: https://free.pentesttesting.com/
📸 Screenshot of an actual vulnerability report generated using the tool to check Website Vulnerability
Tumblr media
An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
✅ Our Web App Penetration Testing Services
For production apps and high-value APIs, we recommend deep testing beyond automated scans.
Our professional Web App Penetration Testing Services at Pentest Testing Corp. include:
Business logic testing
OWASP API Top 10 analysis
Manual exploitation & proof-of-concept
Detailed PDF reports
💼 Learn more: https://www.pentesttesting.com/web-app-penetration-testing-services/
📚 More Articles from Pentest Testing Corp.
For in-depth cybersecurity tips and tutorials, check out our main blog:
🔗 https://www.pentesttesting.com/blog/
Recent articles:
Laravel API Security Best Practices
XSS Mitigation in React Apps
Threat Modeling for SaaS Platforms
📬 Stay Updated: Subscribe to Our Newsletter
Join cybersecurity enthusiasts and professionals who subscribe to our weekly threat updates, tools, and exclusive research:
🔔 Subscribe on LinkedIn: https://www.linkedin.com/build-relation/newsletter-follow?entityUrn=7327563980778995713
💬 Final Thoughts
Symfony is powerful, but with great power comes great responsibility. Developers must understand API security vulnerabilities and patch them proactively. Use automated tools like ours for Website Security check, adopt secure coding practices, and consider penetration testing for maximum protection.
Happy Coding—and stay safe out there!
1 note · View note
siddhiinfosoft5 · 2 months ago
Text
Future of PHP: What’s Coming in PHP 9? – Discuss upcoming features and trends in PHP development
Introduction
Despite numerous predictions about its decline, PHP continues to be a cornerstone of web development. From powering small personal blogs to massive social media platforms, PHP has proven its resilience and adaptability. With the upcoming release of PHP 9.0, developers are eager to explore the new features and improvements that will shape the future of PHP development Services.
While the official release date of PHP 9.0 remains unknown, community discussions and leaks provide insight into the major changes and enhancements expected. In this post, we will delve into the evolution of PHP, its key features, and why it remains an essential tool for developers worldwide. Additionally, we will discuss upcoming features and trends in PHP development, offering insights into the direction PHP is heading.
Evolution of PHP: A Brief Overview
PHP (Hypertext Preprocessor) has come a long way since its inception in 1994. Originally created as a simple scripting language for building dynamic web pages, PHP has evolved into a robust and powerful language that powers a significant portion of the internet.
PHP 5
Introduced object-oriented programming (OOP) features.
Implemented PDO (PHP Data Objects) for secure database interactions.
Improved exception handling and memory management.
PHP 7
Boosted performance with the Zend Engine 3.0.
Introduced scalar type declarations and return type hints.
Implemented null coalescing operator (??).
Improved error handling with Throwable exceptions.
PHP 8
Brought Just-In-Time (JIT) compilation for significant performance improvements.
Introduced Union Types, Match Expression, Named Arguments, and Attributes.
Implemented Constructor Property Promotion to reduce boilerplate code.
Now, with PHP 9 on the horizon, what can we expect?
Key Features of PHP 8 That Paved the Way for PHP 9
Before diving into PHP 9.0, let's briefly review some of the most impactful features introduced in PHP 8:
1) Just-In-Time (JIT) Compiler
Performance: JIT compilation allows code to be compiled at runtime, significantly improving execution speed for computationally intensive tasks.
Impact: While not drastically enhancing standard web applications, JIT opens doors for PHP’s use in fields like scientific computing and machine learning.
2) Union Types
Flexibility: Allows functions to accept multiple data types, enhancing type safety and robustness.
Example: function foo(int|float $number) { /* ... */ }
3) Attributes (Annotations)
Meta-programming: Introduces structured metadata for classes, methods, and properties.
Usage: Simplifies code annotation, improving integration with frameworks and tools.
4) Match Expression
Simplicity: Provides a more readable alternative to switch statements.
Example:
$result = match ($value) {
    1 => 'one',
    2 => 'two',
    default => 'other',
};
5) Constructor Property Promotion
Efficiency: Reduces boilerplate code for class property initialization.
Example:
class Point {
    public function __construct(private int $x, private int $y) {}
}
6) Nullsafe Operator
Error Handling: Reduces null checks, making code more concise.
Example: $country = $session?->user?->getAddress()?->country;
Anticipated Features in PHP 9
As PHP 9 is still under development, specific features may change. However, based on leaks and discussions, here are the expected improvements:
1) Removal of Deprecated Features
PHP 9.0 will eliminate features deprecated in PHP 8.1 - 8.4, streamlining the language and enhancing maintainability.
2) Transformation of Warnings to Errors
Warnings for undefined variables and properties will be converted into errors, demanding more precise coding practices.
3) Deprecated Dynamic Properties
Dynamic properties, deprecated in PHP 8.2, will now trigger ErrorException, enforcing structured coding practices.
4) New Random Extension
A new random number generator is being introduced, improving performance, security, and simplicity.
5) Standalone Types for null, true, and false
PHP 9.0 will recognize null, true, and false as standalone types, enhancing type precision.
6) Disjunctive Normal Form (DNF) Types
DNF types will enable complex combinations of union and intersection types, making PHP's type system more powerful.
7) Constants in Traits
PHP 9.0 will allow traits to define constants, expanding their capabilities for reusable code blocks.
8) Redact Sensitive Parameters in Backtraces
A crucial security improvement, this feature prevents sensitive data from being exposed in error backtraces.
9) Enhancements in Enum Property Fetching
PHP 9.0 will simplify the retrieval of enum properties in constant expressions, making enums more useful.
10) Additional Changes
Changes to return types in DateTime methods.
Deprecation of utf8_encode() and utf8_decode().
Locale-insensitive strtolower() and strtoupper().
Signature changes in SPL methods.
Introduction of "n" modifier in PCRE library.
Changes in ODBC username and password escaping.
Deprecation of ${} string interpolation.
Trends in PHP Development
1) Increased Use of Asynchronous Programming
PHP developers are exploring solutions like Swoole and ReactPHP to handle asynchronous tasks, improving performance in real-time applications.
2) Serverless PHP
With the rise of serverless computing, PHP is being adapted for FaaS (Functions as a Service) platforms, allowing developers to build scalable applications without managing infrastructure.
3) Enhanced Security Measures
PHP continues to implement stricter security protocols, focusing on data protection, encryption, and threat mitigation.
4) Microservices and API-First Development
Many PHP developers are shifting toward microservices and API-driven architectures, leveraging PHP frameworks like Laravel and Symfony to build efficient backend solutions.
The PHP Foundation's Role
The PHP Foundation plays a key role in guiding PHP's future, ensuring stability and funding core development. Their efforts, including initiatives like the Advisory Board and GitHub Sponsors, foster community engagement and ensure PHP's continued evolution.
Conclusion
PHP continues to evolve, adapting to modern web development needs while maintaining its flexibility. PHP 9.0 builds on the strong foundation of PHP 8, offering further performance improvements, enhanced asynchronous programming capabilities, a more robust type system, and better error handling.
While we await its official release, PHP 9.0 is shaping up to be a significant upgrade that will empower developers to build more efficient, secure, and scalable applications.
Stay tuned for more updates on PHP 9 and its impact on the web development landscape, as well as emerging trends shaping the future of PHP development.
Resource: What’s Coming in PHP 9? – Discuss upcoming features and trends in PHP development
0 notes
sailorsacademy13 · 3 months ago
Text
Sailors Academy in Ludhiana offers expert IT and digital marketing training courses. We provide hands-on learning in web development, SEO, social media marketing, graphic design, and more. Our experienced instructors equip students with industry-relevant skills, empowering them to excel in the fast-paced tech and marketing world. Join us today!
1 note · View note
fromdevcom · 5 months ago
Text
Looking for best Drupal theme? We have short listed some of the high quality themes for Drupal users. These premium drupal themes may help you create the best Drupal website at affordable price. The use of a existing premium Drupal theme eliminates a lot of efforts that goes in developing it. An already used theme can certainly help you focus your attention of long term goals for business. Some of these themes are very popular and used in thousands of websites, whereas others are good at specific domain. Drupal is an open source content management platform that is free to use by millions of webmasters and bloggers. There are many premium Drupal themes that are available that best fit your niches and specific business industry. Drupal is written in PHP and its highly extensible, that allows easy change of look and feel using different themes. The Drupal core module provides all features of a content management system. It also has a huge community support that has already contributed thousands of useful modules and themes. If you are a designer or a Drupal administrator, there are many Drupal themes that are available as options. To help you narrow down your numerous choices, here are some of the best Drupal themes for designers to choose from: Journal Crunch The theme comes with a front page that a single column layout and special rendering for sticky posts. You can also select to use two column layout and the images on your contents are supported with CSS. You can create an eye-catching website design using the Journal Crunch theme which is used for the Smashing Magazine website. It is an excellent theme to use for designers who want to maintain a magazine like a website to display their portfolio and to showcase their designs. It is a great theme option too for designers who want to have a news blog. Fontfolio This is a Drupal premium theme for designers and artists who want to showcase their creative design and artworks. The theme has full width or a liquid grid layout to display the category pages and the front page. It comes with a clean 2 column theme with a responsive layout. Users of the theme can have a wider reach to multi-language audiences owing to its multi-lingual feature that could translate the website according to the enabled languages by its users from the theme settings. Its view support feature allows you to use the theme's default grid style through UI viewing or unformatted list. Fontfolio is also optimized for socials with its social network icons that allow you to integrate your website to your Facebook, Google +, Dribble and Twitter accounts. Cenus This is a minimalist Drupal theme that allows every designer to smartly showcase their portfolio and projects. The theme is Jquery supported and provides unique templates to choose which would be best in displaying your projects. It comes with two themes in dark and light colors, comes with WYSIWYG editor, Pretty Photo gallery, and is SEO optimized. Trace This is a Drupal theme that comes with a responsive design and a 960 grid system. Designers can make use of this theme in creating websites that will showcase their designs portfolio and products. The theme is supported by CSS3 and HTML5. Users of the theme will be able to give their visitors an optimized viewing experience of their products and projects with easy reading and navigating process. It has 28 flexible regions and is integrated with a WYSIWYG editor and Superfish menu. You can select up to 2 sidebars when designing your Drupal website. Simple Corp This is an amazing Drupal theme that designers can use for their projects. It is optimized for mobile viewing and can make an interesting website with colorful theme options that come with more than 15 light and dark color schemes to choose from. You can customize the colors of your buttons as well. It has multiple theme setting options and the extra shortcodes to use for better customization of your website design. It has a Flexsider slideshow and JCarousel implementations.
It is also HTML5 and CSS3 supported. You can make unique image effects on your website too. Selecta Designers who aim to have their own video blogs should consider using this Drupal theme for their website. Optimized for video sharing, the theme has special and unique video options such as video pages, feed pages and featured videos using JavaScript implementation that you can disable anytime. It provides a comment form, contact form, and even use pictures for comments. You can display your brand logo, site name, slogan, and favicon. There are 11 regions that are available from the theme and a 2 column layout. Concept The theme is built in Twitter Bootstrap framework and comes with full Google font integration feature. It is with a responsive design and comes with a boxed and wide layout. It has 12 responsive grids and retina ready to give improved viewing experience to your visitors. It has an advanced typography setting and a powerful admin power to let you exercise wonderful customizations to your website. You can be as creative as you can through the available unlimited background colors, gradients, and patterns. It is optimized for SEO and provides a WYSIWYG editor support. It has a compressed CSS and JavaScript feature that will significantly improve the loading performance of your website. News Center This is a Drupal 7 premium theme which is excellent in promoting a designer's masterworks in the newspaper, news and magazine layout. It has a responsive layout and an easy installation process. It comes with a rich text format and supported with a WYSIWYG editor. A rating star is available to allow your viewers to rate your content or articles and offers a newsletter subscription option to your website visitors. It also comes with article sharing feature to more than 300 social media sites to give your website better visibility in the social media community. You can also enhance your URL and is SEO optimized. More available options from its settings are available such as 15 prebuilt views and sidebar advertisement features. Your visitors can also use a Gravatar when leaving comments to your site. Smooth This theme offers you 8 different theme color options. It has 16 or 12 column grids that automatically align to your block widths with CSS indenting feature for advanced block positioning of your grids. Its layout is highly fluid, allowing you to adjust the width of your layout freely for better customization. You can choose from a single to a couple of sidebars to use for your website that is adjustable with an automatic adjustment of your content width. It is integrated with Google fonts API. The theme has a Superfish dropdown menu for easy management of your menu. Extra graphics are also available for your favicons, Photoshop PSD files, logo and other stock images that you want to display on your website. TB Mollise If you have an eye for a Drupal theme that will give your website a professional and business-like presentation, this is a theme for you. It comes with a Superfish menu that makes configuring your website settings easier and with ease. It has quick tabs feature that allows you to make your desired customization of your site. Its clean design is perfect in making your website visitors to freely view your portfolio and design works. It has a flexible layout system that allows you to select the most appropriate layout width to showcase your work and brand. TB Sirate The theme allows its users to post contents with features of a book page, poll, blog, photostream, articles and forum topic. It is optimized for cross browsers like Chrome, Safari, Internet Explorer 7, Opera and Firefox. It is compliant with XHTML 1.0 transitional and CSS. The drop down feature of the Superfish menu gives you smoother navigating experience. It has quicktabs module, and modules supporting slideshow viewing, and gallery formatting for photo streaming. The theme will give your website a more professional look and a clean, lighter layout. You can easily launch the website more quickly because of its lighter weight codes.
Blocks Blocks is a metro-inspired Drupal 7 theme that comes with a responsive design. It has an advanced theme setting with a touch-ready slider. You can enjoy designing your website theme according to your preferences with its unlimited color settings. It has 16 available pattern selections and supported with advanced jQuery elements. There are also social media integration tabs including Twitter widgets. You can choose between a wide or boxed layout. Several custom sections are available including an image slider that allows you to highlight certain areas of your website that are important. Blocks support different major browsers and there are different image portfolio templates available for your website design. Splendio If you have an eye for an engaging website for your target visitors, this is one of the best Drupal themes that you can use. You can always spice up your blog using its unique and modern template designs. Its width is fixed at 980px with 1 or 2 columns for the theme layout. You can post thumbnail and integrate social media icons for Facebook and Twitter as well. The regions are collapsible and you can use the Google web fonts for font customization. It has good typography settings and the layout and design of the theme are optimized for a personal site, magazine style, and blog sites. It has detailed CSS features, form elements, comment forms, and node teaser. You can always configure the layout of your website including the sidebars. Converge A unique feature of this premium Drupal theme is the fancy slider that allows you to showcase immediately your work or portfolio to your visitors. There are 3 beautiful sliders to choose from and there are 1 to 3 column options for your layout design. The theme has an advanced feature of SKINR classes, theme block setting, and typography options. The blocks are also flexible and it is supported with Jquery animation menu. With the unlimited layout possibilities for your website, you can easily create the kind of feel that you want for your site to represent your brand. Proma This theme has a responsive design and with professional templates to use for your website design. It uses the latest CSS3 and HTML5 techniques with a great layer slider management system. You can also embed a video on the slide. The theme is SEO ready and uses the Google web fonts, with easy to customize features for tabs and commenting forms. There are 15 color variations available for the theme with 9 backgrounds to choose from. About the Author: The guest post is done by Stacy, technology and SEO writer, and blogger. She covers tech and seo news on many websites. She runs her own website: iflexion company where you can find out much useful info on how to use spy software for your mobile device. Updated On June 2019: Fixed Broken links and updated minor typos.
0 notes
tomatophp · 6 months ago
Text
Issues A list of issues from the repositories >>
(page 3 )
>> first / bug >
[Feature] Conflict with existing settings table
#6 opend 3 months ago in repository tomatophp/filament-pwa .
Update FilamentSubscriptionsPlugin.php
#12 opend 2 months ago in repository tomatophp/filament-subscriptions .
Problem On Migrations
#10 opend 3 months ago in repository tomatophp/filament-subscriptions .
[Bug] Subscriber error when the type of id not int
#8 opend 3 months ago in repository tomatophp/filament-subscriptions .
Unable to checkout
#8 opend 2 months ago in repository tomatophp/filament-pos .
Order Status Settings Error
#7 opend 2 months ago in repository tomatophp/filament-pos .
bug after clear install
#4 opend 3 months ago in repository tomatophp/filament-pos .
path(‘’) for both panels
#13 opend 2 months ago in repository tomatophp/filament-tenancy .
[Feature] Register Support
#5 opend 3 months ago in repository tomatophp/filament-tenancy .
Update StripeV3 driver to use default product name
#9 opend 2 months ago in repository tomatophp/filament-payments .
Tumblr media
1 note · View note
fernando-arciniega · 6 months ago
Text
Agregar un paginador y un buscador al Frontend - Del proyecto "Crea un carrito de compras con PHP, MySQL y Bootstrap"
Tumblr media
Para mejorar la funcionalidad del frontend, implementaremos dos características: - Un paginador que muestra 9 productos por página. - Un buscador que permite filtrar productos por nombre o descripción. Aquí te detallo los cambios realizados al código original para agregar las funcionalidades de paginación (9 productos por página) y el buscador, manteniendo el encabezado y el pie de página. Cambios realizados al código original 1. Incorporación de variables y lógica para la paginación - Nuevas variables: - $productos_por_pagina: Define cuántos productos se mostrarán por página (9 en este caso). - $pagina_actual: Obtiene el número de página desde la URL (GET). - $inicio: Calcula el índice inicial para la consulta SQL con LIMIT. - Consulta para contar productos: - Se agregó una consulta para contar el total de productos y calcular cuántas páginas serán necesarias. - Si hay una búsqueda activa, el conteo se ajusta para filtrar solo los productos que coinciden con la búsqueda. Código agregado: $productos_por_pagina = 9; $pagina_actual = isset($_GET) ? (int)$_GET : 1; if ($pagina_actual $inicio = ($pagina_actual - 1) * $productos_por_pagina; // Consulta para contar productos if (!empty($busqueda)) { $consulta_total = "SELECT COUNT(*) AS total FROM productos WHERE nombre LIKE '%$busqueda%' OR descripcion LIKE '%$busqueda%'"; } else { $consulta_total = "SELECT COUNT(*) AS total FROM productos"; } $total_productos = $conexion->query($consulta_total)->fetch_assoc(); $total_paginas = ceil($total_productos / $productos_por_pagina); 2. Modificación de la consulta de productos - Se añadió el uso de LIMIT para dividir los productos en páginas. - Si hay una búsqueda activa, se agregó un filtro en la consulta con WHERE nombre LIKE o descripcion LIKE. Código agregado/modificado: if (!empty($busqueda)) { $consulta = "SELECT * FROM productos WHERE nombre LIKE '%$busqueda%' OR descripcion LIKE '%$busqueda%' LIMIT $inicio, $productos_por_pagina"; } else { $consulta = "SELECT * FROM productos LIMIT $inicio, $productos_por_pagina"; } $resultado = $conexion->query($consulta); 3. Inclusión del formulario de búsqueda - Se añadió un formulario HTML en la parte superior del listado de productos, con un campo de texto y un botón para buscar productos. - El valor del campo de texto se conserva al recargar la página para mostrar el término de búsqueda. Código agregado: Read the full article
0 notes
mobappdevelopmentcompany · 7 months ago
Text
PHP Updates and their Impact on Web Development 
PHP, a widely acknowledged server-side scripting language is a great tool for web app development teams. As researched by the web technology survey portal W3 Techs, “75.9% of all websites are powered by PHP.” It’s interesting how PHP has undergone significant transformations since its inception to address the ever-growing needs of web development. What started as a tool for generating basic dynamic web pages has grown into a powerful language capable of supporting large-scale applications. So, let’s explore PHP’s evolution and the crucial updates so far. 
Major PHP Updates from inception till date 
Tumblr media
1. Early Versions (PHP/FI to PHP 3) 
PHP/FI (1995): The journey of PHP began when Rasmus Lerdorf created a simple set of CGI scripts with the basic feature of form handling. He named it as ‘Personal Home Page/Forms Interpreter (PHP/FI) and used it for tracking visits to his online resume.  
PHP 3 (1998): The real breakthrough came with PHP 3, when Andi Gutmans and Zeev Suraski rewrote the PHP core. PHP 3 introduced a more structured syntax and improved functionality, establishing PHP as a full-fledged scripting language for web application development. 
2. PHP 4 (2000) 
Zend Engine 1.0 (performance optimization and memory management)  
Output buffering and session handling 
Object-Oriented Programming (OOP) 
3. PHP 5 (2004) 
Zend Engine 2 (further performance improvements and extensibility of the language) 
Improved OOP Support features like better support for classes, methods, inheritance, interfaces, and constructors/destructors 
Exceptions (for error handling)  
PHP Data Objects (PDO) extension (for consistent interaction with databases) 
4. PHP 7 (2015) 
New Zend Engine 3 named PHP Next Generation (PHPNG): improved memory usage and made applications run much faster. 
Return Types and Scalar Type Declarations: type hinting (e.g., int, float, string, bool) and the ability to declare return types in functions: made the code more predictable and easier to debug. 
New syntax features: the null coalescing operator (??) and the spaceship operator (<=>): made the code more concise. 
Throwable interface for exceptions and errors: Improved issue detection and error handling 
5. PHP 8 (2020) 
PHP 8 is a crucial update as the features introduced are not just incremental improvements; they represent a new era for PHP that aligns it more closely with modern software development practices. Here’s an overview of all the PHP 8 versions.  
Tumblr media
PHP 8.0 (Released December 3, 2020) 
JIT (Just-In-Time) Compilation: expedites performance by compiling code into machine code at runtime. 
Union Types: Allows functions and methods to accept multiple types of values. 
Attributes (Annotations): Offers a new way to add metadata to classes, methods, and properties using a new syntax. 
Named Arguments: Call functions with arguments specified by their names, improving readability. 
Constructor Property Promotion: Combines constructor assignment and property declaration to minimize boilerplate code. 
Match Expression: A new match expression similar to switch but with safer comparisons and return values. 
Nullsafe Operator: The mechanism of “method chaining” on potentially null values; no explicit null checks required. 
Trailing Commas in Parameter Lists: Enables trailing commas in function and method parameter lists. 
PHP 8.1 (Released November 25, 2021) 
Enumerations (Enums): Introduces a native enum type for defining a set of possible values. 
Fibers: Allows for cooperative multitasking by providing a way to pause and resume functions. 
Readonly Properties: Properties that can only be written once and then become read-only. 
Enhances array unpacking to handle string keys. 
Intersection Types: Allows combining multiple types into one, requiring a value to satisfy all specified types. 
Internal optimizations, including JIT compiler improvements. 
PHP 8.2 (Released December 8, 2022) 
Read-only Properties: Expands the readonly feature from PHP 8.1 to allow class properties that can be assigned a value only once. 
Disjunctive Normal Form Types: Improves type system flexibility by allowing complex type expressions. 
New Fetch Style for PDO::FETCH_MODE: Adds a new fetch style for PDO that makes working with database results easier. 
Deprecations and Removals: Modifies or removes certain features and functions deprecated in earlier versions.  
Performance Enhancements: Includes various optimizations and bug fixes for improved performance. 
PHP 8.3: The Latest PHP Version (Released September 10, 2024) 
The latest stable release of PHP is PHP 8.3, which continues to enhance security, performance, and compatibility with modern technologies. Key improvements in this version include better error handling, optimized performance (e.g., reduced memory usage and faster response times), and enhanced compatibility with frameworks, libraries, and emerging technologies such as Progressive Web Apps (PWAs) and WebSockets​. PHP 8.3 also strengthens security by providing updates to protect apps from potential threats, making it essential for developers to stay updated. 
Top Highlights of PHP 8.3 at a Glance 
1. Readonly Classes 
PHP 8.3 introduces the ability to declare an entire class as readonly, meaning all properties in that class are implicitly readonly without the need to declare them individually. This simplifies the usage of immutable objects and enforces immutability across the class. 
readonly class MyImmutableClass { 
    public int $id; 
    public string $name; 
2. json_validate() Function 
A new json_validate() function is added to validate JSON strings without fully decoding them. This comes in handy when you need to check the structure or syntax of JSON data before you work with it. 
$isValid = json_validate('{"name": "John"}'); // returns true if valid 
3. null Return Types 
PHP 8.3 introduces null as an explicit return type, allowing developers to declare functions that can only return null. 
function myFunction(): null { 
    return null; 
4. Generator Improvements 
Generator::throw() now works as expected with Generator objects, allowing the throwing of exceptions into generators more consistently. This can be useful for error handling in asynchronous code or lazy evaluation scenarios. 
$generator = (function() { 
    try { 
        yield 1; 
    } catch (Exception $e) { 
        echo $e->getMessage(); 
    } 
})(); 
$generator->throw(new Exception("An error occurred")); 
5. New is_any() and is_none() Functions 
PHP 8.3 adds the is_any() and is_none() functions to make it easier to check multiple types or values in one go. 
$value = 'example'; 
if (is_any($value, 'string', 'integer')) { 
    // Do something 
if (is_none($value, 'array', 'object')) { 
    // Do something else 
6. Disjunctive Normal Form (DNF) Types 
Type unions can now be used in disjunctive normal form, improving flexibility when specifying complex return types or parameter types. 
function process(mixed $value): (int|float)|(string|bool) { 
    // Function logic 
Other Improvements 
Array Unpacking with String Keys: PHP 8.3 improves array unpacking by allowing the use of string keys; this was previously limited to integer-indexed arrays. 
New Functions: Various new built-in functions, such as str_truncate(), have been added to make string handling more flexible and performant. 
Performance Optimizations: There are further performance improvements, particularly in opcache and memory handling, continuing the performance gains seen in PHP 8.x series. 
PHP 8.4: Upcoming Update  
PHP 8.4, to be officially released on November 21, 2024; promises to bring valuable improvements and features, enhancing both performance and developer experience. Currently, it is undergoing the pre-release phase, transitioning through Alphas, Betas, and Release Candidates. 
Expected Features 
Property hooks RFC will make it easier to manage properties with less boilerplate code.  
The technique of “method chaining” without parentheses is a nice convenience  
JIT improvements should help with performance and memory usage 
The deprecation of implicit nullable types will encourage more explicit type declarations 
The new DOM HTML5 support is great for handling modern HTML content.  
How to Prepare for PHP 8.4? 
Testing: Ensure your codebase is compatible with the new version by testing in a staging environment. 
Updating Dependencies: Check and update any third-party libraries or frameworks to ensure compatibility with PHP 8.4. 
Review RFCs: Stay informed about new RFCs and feature additions to leverage the new capabilities effectively. 
Takeaway 
The evolution of PHP continues, and with each version, it becomes a stronger and more versatile tool in the developer's toolkit. If you haven’t upgraded yet, now is the time to explore what PHP 8 can do for your projects. Whether you're building small-scale applications powered by PHP or enterprise-level software, these updates will make your development process smoother and more efficient. 
0 notes
laurenreadsya · 8 months ago
Text
Script PHP Menampilkan Artikel Terkait
Apakah Anda sedang belajar membuat script CMS sendiri? Jika ya, rasanya belum lengkap deh tanpa fitur yang menampilkan daftar artikel yang terkait dengan sebuah artikel yang sedang dibaca oleh pengunjung blog. Dengan adanya fitur ini, pengunjung akan diarahkan ke artikel lain yang masih berhubungan dengan artikel yang sedang dibacanya sehingga bisa menambah wawasan lebih bagi mereka. Sedangkan efek positif bagi Anda sebagai pemilik situs adalah meningkatnya impression atau page view situs Anda, dan juga membuat visitor lebih tahan berlama-lama untuk menjelajahi situs Anda.
Apabila Anda menggunakan WordPress atau blogging software yang lain, maka fitur untuk menampilkian artikel terkait ini bisa langsung ditanam menggunakan plugin yang disediakan, misalnya YARPP. Namun, bagi Anda yang membuat CMS sendiri tentunya hal ini menjadi tantangan tersendiri. Oleh karena itu dalam artikel ini, saya akan mencoba memaparkan ide untuk membuat modul script yang menampilkan artikel terkait dengan PHP.
Misalkan kita mempunyai CMS dengan struktur tabel database untuk menyimpan data artikel seperti di bawah ini: CREATE TABLE `artikel` ( `id` int(11) AUTO_INCREMENT, `judul` varchar(100), `konten` text, `tanggal` date, PRIMARY KEY (`id`) );
dan andaikan kita sudah memiliki data artikel sbb:
https://web.archive.org/web/20231123143542im_/https://lh3-testonly.googleusercontent.com/blogger_img_proxy/ALY8t1uolFM_KTcIGadsDyfVT-Nqk4sIFcgxrKAWlFjJAsqyxHvnRZEH9_7zfRXNMZIURmoa4lYOX-1sQTswBeoovTbv66XA-vkv45YM8cUXycUJYm21npmQAl7QNlrbJLYcrdAm4R4NvPblf5GcXRg=s0-d
Selanjutnya, kita buat script untuk menampilkan detail isi artikelnya berdasarkan id artikel nya. artikel.php <?php // koneksi ke database mysql_connect('localhost', 'username', 'password'); mysql_select_db('database'); // membaca id artikel $idartikel = abs((int) $_GET['id']); // membaca data detail artikel berdasarkan id artikel $query = "SELECT * FROM artikel WHERE id = '$idartikel'"; $hasil = mysql_query($query); $data = mysql_fetch_array($hasil); ?> <html> <head> <title><?php echo $data['judul']?></title> </head> <body> <h1><?php echo $data['judul']?></h1> <small><em>Tanggal publikasi: <?php echo $data['tanggal']?></em></small> <div> <?php echo $data['konten']?> </div> <div> <h3>Artikel Terkait</h3> <?php include "function.php"; artikelTerkait($idartikel); ?> </div> </body> </html>
Script di atas digunakan untuk menampilkan konten dari sebuah artikel berdasarkan id artikelnya, dimana untuk menampilkan konten suatu artikel menggunakan URL http://namahost/artikel.php?id=… Perhatikan perintah $idartikel = abs((int) $_GET['id']);
perintah tersebut digunakan untuk mencegah SQL injection melalui GET method sebagaimana yang dulu pernah saya tulis artikelnya.
Jika kita perhatikan dari script di atas, maka di bawah isi artikelnya ada bagian sbb:<div> <h3>Artikel Terkait</h3> <?php include "function.php"; artikelTerkait($idartikel); ?> </div>
Selanjutnya kita tinjau apa isi dari function artikelTerkait(). Dalam contoh ini, keterkaitan artikel yang dimaksud di sini ditinjau dari kemiripan judul artikelnya. Adapun idenya adalah, kita baca semua judul
artikel yang ada dalam database kecuali artikel yang menjadi acuan (artikel ber ID $idartikel). Selanjutnya untuk semua judul artikel ini, kita lihat kemiripannya dengan judul dari artikel yang ber ID $idartikel ini. Kita bisa melihat kemiripan dari judul artikel ini menggunakan function similar_text() yang pernah saya bahas di artikel lain tentang uji kemiripan teks.
Kemudian, karena hasil dari penggunakan similar_text() ini berupa angka dalam bentuk prosentase kemiripan, maka sebaiknya kita membuat semacam batas minimal prosentase atau threshold, yang nantinya digunakan untuk memberi batas minimal kemiripannya. Sebagai contoh misalkan daftar artikel terkait yang ditampilkan hanya artikel yang memiliki tingkat kemiripan 50% ke atas. Hal ini berfungsi untuk memfilter mana artikel yang benar-benar mirip atau tidak. Artikel yang jauh dari mirip, akan memiliki prosentase kemiripan kecil. Tapi besar kecilnya threshold ini sepenuhnya terserah Anda, karena Andalah yang menentukan.
Hal yang menjadi pemikiran berikutnya adalah, bagaimana jika jumlah artikel yang terkait itu ada banyak, misalkan ada 100 buah? tentunya tidak mungkin kita tampilkan semua karena halaman page artikelnya bisa jadi penuh dengan judul-judul artikel sehingga tidak menarik bagi pengunjung. Oleh karena itu kita sebaiknya batasi jumlah artikel terkaitnya. Untuk mengimplementasikan hal ini, setiap judul artikel yang kemiripannya di atas threshold, maka kita simpan ke dalam sebuah array. Selama jumlah artikel dalam array tersebut belum memenuhi batas maksimum jumlah artikel nya, maka judul-judul terkait itu bisa ditambahkan dalam array. Setelah proses ini selesai, barulah kita tampilkan list judul artikel terkaitnya yang ada dalam array tersebut.
Nah… dari ide di atas, kita bisa membuat scriptnya sbb:
function.php <?php // koneksi ke database mysql_connect('localhost', 'username', 'password'); mysql_select_db('database'); function artikelTerkait($id) { // batas threshold 40% $threshold = 40; // jumlah maksimum artikel terkait yg ditampilkan 3 buah $maksArtikel = 3; // array yang nantinya diisi judul artikel terkait $listArtikel = Array(); // membaca judul artikel dari ID tertentu (ID artikel acuan) // judul ini nanti akan dicek kemiripannya dengan artikel yang lain $query = "SELECT judul FROM artikel WHERE id = '$id'"; $hasil = mysql_query($query); $data = mysql_fetch_array($hasil); $judul = $data['judul']; // membaca semua data artikel selain ID artikel acuan $query = "SELECT id, judul FROM artikel WHERE id <> '$id'"; $hasil = mysql_query($query); while ($data = mysql_fetch_array($hasil)) { // cek similaritas judul artikel acuan dengan judul artikel lainnya similar_text($judul, $data['judul'], $percent); if ($percent >= $threshold) { // jika prosentase kemiripan judul di atas threshold if (count($listArtikel) <= $maksArtikel) { // jika jumlah artikel belum sampai batas maksimum, tambahkan ke dalam array $listArtikel[] = "<li><a href='artikel.php?id=".$data['id']."'>".$data['judul']."</a></li>"; } } } // jika array listartikel tidak kosong, tampilkan listnya // jika kosong, maka tampilkan 'tidak ada artikel terkait' if (count($listArtikel) > 0) { echo "<ul>"; for ($i=0; $i<=count($listArtikel)-1; $i++) { echo $listArtikel[$i]; } echo "</ul>"; } else echo "<p>Tidak ada artikel terkait</p>"; } ?>
Mudah bukan membuatnya?
Nah… selanjutnya Anda bisa kembangkan sendiri script di atas, misalnya jika di dalam CMS Anda ada semacam kata kunci atau tag, maka artikel terkait bisa berdasarkan tag tersebut atau kategori artikel. Bisa juga, list artikel terkait yang muncul disorting dahulu dengan tingkat kemiripan paling tinggi terletak di urutan paling atas misalnya.
Selamat mencoba…
0 notes
om-kumar123 · 3 days ago
Text
PHP Array count() Function
The count( ) function is an inbuilt function of PHP, and it is used to count the elements of an array or the properties of an object. This function was introduced in PHP 4.0.
Syntax
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] );  
Tumblr media
0 notes
benefits1986 · 9 months ago
Text
it's a sigh-n
Int. Sasakyan. SLEX Stopover.
J: O, hindi na Taurus 'yan a. So, ano na? Anong petsa na?
A: Hindi nga e pero parang mas malala.
J: Anong mas malala? 'Di ba, ang dami mo ng naka-thing na ibang zodiac signs pero ano? Anong gusto mo? Gawa tayong bagong planeta para may bagong zodiac?
A: Aynakow. Gusto mo lang kasi parehas kayo ng sign. Hayup ka.
J: Alam mo 'yung karma?
A: TS ba 'yan?
J: Gago ka talaga noh. Ayan ka na naman.
A: E. Basta.
J: Isama na 'yan sa dream destination mo para matapos na. Dun sure akong 'di ka hihindi e.
A: Luh. Lekat pulikat ka. Gusto mo lang na may kalaro si X.
J: O 'di ba? Komplete na. Saka aminin mo na kasi. May something. Iba ka e.
A: ULOL. Mukha mo.
J: Pakita mo na 'yan para magkalapagan na. Ako pa mag-coach sa kanya para matapos na dahil 'pag ikaw kausap, wala e. Lagi na lang may red flag kahit wala naman dapat.
A: Pakialamero ka kasi talaga noh. Paladesisyon pa.
J: Huy. Thank you a.
A: Saan na naman?
J: Sa lahat.
A: Lekat. Ano na namang kailangan mo? Wala na. Ubos na.
J: Happy lang talaga ako.
A: Ah, 'yun ba? Oo naman. Maliit na bagay. Saka ang ending, ako ang nagwagi. PAK Q malala.
J: Ikaw naman ang laging tama e.
A: O bakit mali ba ako?
J: Sabi ko nga 'di ba? Happy ka na?
A: Hindi. Saks lang. Always.
J: Akalain mo nga naman 'di ba? 2024. Year of answered prayers at paramdam ng nanay mong dragon.
A: Hay. 'Yang dasal ko na 'yan, ang tagal na niyan. 2018 pa yata? Pero sabi ko, Jesssaasss, take the wheel, though 'di pa rin ako sumusuko. Nag-pivot na lang ako na okay naaaa, in your perfect time na lang, Lerd.
J: 'Di nga ako makatulog e. From muntik ma-ER dahil sa highblood ng malala, eto na kami ngayon. Saka sobrang sikip ng dibdib ko. Naiyak pa ako kasi naman, ang lala. Pero, masaya talaga ako kasi 'di ko expected na magiging ganito ang ending.
A: Alam mo, napaka arte mo talaga kasi noh.
J: Thank you sa lahat.
A: Ako na sagot ng gas pati toll.
J: Mura lang toll. Gas na lang. May S&R pa akong discount card.
A: Mura nga gas dito noh? Shemay. Mura na pala. Dati parang 70 php e. Hirap ng puro Grab lang e. Lels. Ikaw, pak na pak car.
J: Sus. Ayaw mo lang kasi mag-kotse dahil bobo kang mag-drive.
A: Troot.
J: Hindi nga kasi, push mo na 'yan. 'Pag 'yan nawala pa, ewan ko na talaga sa'yo. Pero 'di naman ako magugulat kasi super powers mo 'yan mag-no.
A: Gusto mo lang na may ka-double team ka sa akin.
J: Feeling ko magkakasundo kami niyan.
A: Wala akong pake. Magsama-sama kayo.
J: Naku. Iba na nga 'to. Iba ka e. Iba talaga. Girl na girl. Yes.
A: ULOL.
J: Magkaka-apo na ulit ang lahi nating palaki ng palaki.
A: Menopause na ako.
J: Walang maniniwala sa'yo. Awrahan mo pang-Gen Z. Lagot ka. Saka 'wag ka maniniwala diyan sa anak-anak na puwedeng wala. Lagot ka diyan. Butas condom gaming real quick. 'Di ka naman kasi nalalasing so, wala ng ibang paraan.
A: Kadire. Gago. Sinsabi mo lang 'yan kasi akala mo baog ka na. Sinagad mo masyado sa maling pag-shoot. Hayup ka. 'Wag mo akong idamay sa mga shit mo sa buhay. Nanahimik ako dito.
J: Overthink pa more. Sige pa.
A: Gusto mong patagasin ko gas mo saka butasin ko bumbunan mo?
0 notes
pentesttestingcorp · 2 months ago
Text
Fix Insecure Direct Object References (IDOR) in Symfony
🚨 What is Insecure Direct Object References (IDOR)?
Insecure Direct Object References (IDOR) occur when an application exposes references to internal objects such as database records or files, and these references can be manipulated by an attacker to gain unauthorized access.
Tumblr media
Symfony applications, like many modern frameworks, are vulnerable to IDOR when proper access controls are not enforced at the object level.
🧠 Why is IDOR Dangerous in Symfony?
Symfony relies on route parameters and object injection to retrieve resources. If these resources (e.g., /user/{id} or /invoice/{id}) are not protected with appropriate permission checks, attackers can:
View other users’ data
Modify sensitive records
Access private files
💥 Real-World Example of IDOR in Symfony
Let’s say your Symfony app has the following route:
// src/Controller/UserController.php #[Route('/user/{id}', name: 'user_profile')] public function profile(int $id, UserRepository $userRepository): Response { $user = $userRepository->find($id); return $this->render('user/profile.html.twig', [ 'user' => $user ]); }
If there’s no check to verify that the authenticated user is requesting their own data, anyone can access any profile like:
GET /user/1 GET /user/2
This is a textbook IDOR vulnerability.
🛡️ Fixing IDOR in Symfony (Best Practices)
✅ 1. Check Object Ownership
public function profile(int $id, UserRepository $userRepository, Security $security): Response { $user = $userRepository->find($id); if ($user !== $security->getUser()) { throw $this->createAccessDeniedException('Unauthorized access!'); } return $this->render('user/profile.html.twig', ['user' => $user]); }
✅ 2. Use Voters for Fine-Grained Access Control
// src/Security/UserVoter.php public function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool { $currentUser = $token->getUser(); if (!$currentUser instanceof UserInterface) { return false; } /** @var User $subject */ switch ($attribute) { case 'VIEW': return $currentUser === $subject; } return false; }
Then in the controller:
$this->denyAccessUnlessGranted('VIEW', $user);
This decouples access logic from controllers and is much easier to manage.
💡 Coding Example: IDOR in Symfony File Access
// DownloadController.php #[Route('/download/{filename}', name: 'file_download')] public function download(string $filename, Security $security): Response { $user = $security->getUser(); $filePath = '/uploads/' . $user->getId() . '/' . $filename; if (!file_exists($filePath)) { throw $this->createNotFoundException('File not found.'); } return $this->file($filePath); }
This prevents attackers from downloading files outside their own directory.
🛠️ Test for IDOR Automatically
You can easily test your Symfony application for IDOR and other critical vulnerabilities using our Website Vulnerability Scanner.
Tumblr media
Above: Free Website Vulnerability Scanner Homepage
Once your scan is completed, you’ll receive a detailed report with all detected vulnerabilities to check Website Vulnerability, including IDOR.
Tumblr media
Above: Vulnerability Report Generated by Our Free Tool
🔗 More Security Tips on Symfony
Explore more Symfony security topics like XSSI, CSRF, and Session Replay Attacks on our main blog at 👉 Pentest Testing Corp.
📌 Summary
IDOR is a critical access control issue where users can access data not meant for them.
Always verify ownership before returning resources.
Use Symfony voters for clean, secure access decisions.
Regularly run vulnerability scans using tools like our Free Website Vulnerability Scanner online.
🔁 Share and Secure!
Found this useful? Share it with other Symfony developers or security teams. Let’s build safer web apps together!
#Symfony #WebSecurity #Pentesting #IDOR #Cybersecurity #PHP #SymfonySecurity
1 note · View note