#php json encode example
Explore tagged Tumblr posts
fromdevcom · 1 month ago
Text
Decoding Data in PHP: The Ultimate Guide to Reading File Stream Data to String in 2025 Reading file content into a string is one of the most common tasks in PHP development. Whether you're parsing configuration files like JSON or INI, processing uploaded documents, or consuming data from streams and APIs, being able to efficiently and correctly read file data into a string is essential. With PHP 8.x, developers have access to mature, robust file handling functions, but choosing the right one—and understanding how to handle character encoding, memory efficiency, and errors—is key to writing performant and reliable code. In this comprehensive guide, we’ll walk through the best ways to read file stream data into a string in PHP as of 2025, complete with modern practices, working code, and real-world insights. Why Read File Stream Data to String in PHP? There are many scenarios in PHP applications where you need to convert a file's contents into a string: Parsing Configuration Files: Formats like JSON, INI, and YAML are typically read as strings before being parsed into arrays or objects. Reading Text Documents: Applications often need to display or analyze user-uploaded documents. Processing Network Streams: APIs or socket streams may provide data that needs to be read and handled as strings. General File Processing: Logging, data import/export, and command-line tools often require reading file data as text. Methods for Reading and Converting File Stream Data to String in PHP 1. Using file_get_contents() This is the simplest and most widely used method to read an entire file into a string. ✅ How it works: It takes a filename (or URL) and returns the file content as a string. 📄 Code Example: phpCopyEdit 📌 Pros: Very concise. Ideal for small to medium-sized files. ⚠️ Cons: Loads the entire file into memory—can be problematic with large files. Error handling must be explicitly added (@ or try/catch via wrappers). 2. Using fread() with fopen() This method provides more control, allowing you to read file contents in chunks or all at once. 📄 Code Example: phpCopyEdit 📌 Pros: Greater control over how much data is read. Better for handling large files in chunks. ⚠️ Cons: Requires manual file handling. filesize() may not be reliable for network streams or special files. 3. Reading Line-by-Line Using fgets() Useful when you want to process large files without loading them entirely into memory. 📄 Code Example: phpCopyEdit 📌 Pros: Memory-efficient. Great for log processing or large data files. ⚠️ Cons: Slower than reading in one go. More code required to build the final string. 4. Using stream_get_contents() Works well with generic stream resources (e.g., file streams, network connections). 📄 Code Example: phpCopyEdit 📌 Pros: Works with open file or network streams. Less verbose than fread() in some contexts. ⚠️ Cons: Still reads entire file into memory. Not ideal for very large data sets. 5. Reading Binary Data as a String To read raw binary data, use binary mode 'rb' and understand the data's encoding. 📄 Code Example: phpCopyEdit 📌 Pros: Necessary for binary/text hybrids. Ensures data integrity with explicit encoding. ⚠️ Cons: You must know the original encoding. Risk of misinterpreting binary data as text. Handling Character Encoding in PHP Handling character encoding properly is crucial when working with file data, especially in multilingual or international applications. 🔧 Best Practices: Use UTF-8 wherever possible—it is the most compatible encoding. Check the encoding of files before reading using tools like file or mb_detect_encoding(). Use mb_convert_encoding() to convert encodings explicitly: phpCopyEdit$content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1'); Set default encoding in php.ini:
iniCopyEditdefault_charset = "UTF-8" Be cautious when outputting string data to browsers or databases—set correct headers (Content-Type: text/html; charset=UTF-8). Error Handling in PHP File Operations Proper error handling ensures your application fails gracefully. ✅ Tips: Always check return values (fopen(), fread(), file_get_contents()). Use try...catch blocks if using stream wrappers that support exceptions. Log or report errors clearly for debugging. 📄 Basic Error Check Example: phpCopyEdit Best Practices for Reading File Stream Data to String in PHP ✅ Use file_get_contents() for small files and quick reads. ✅ Use fread()/fgets() for large files or when you need precise control. ✅ Close file handles with fclose() to free system resources. ✅ Check and convert character encoding as needed. ✅ Implement error handling using conditionals or exceptions. ✅ Avoid reading huge files all at once—use chunked or line-by-line methods. ✅ Use streams for remote sources (e.g., php://input, php://memory). Conclusion Reading file stream data into a string is a foundational PHP skill that underpins many applications—from file processing to configuration management and beyond. PHP 8.x offers a robust set of functions to handle this task with flexibility and precision. Whether you’re using file_get_contents() for quick reads, fgets() for memory-efficient processing, or stream_get_contents() for stream-based applications, the key is understanding the trade-offs and ensuring proper character encoding and error handling. Mastering these techniques will help you write cleaner, safer, and more efficient PHP code—an essential skill for every modern PHP developer. 📘 External Resources: PHP: file_get_contents() - Manual PHP: fread() - Manual PHP: stream_get_contents() - Manual
0 notes
shalcool15 · 1 year ago
Text
Creating a Simple REST API with PHP: A Beginner's Guide
In the digital era, REST APIs have become the backbone of web and mobile applications, facilitating seamless communication between different software systems. PHP, with its simplicity and wide adoption, is a powerful tool for building robust REST APIs. This guide aims to introduce beginners to the fundamentals of creating a simple REST API using PHP.
Understanding REST APIs
Before diving into the technicalities, it's essential to understand what REST APIs are. REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server, cacheable communications protocol -- typically HTTP. In simpler terms, REST uses HTTP requests to GET, PUT, POST, and DELETE data.
Setting Up Your Environment
To start building your REST API with PHP, you'll need a local server environment like XAMPP, WAMP, or MAMP. These software packages provide the necessary tools (Apache, MySQL, and PHP) to develop and test your API locally. Once installed, start the Apache server to run your PHP scripts.
Planning Your API
Before coding, plan what resources your API will provide access to and the corresponding endpoints. For example, if you're building an API for a blog, resources might include articles, authors, and comments. An endpoint for retrieving articles could be structured as http://yourdomain.com/api/articles.
Creating the API
1. Setting Up a Project Structure
Create a new directory in your server's root folder (e.g., htdocs in XAMPP) named my_api. Inside this directory, create two files: .htaccess and index.php. The .htaccess file will be used for URL rewriting, making your API endpoints clean and user-friendly.
.htaccess
apacheCopy code
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([a-zA-Z0-9-]+)/?$ index.php?request=$1 [QSA,NC,L]
This configuration redirects all requests to index.php, passing the request path as a query parameter.
2. Implementing the API Logic
index.php
Start by initializing an array to mock a database of articles. Then, parse the request to determine which resource is being accessed.
phpCopy code
<?php // Mock database of articles $articles = [ ['id' => 1, 'title' => 'The First Article', 'content' => 'This is the first article.'], ['id' => 2, 'title' => 'The Second Article', 'content' => 'This is the second article.'] ]; // Get the request path $request = $_GET['request'] ?? ''; // Split the path into components $requestParts = explode('/', $request); // Determine the resource $resource = $requestParts[0] ?? ''; header('Content-Type: application/json'); switch ($resource) { case 'articles': echo json_encode($articles); break; default: http_response_code(404); echo json_encode(['error' => 'Resource not found']); break; }
This script checks the requested resource and returns a JSON-encoded list of articles if the articles resource is accessed. For any other resource, it returns a 404 error with a JSON error message.
3. Testing Your API
To test your API, you can use tools like Postman or simply your browser. For instance, navigating to http://localhost/my_api/articles should display the JSON-encoded articles.
Extending Your API
Once you've mastered the basics, you can extend your API by implementing additional HTTP methods (POST, PUT, DELETE) and adding authentication for secure access. This might involve more advanced PHP programming, including working with headers for content type and authentication tokens, and dealing with more complex routing and database interactions.
Best Practices
When developing your API, keep in mind best practices such as:
Security: Implement measures like authentication, input validation, and sanitization to protect your API.
Versioning: Version your API from the start (e.g., v1/articles) to avoid breaking changes for users as your API evolves.
Documentation: Provide clear, concise documentation for your API's endpoints, request parameters, and response objects.
Embracing PHP's Flexibility for Rapid Development
One of the unique aspects of creating a REST API with PHP is leveraging PHP's inherent flexibility and simplicity for rapid development. As a dynamically typed language, PHP allows developers to iterate quickly without the strict type constraints found in statically typed languages. This flexibility is particularly beneficial in the early stages of API development, where the data model and business logic might frequently change. Furthermore, PHP's extensive standard library and numerous frameworks can significantly speed up the development process. For instance, using a PHP framework like Laravel or Symfony can provide out-of-the-box solutions for routing, security, and ORM (Object-Relational Mapping), enabling developers to focus on the unique aspects of their application rather than boilerplate code. To streamline projects with experts, businesses look for top php development companies and avail their services to implement better development strategies.
The Power of PHP's Community and Resources
Another unique advantage of building REST APIs with PHP is the extensive community support and wealth of resources available. PHP is one of the most widely used programming languages for web development, with a vibrant community that contributes to a vast ecosystem of libraries, frameworks, and tools. This community support means developers can often find solutions to common problems and questions through forums, blogs, and tutorials. Additionally, the availability of comprehensive documentation and best practices makes it easier for businesses to avail PHP development services to delve deeper into advanced topics. The combination of PHP's ease of use and the support of its community makes it an excellent choice for developing REST APIs, providing both beginners and seasoned developers with the resources they need to succeed.
Conclusion
Building a REST API with PHP is a rewarding project that can enhance your web development skills. Following this guide, you've taken the first step towards creating your API, understanding its foundational concepts, and applying best practices. As want to incorporate more features, refine code, and explore the vast possibilities of RESTful services, the natural choice for them is to hire php developers by outsourcing.
Remember, the key to mastering API development is practice and continuous learning. Experiment with different scenarios, contribute to open-source projects, and stay updated with the latest trends in web development. Your journey as an API developer is just beginning, and the digital world eagerly awaits your contributions.
0 notes
this-week-in-rust · 2 years ago
Text
This Week in Rust 476
Hello and welcome to another issue of This Week in Rust! Rust is a programming language empowering everyone to build reliable and efficient software. This is a weekly summary of its progress and community. Want something mentioned? Tag us at @ThisWeekInRust on Twitter or @ThisWeekinRust on mastodon.social, or send us a pull request. Want to get involved? We love contributions.
This Week in Rust is openly developed on GitHub. If you find any errors in this week's issue, please submit a PR.
Updates from Rust Community
Foundation
A Q4 Recap & 2022 Reflection from Rebecca Rumbul
Project/Tooling Updates
rust-analyzer changelog #162
fltk-rs in 2022
shuttle - Release v0.8.0
This Week in Fyrox
gitoxide - The year in retrospective, and what's to come
The AeroRust community - 3 years birthday (and the roadmap for 2023)
SeaQuery 0.28.0 - A dynamic query builder for SeaORM
Databend 2022 Recap
Observations/Thoughts
State Machines III: Type States
Rust — vim — code completion
How to Test
Embedded Rust and Embassy: DMA Controllers
Parsing TFTP in Rust
Rustdoc JSON in 2022
From PHP to Rust: Migrating a REST API between these two languages. (Part I)
React + Rust + Wasm: Play an Animated 3D Model
Open Source Grindset Explained (with a Rust example)
Rust Walkthroughs
Building a Simple DB in Rust - Part 1
Microservices with Rust and WASM using Fermyon
Compiling Brainfuck code - Part 4: A Static Compiler
Rusty Circuit Breaker 🦀
Zero-dependency random number generation in Rust
Miscellaneous
Rust 101: an open-source university course
[video] If Rust Compiles, It WORKS (Testing not needed 📚)
[video] Introduction to Axum
[video] Ergonomic APIs for hard problems - Raph Levien
Crate of the Week
This week's crate is Sniffnet, a cross-platform GUI application to analyze your network traffic.
Thanks to Gyuly Vgc for the suggestion!
Please submit your suggestions and votes for next week!
Call for Participation
Always wanted to contribute to open-source projects but did not know where to start? Every week we highlight some tasks from the Rust community for you to pick and get started!
No calls for participation this week. Keep an eye out for more places to contribute next week!
If you are a Rust project owner and are looking for contributors, please submit tasks here.
Updates from the Rust Project
291 pull requests were merged in the last week
CFI: monomorphize transparent ADTs before typeid
account for match expr in single line
account for macros in const generics
account for multiple multiline spans with empty padding
adjust message on non-unwinding panic
allow trait method paths to satisfy const Fn bounds
always suggest as MachineApplicable in recover_intersection_pat
detect diff markers in the parser
detect when method call on LHS might be shadowed
dont use --merge-base during bootstrap formatting subcommand
emit fewer errors on invalid #[repr(transparent)] on enum
encode spans relative to the enclosing item -- enable on nightly
error parsing lifetime following by Sized and message + between them
fix confusing diagnostic when attempting to implementing trait for tuple
format only modified files
on unsized locals with explicit types suggest &
only deduplicate stack traces for good path bugs
give the correct track-caller location with MIR inlining
implement allow-by-default multiple_supertrait_upcastable lint
improve heuristics whether format_args string is a source literal
make trait/impl where clause mismatch on region error a bit more actionable
merge multiple mutable borrows of immutable binding errors
partially fix explicit_outlives_requirements lint in macros
properly calculate best failure in macro matching
provide a better error and a suggestion for Fn traits with lifetime params
provide local extern function arg names
recover fn keyword as Fn trait in bounds
remove unreasonable help message for auto trait
silence knock-down errors on [type error] bindings
suggest Pin::as_mut when encountering borrow error
suggest impl Iterator when possible for _ return type
suggest rewriting a malformed hex literal if we expect a float
suppress errors due to TypeError not coercing with inference variables
trim more paths in obligation types
miri: cargo-miri: use rustc to determine the output filename
miri: handle unknown targets more gracefully
miri: simplify path joining code a bit
miri: support using a JSON target file
miri: tweaks to retag diagnostic handling
use some more const_eval_select in pointer methods for compile times
more inference-friendly API for lazy
more verbose Debug implementation of std::process:Command
add #[inline] markers to once_cell methods
unify id-based thread parking implementations
available_parallelism:gracefully handle zero value cfs_period_us
catch panics/unwinding in destruction of thread-locals
cargo: asymmetric tokens
cargo: reasons for rebuilding
clippy: fix false negative in needless_return
clippy: fix match_single_binding suggestion introducing an extra semicolon
clippy: move mutex_atomic to restriction
rust-analyzer: derive Hash
rust-analyzer: enum variant discriminants hints
rust-analyzer: diagnose private assoc item accesses
rust-analyzer: diagnose private field accesses
rust-analyzer: implement yeeting
rust-analyzer: fall back to inaccessible associated functions and constants if no visible resolutions are found
rust-analyzer: improve exit point highlighting for for and while loops in tail position
rust-analyzer: merge multiple intersecting ranges
rust-analyzer: prefix prelude items whose name collides in current scope
rust-analyzer: type check unstable try{} blocks
rust-analyzer: support multi-character punct tokens in MBE
rust-analyzer: write down adjustments introduced by binary operators
Rust Compiler Performance Triage
Fairly busy week with some massive performance improvements at the expense of some significant albeit smaller regressions. The main wins came in a long-standing PR from @cjgillot to enable encoding spans in metadata relative to their enclosing item. This causes more work in full compilation which causes some regressions up to 5% but can lead to very large wins in incremental compilation scenarios (up to ~70%). For example, the clap crate compiles 68% faster after a small 1 line change than it did previously.
Triage done by @rylev. Revision range: b38a6d..b43596
Summary:
(instructions:u) mean range count Regressions ❌ (primary) 1.6% [0.3%, 4.6%] 97 Regressions ❌ (secondary) 1.8% [0.2%, 7.6%] 60 Improvements ✅ (primary) -9.7% [-68.7%, -0.2%] 53 Improvements ✅ (secondary) -1.7% [-15.3%, -0.1%] 62 All ❌✅ (primary) -2.4% [-68.7%, 4.6%] 150
1 Regressions, 1 Improvements, 4 Mixed; 1 of them in rollups 47 artifact comparisons made in total
Full report here
Approved RFCs
Changes to Rust follow the Rust RFC (request for comments) process. These are the RFCs that were approved for implementation this week:
No RFCs were approved this week.
Final Comment Period
Every week, the team announces the 'final comment period' for RFCs and key PRs which are reaching a decision. Express your opinions now.
RFCs
No RFCs entered Final Comment Period this week.
Tracking Issues & PRs
[disposition: merge] Only include stable lints in rustdoc::all group
[disposition: merge] Don't derive Debug for OnceWith & RepeatWith
[disposition: merge] PhantomData layout guarantees
[disposition: merge] Add O(1) Vec -> VecDeque conversion guarantee
[disposition: merge] Stabilize ::{core,std}::pin::pin!
[disposition: merge] Stabilize main_separator_str
[disposition: merge] Loosen the bound on the Debug implementation of Weak.
New and Updated RFCs
No New or Updated RFCs were created this week.
Call for Testing
An important step for RFC implementation is for people to experiment with the implementation and give feedback, especially before stabilization. The following RFCs would benefit from user testing before moving forward:
No RFCs issued a call for testing this week.
If you are a feature implementer and would like your RFC to appear on the above list, add the new call-for-testing label to your RFC along with a comment providing testing instructions and/or guidance on which aspect(s) of the feature need testing.
Upcoming Events
Rusty Events between 2023-01-04 - 2023-02-01 🦀
Virtual
2023-01-04 | Virtual (Indianapolis, IN, US) | Indy Rust
Indy.rs - with Social Distancing
2023-01-04 | Virtual (Stuttgart, DE) | Rust Community Stuttgart
Rust-Meetup
2023-01-05 | Virtual (Charlottesville, VA, US) | Charlottesville Rust Meetup
Part 2: Exploring USB with Rust
2023-01-10 | Virtual (Dallas, TX, US) | Dallas Rust
Second Tuesday
2023-01-11 | Virtual (Boulder, CO, US) | Boulder Elixir and Rust
Monthly Meetup
2023-01-12 | Virtual (San Francisco, CA, US; Stockholm, SE; New York, NY US) | Microsoft Reactor San Francisco | Microsoft Reactor New York
Crack code interview problems in Rust - Ep. 1 | Stockholm Mirror | New York Mirror
2023-01-12 | Virtual (Nürnberg, DE) | Rust Nuremberg
Rust Nürnberg online
2023-01-14 | Virtual | Rust GameDev
Rust GameDev Monthly Meetup
2023-01-16 | Virtual (San Francisco, CA, US; São Paulo, BR; New York, NY, US) | Microsoft Reactor San Francisco and Microsoft Reactor São Paulo and Microsoft Reactor New York
Primeros pasos con Rust - Qué es y Configuración el entorno de desarrollo | São Paulo Mirror | New York Mirror
2023-01-17 | Virtual (Berlin, DE) | OpenTechSchool Berlin
Rust Hack and Learn
2023-01-17 | Virtual (San Francisco, CA, US; São Paulo, BR, New York, NY, US) | Microsoft Reactor San Francisco and Microsoft Reactor São Paulo and Microsoft Reactor New York
Primeros pasos con Rust - Creación del primer programa de Rust | *São Paulo Mirror | New York Mirror
2023-01-17 | Virtual (Washington, DC, US) | Rust DC
Mid-month Rustful
2023-01-18 | Virtual (San Francisco, CA, US; São Paulo, BR; New York, NY US) | Microsoft Reactor San Francisco and Microsoft Reactor São Paulo and Microsoft Reactor New York
Primeros pasos con Rust: QA y horas de comunidad | Sao Paulo Mirror | New York Mirror
2023-01-18 | Virtual (Vancouver, BC, CA) | Vancouver Rust
Rust Study/Hack/Hang-out
2023-01-26 | Virtual (Charlottesville, VA, US) | Charlottesville Rust Meetup
Rust Lightning Talks!
2023-01-31 | Virtual (Dallas, TX, US) | Dallas Rust
Last Tuesday
2023-02-01 | Virtual (Indianapolis, IN, US) | Indy Rust
Indy.rs - with Social Distancing
Asia
2023-01-15 | Tokyo, JP | Tokyo Rust Meetup
Property-Based Testing in Rust
Europe
2023-01-12 | Enschede, NL | Dutch Rust Meetup
Rust Meetup - Subject TBA
2023-01-20 | Stuttgart, DE | Rust Community Stuttgart
OnSite Meeting
2023-01-25 | Paris, FR | Rust Paris
Rust Paris meetup #55
North America
2023-01-05 | Lehi, UT, US | Utah Rust
Lightning Talks 'n' Chill (a.k.a. Show & Tell), with Pizza!
2023-01-09 | Minneapolis, MN, US | Minneapolis Rust Meetup
Happy Hour and Beginner Embedded Rust Hacking Session (#2!)
2023-01-11 | Austin, TX, US | Rust ATX
Rust Lunch
2023-01-17 | San Francisco, CA, US | San Francisco Rust Study Group
Rust Hacking in Person
2023-01-26 | Copenhagen, DK | Copenhagen Rust group
Rust Hack Night #32
2023-01-26 | Lehi, UT, US | Utah Rust
Building a Rust Playground with WASM and Lane and Food!
If you are running a Rust event please add it to the calendar to get it mentioned here. Please remember to add a link to the event too. Email the Rust Community Team for access.
Jobs
Please see the latest Who's Hiring thread on r/rust
Quote of the Week
You haven’t “fooled” rustc, you are using unsafe code. Unsafe code means that all you can do is fool yourself.
– Frank Steffahn on rust-users
Thanks to Quine Dot for the suggestion!
Please submit quotes and vote for next week!
This Week in Rust is edited by: nellshamrell, llogiq, cdmistman, ericseppanen, extrawurst, andrewpollack, U007D, kolharsam, joelmarcey, mariannegoldin, bennyvasquez.
Email list hosting is sponsored by The Rust Foundation
Discuss on r/rust
0 notes
airman7com · 5 years ago
Text
PHP json encode - Konversi Array Ke JSON, Objek Ke JSON
PHP json encode – Konversi Array Ke JSON, Objek Ke JSON
Fungsi fungsi PHP json_encode () digunakan untuk mengubah array atau objek PHP menjadi JSON. PHP memiliki beberapa fungsi pre-built untuk menangani JSON.
Dalam tutorial ini, kita akan belajar bagaimana mengkonversi objek PHP ke JSON, mengkonversi PHP String ke JSON, PHP Array To JSON, mendapatkan data dari array JSON di php convert Multidimensional PHP Array ke JSON dengan definisi, sintaksis,…
View On WordPress
0 notes
sanesquaregg · 2 years ago
Text
What exactly is GraphQL?
GraphQL is a new API standard was invented and developed by Facebook. GraphQL is intended to improve the responsiveness, adaptability, and developer friendliness of APIs. It was created to optimize RESTful API calls and offers a more flexible, robust, and efficient alternative to REST. It is an open-source server-side technology that is now maintained by a large global community of companies and individuals. It is also an execution engine that acts as a data query language, allowing you to fetch and update data declaratively. GraphQL makes it possible to transfer data from the server to the client. It allows programmers to specify the types of requests they want to make.
GraphQL servers are available in a variety of languages, including Java, Python, C#, PHP, and others. As a result, it is compatible with any programming language and framework.
For a better understanding, the client-server architecture of GraphQL is depicted above
No JSON is used to write the GraphQL query. A GraphQL query is transmitted as a string to the server then when a client sends a 'POST' request to do so.
The query string is received by the server and extracted. The server then processes and verifies the GraphQL query in accordance with the graph data model and GraphQL syntax (GraphQL schema).
The GraphQL API server receives the data requested by the client by making calls to a database or other services, much like the other API servers do.
The data is then taken by the server and returned to the client as a JSON object.
Here are some major GraphQL characteristics:
Declarative query language, not imperative, is offered.
It is hierarchical and focused on the product.
GraphQL has excellent type checking. It denotes that inquiries are carried out inside the framework of a specific system.
GraphQL queries are encoded in the client rather than the server.
It has all the attributes of the OSI model's application layer.
GraphQL has three essential parts:
Query
Resolver
Schema
1. Query: The client machine application submitted the Query as an API request. It can point to arrays and support augments. To read or fetch values, use a query. There are two key components to a query:
a) Field: A field merely signifies that we are requesting a specific piece of information from the server. The field in a graphQL query is demonstrated in the example below. query { employee { empId ename } } "data": { "employee”: [ { "empId": 1, "ename": "Ashok" }, { "id": "2", "firstName": "Fred" } …] } }
In the above In the GraphQL example above, we query the server for the employee field along with its subfields, empId and ename. The data we requested is returned by the GraphQL server.
b) Arguments: As URL segments and query parameters, we can only pass a single set of arguments in REST. A typical REST call to obtain a specific profile will resemble the following: GET /api'employee?id=2 Content-Type: application JSON { "empId": 3, "ename": "Peter." }
2. Resolver: Resolvers give instructions on how to translate GraphQL operations into data. They define resolver routines that convert the query to data.
It shows the server the location and method for fetching data for a certain field. Additionally, the resolver distinguishes between API and database schema. The separated information aids in the modification of the database-generated material.
3. Schema: The heart of GraphQL implementation is a schema. It explains the features that the clients connected to it can use.
The benefits of using GraphQL in an application are summarized below.
It is more precise, accurate, and efficient.
GraphQL queries are simple and easy to understand.
Because it uses a simple query, GraphQL is best suited for microservices and complex systems.
It makes it easier to work with large databases.
Data can be retrieved with a single API call.
GraphQL does not have over-fetching or under-fetching issues.
GraphQL can be used to discover the schema in the appropriate format.
GraphQL provides extensive and powerful developer tools for query testing and documentation.
GraphQL automatically updates documentation in response to API changes.
GraphQL fields are used in multiple queries that can be shared and reused at a higher component level.
You have control over which functions are exposed and how they operate.
It is suitable for rapid application prototyping.
GraphQL can be used in all types of mobile and web applications across industries, verticals, and categories that require data from multiple sources, real-time data updates, and offline capabilities. Here is some application that benefits greatly from GraphQL development:
It offers Relay as well as other client frameworks.
GraphQL assists you in improving the performance of your mobile app.
It can reduce the problem of over fetching to reduce server-side cloud service and client-side network usage.
It can be used when the client application needs to specify which fields in a long query format are required.
GraphQL can be fully utilized when adding functionality to an existing or old API.
It is used to simplify complicated APIs.
The mix-and-match façade pattern, which is popular in object-oriented programming.
When you need to combine data from multiple sources into a single API.
GraphQL can be used as an abstraction on an existing API to specify response structure based on user requirements.
In this blog, I’ve attempted to explain the significance of GraphQL it is a new technology that allows developers to create scalable APIs that are not constrained by the limitations of REST APIs. It allows developers to use an API to easily describe, define, and request specific data. Please let us know what you think of GraphQL. Do you have any further questions? Please do not hesitate to contact us. We will gladly assist you.
0 notes
makersterri · 3 years ago
Text
Php json decode unicode
Tumblr media
PHP JSON DECODE UNICODE GENERATOR
PHP JSON DECODE UNICODE UPDATE
Specifies a bitmask (JSON_BIGINT_AS_STRING, Object will be converted into an associative array. Json_decode( string, assoc, depth, options) Parameter Values Parameter PHP Examples PHP Examples PHP Compiler PHP Quiz PHP Exercises PHP Certificate PHP - AJAX AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll PHP XML PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat PHP XML DOM
PHP JSON DECODE UNICODE UPDATE
MySQL Database MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data PHP OOP PHP What is OOP PHP Classes/Objects PHP Constructor PHP Destructor PHP Access Modifiers PHP Inheritance PHP Constants PHP Abstract Classes PHP Interfaces PHP Traits PHP Static Methods PHP Static Properties PHP Namespaces PHP Iterables PHP Advanced PHP Date and Time PHP Include PHP File Handling PHP File Open/Read PHP File Create/Write PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions PHP Forms PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail PHP Form Complete Store the expression in a $json2 variable and echo it.Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET PHP RegEx Use the decoded JSON object as the first parameter to the json_encode() function and the JSON_PRETTY_PRINT option as the second parameter. Then, use the json_decode() function on the variable $json1. Create a variable $json1 and store a raw JSON object in it. We will take the JSON object and decode it using the json_decode() function and then will encode it with the json_encode() function along with the JSON_PRETTY_PRINT option.įor example, set the Content-Type to application/json as we did in the method above. We will prettify a JSON object in the following example. We also use the header() function like in the second method to notify the browser about the JSON format. We can use the json_encode() function with the json_decode() function and the JSON_PRETTY_PRINT as the parameters to prettify the JSON string in PHP. Use the json_encode() and json_decode() Functions to Prettify the JSON String in PHP Header('Content-Type: application/json') Įcho json_encode($age, JSON_PRETTY_PRINT) As a result, we will get a prettified version of JSON data in each new line.Įxample Code: $age = array("Marcus"=>23, "Mason"=>19, "Jadon"=>20) In the next line, use the json_encode() function with the JSON_PRETTY_PRINT option on the array as we did in the first method. We can use the json_encode() function as in the first method.įor example, write the header() function and set the Content-Type to application/json. We will use the same associative array for the demonstration. We can use the JSON_PRETTY_PRINT option as in the first method to prettify the string. We can use the header() function to set the Content-Type to application/json to notify the browser type. Use the application/json and JSON_PRETTY_PRINT Options to Prettify the JSON String in PHP $json_pretty = json_encode($age, JSON_PRETTY_PRINT) Then, echo the variable enclosing it with the HTML tag.Įxample Code: $age = array("Marcus"=>23, "Mason"=>19, "Jadon"=>20) Next, use the json_encode() function on the $age variable and write the option JSON_PRETTY_PRINT as the second parameter and store the expression in $json_pretty variable. Write the keys Marcus, Mason, and Jadon and the values 23, 19, and 20.
PHP JSON DECODE UNICODE GENERATOR
QR Code Generator in PHP with Source Code 2021 | freeload | PHP Projects with Source Code 2021įor example, create an associative array in the variable $age. The tag preserves the line break after each key-value pair in the string. We will prettify an associative array in the example below. However, we can use the HTML tags to indent the strings to the new line. It will add some spaces between the characters and makes the string looks better. We can specify the string to be prettified and then the option in the json_encode() function. The json_encode() function has a option JSON_PRETTY_PRINT which prettifies the JSON string. We can encode indexed array, associative array, and objects to the JSON format. We can use the json_encode() function to convert a value to a JSON format. Use the HTML Tag and the JSON_PRETTY_PRINT Option to Prettify the JSON String in PHP This article will introduce different methods to prettify the raw JSON string in PHP.
Use the json_encode() and json_decode() Functions to Prettify the JSON String in PHP.
Use the application/json and JSON_PRETTY_PRINT Options to Prettify the JSON String in PHP.
Use the HTML Tag and the JSON_PRETTY_PRINT Option to Prettify the JSON String in PHP.
Tumblr media
0 notes
mainsnoble · 3 years ago
Text
Json decode
Tumblr media
#JSON DECODE HOW TO#
#JSON DECODE CODE#
#JSON DECODE FREE#
With the help of the Online JSON Parser Tool, we can easily format our minify JSON Data and easily find key and value pairs and identify changes quickly.
JSON Data mainly used when we need to transfer data with different platforms and it’s easy to synchronize and used in any system.
All Data are available in Key and value pair. Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the.
Here, In the above sample JSON data Name, Country, and Age are known as key and Jone, USA, and 39 known as a Value.
In Treeview, You can Search and highlight, and Sorting Data.
jsondecode converts JSON data types to the MATLAB data types in this table.
Minify or Compact JSON Data to resave and reduct its Size. JSON supports fewer data types than MATLAB.
JSON Validator for your Online Changes and your other JSON Data.
Redo and Undo facility when you edit your JSON online.
#JSON DECODE HOW TO#
How to Parse Large JSON Data with Isolates in Dart 2.The JSON Parser Tools have Below the main functionality:.
#JSON DECODE CODE#
How to Parse JSON in Dart/Flutter with Code Generation using FreezedĪnd if you need to parse large JSON data, you should do so in a separate isolate for best performance.In such cases, code generation is a much better option and this article explains how to use it: If you have a lot of different model classes, or each class has a lot of properties, writing all the parsing code by hand becomes time-consuming and error-prone. Restaurant Ratings example - JSON Serialization code.While the example JSON we used as reference wasn't too complex, we still ended up with a considerable amount of code: consider using the deep_pick package to parse JSON in a type-safe way.for nested JSON data (lists of maps), apply the fromJson() and toJson() methods.add explicit casts, validation, and null checks inside fromJson() to make the parsing code more robust.create model classes with fromJson() and toJson() for all domain-specific JSON objects in your app.When null, JSON objects will be returned as. When true, JSON objects will be returned as associative array s when false, JSON objects will be returned as object s. PHP implements a superset of JSON as specified in the original RFC 7159. use jsonEncode() and jsonDecode() from 'dart:convert' to serialize JSON data This function only works with UTF-8 encoded strings.But if we want our apps to work correctly, it's very important that we do it right and pay attention to details: JSON serialization is a very mundane task. You can build anything with Appwrite! Click here to learn more. Appwrite is a secure, self-hosted solution that provides developers with a set of easy-to-use REST APIs to manage their core backend needs. Open-Source Backend Server for Flutter Developers. Help me keep it that way by checking out this sponsor:
#JSON DECODE FREE#
Serializing Nested ModelsĪs a last step, here's the toJson() method to convert a Restaurant (and all its reviews) back into a Map:Ĭode with Andrea is free for everyone. You need to write the parsing code that is most appropriate for your use case. This specific implementation makes some assumptions about what may or may not be null, what fallback values to use etc.
if the reviews are missing, we use an empty list ( ) as a fallback.
map() operator to convert each dynamic value to a Review object using omJson()
the values in the list could have any type, so we use List.
the reviews may be missing, hence we cast to a nullable List.
Tumblr media
1 note · View note
longventure · 3 years ago
Text
Php json decode as object
Tumblr media
#Php json decode as object how to#
Let’s take the first example, here we will convert the JSON string to PHP array using the json_decode() function. Reviver method object can be passed in JSON.parse() to return a modified object of JSON in case of custom logic requires to add and return the different.
options: It includes bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING, JSON_THROW_ON_ERROR.
#Php json decode as object how to#
Let’s see how to do it in practice with a few examples. There exist specific built-in functions that allow encoding and decoding JSON data. The data structures of JSON are identical to PHP arrays. Follow the steps and you’ll manage to meet your goal easily. Chapter 2 JSON encoding Creating a JSON object with PHP is simple: You just need to use the jsonencode () function. In this snippet, you can find a step-by-step guide on how to create and parse JSON data with PHP. depth: It states the recursion depth specified by user. Decode a JSON object received by your PHP script.If it is true then objects returned will be converted into associative arrays. Normally, jsondecode() will return an object of stdClass if the top level item in the JSON object is a dictionary or an indexed array if the JSON object. It only works with UTF-8 encoded strings. json: It holds the JSON string which need to be decode.The syntax of JSON decode function is:- json_decode(string, assoc, depth=500, options) Parameters of json_decode() function PHP: json_decode() | How to decode json to array in PHPĭefination:- The PHP json_decode() function, which is used to decode or convert a JSON object to a PHP object. An optional Assoc boolean to instruct whether to bypass conversion to an object and to produce an associative array. The decode function has the following parameters. It basically accepts three parameters, but you will usually only need the first one, i.e. Now jsondecode() on the other hand, has a completely different goal, which is to only attempt to convert a JSON string to a PHP object or array. will decode the json string as array For some reason I’m able to extract the json string as array but when I try it to do it as object it breaks. Like, convert JSON string to array PHP, convert JSON string to multidimensional array PHP and JSON decode and access object value PHP. You can also turn your own data into a well-formatted JSON string in PHP with the help of the jsonencode () function. Be wary that associative arrays in PHP can be a 'list' or 'object' when converted to/from JSON, depending on the keys (of absence of them). When decoding that string with jsondecode, 10,000 arrays (objects) is created in memory and then the result is returned. In this tutorial, we will take examples using the json_decode() function. JSON can be decoded to PHP arrays by using the associative true option. Efficient, easy-to-use, and fast PHP JSON stream parser - GitHub - halaxa/json-machine: Efficient, easy-to-use, and fast PHP JSON stream parser. PHP JSON decode In this tutorial, we will discuss about php json_decode() function syntax, defination, parameters with examples.
Tumblr media
0 notes
javatpoints-blog · 4 years ago
Photo
Tumblr media
JSON tutorial for beginners and professionals provides deep knowledge of JSON technology. Our JSON tutorial will help you to learn JSON fundamentals, example, syntax, array, object, encode, decode, file, date and date format. In this JSON tutorial, you will be able to learn JSON examples with other technologies such as Java, PHP, Python, Ruby, jQuery, AJAX, C#, Perl and Jackson. You will also learn how to convert json to xml, html, csv, php array and vice versa.Javatpoint is one of the best CSS training institute in Noida, Dehli, Gurugram, Ghaziabad and Faridabad. We have a team of experienced CSS developers and trainers from multinational companies to teach our campus student. . We focus on practical training sessions as well as theorerical classes
0 notes
yudiz123blog · 5 years ago
Text
Laravel VII: Abbreviated | Web Development - Yudiz Solutions Pvt. Ltd.
Overview:
Hello there. As we all know the Laracon Online 2020, the largest online Laravel conference, took place on 26 February 2020. Our developer happened to attend a Laracon Online Viewing Party and according to his experience we are going to share with you the highlights. We’re going to focus on Laravel 7 here. Yes, it’s here and stick till the end to know all about it.
Tumblr media
So as most of you might know Taylor Otwell was one of the speakers at the event. He gave us a complete walkthrough for Laravel VII and we are going to cover most of it here.
What is Laravel Airlock?
Airlock is a lightweight Token Generation and verification tool (Provides Authentication) mostly for SPAs (Single Page Applications), where users can generate multiple API tokens and like passport, we can set the roles for particular auth token.
AirLock will work with Laravel 6.x, but everyone recommends using it with Laravel 7.x and you also need to use Laravel UI 2.x for UI files.
We can set allowed domain in config file, so if a request comes from that particular server then and only then that request gets served. So we can say airlock is a similar kind of structure like a passport but it’s for SPA.
For better understanding,we can compare AirLock mechanism with Node/Angular project where frontend API will use AuthToken. Authtoken is similar kind of personal access token which we are used in the passport for mobile authentication
Key features of AirLock:
EncryptCookies
AddQueuedCookiesToResponse
StartSession
 VerifyCsrfToken
Laravel Custom Casts:
In Laravel VII, we can create our own casting for an eloquent model, there are two methods, “get()” and “set()”
“get()” method is used to convert raw data into casted data.
“set()” method is used to convert casted data into raw data value.
For example, if we need to decode data when we receive it and encode data when we save details, we can use these methods like this:
Syntax for “get()” method:
   public function get($model, $key, $value, $attributes) {
            return json_decode($value, true);
   }
Syntax for “set()” method:
   public function set($model, $key, $value, $attributes) {
            return json_encode($value, true);
   }
For eloquent we need to define detail as:
protected $casts = [
           'column_name' => Json::class,
           ];
So now every time we fetch data of a column, we get JSON decoded data and when the data is saved to the column it will get encoded.
HTTP Client:
HTTP Client is used for making an HTTP request from one website to another website or web application. For HTTP client you have to install guzzlehttp/guzzle package into your project. We can make any request along with header through the HTTP Client, also we get the details of response and other params directly, like if we want the main body of the response, then just write down $response->body() this will return the body. If we need to check the status of the response then just need to call $response->status().
Likewise, we can use the following details:
$response->body();
$response->json();
$response->status();
$response->ok();
$response->successful();
$response->serverError();
$response->clientError();
$response->header($header);
$response->headers();
And for the routes we have to write details like:
$response = Http::withHeaders([
           'accept' => 'application/json',
])->post('http://domain.com/users/list', [
           'name' => 'User',
]);
So now onwards we can fire the API from the web routes along with the Headers. We can also pass the Bearer Token by just adding:
$response = Http::withToken('token')->post('http://www.domain.com', ['name' => 'User']);
Fluent String Operations:
We can all agree how useful string operations are as they help us manipulate strings easily and without much hassle. Thanks to Laravel VII, some new and useful string operations were added in this version. String operations such as trim(), replace(‘x’, ‘y’), after(), before(), words() and many more now will be available in Laravel VII.
CORS Support:
Laravel VII also came with the fresh first-party package “CORS” along with options, so now no need to create custom middleware for the same, just configure the config files and use CORS services.
Stub Customization:
This is one of the best updates of Laravel. This will help us to boost up the speed of development. For example, whenever we create a new Model, we will write protected $guarded = [*] in all the models, it becomes a bit time consuming if you see it on a larger picture. So now, we can create our own stub for these kinds of changes, So, if we added protected $guarded = [*] into stub then whenever we create a new model, this line will be added automatically. For example, in all tables we need one default column $table->string(‘custom_id’), in all the migrates, so we will publish the stub and customize it.
Route Model Binding:
This is one of the most interesting features of Laravel 7. In the older version, we can bind any model to route, for example:
Route::get('user/{user}', function(User $user) {
   dd($user);
});
// domain.com/user/1
Here we’ll get the user’s personal details like we applied dependency injection of the User model. In Laravel 7, there is support for Implicit Model Binding, such as if I want to get the user’s details based on the user’s name then I’ll get details by adding simple “:” after model’s name.
Route::get('user/{user:username}', function(User $user){
           return $user;
});
// domain.com/user/kmjadeja
We can also add custom keys and scoping for the Route Model Binding, it’s a very useful thing which can help us to generate SEO friendly URLs.
Custom Keys and Scope:
Sometimes, we need to bind multiple models to the single route and second binding param is dependent on the first building param like we need to get product details that are available under one specific category.
For example, we get all the lists of all the mobile devices which are available under the android category, So now we can do this with simple Route Model Binding
Route::get('category/{category:type}/device/{device:type}',
function (Category $category, Device $device) {
return $device;
});
// domain.com/category/mobile/device/android
 One more simple example:
Route::get('user/{user}/posts/{post:slug}',
function (User $user, Post $post) {
return $post;
});
// domain.com/user/1/posts/upcoming-events
Laravel Query Cast:
·         Query cast is used to “cast” a column while executing the query.
·         Let’s take an example : In the database we save user’s ID, System IP, create_at and updated_at details when user LoggedIn to the system. Now we want to know the last login date of particular user in that case my code will be:
$users = User::select([
   'users.*',
   'last_logged_in_at' => UserLog::selectRaw('MAX(created_at)')
           ->whereColumn('user_id', 'users.id')
])->where('id', 1)->withCasts([
   'last_logged_in_at' => 'date'
])->get();
So here we get the user’s last loggedIn details in “data”, not in the timestamp, we cast the user’s create_at column to date.
Improve email template design:
In Laravel 7 they have simply improved the email template, made the email template simpler and finer.
Queue Configuration:
Currently, if any queue or job is throwing an exception, each time the job will get executed and throw the exception. In Laravel 7, we can set maxExceptions for jobs. If we set the value equal to 3, in that case, if the job gets the exception more than 3 times, the queue stops automatically. #noExtraExecution
Speed improvements for route-cache:
Laravel 7 have 2x speed improvement for routes, it is mostly used with 800+ routes (big projects), php artisan route:cache is used to cache the routes.
Conclusion:
So that’s all for this blog but that’s not all for Laravel 7 and our discussion on it. Stick with us for the next blog regarding some of the features along with their demo codes. Till then, get started with the master document. You can read the master document here.
Hope, you have liked & enjoyed this blog. If you like this blog then follow us for more such interesting articles on the latest technologies.
0 notes
airman7com · 5 years ago
Text
PHP json encode – Convert Array To JSON, Object To JSON
The PHP json_encode () function function is used to convert PHP arrays or objects into JSON. PHP has some pre-built functions to handle JSON.
In this tutorial, we will learn how to convert PHP Object to JSON, convert PHP String to JSON, PHP Array To JSON, get data from JSON array in php convert Multidimensional PHP Array into JSON with definitions, syntax, and examples.
What is JSON?
JSON means…
View On WordPress
0 notes
innovaturelabs · 5 years ago
Text
Security Solutions for PHP
PHP is as secure a language as any other programming language. It’s an open source server side scripting language that has various attributes and frameworks which requires programmers to write and engineer secure applications.
In PHP there are several areas where security issues appear more frequently. Malicious users can exploit these vulnerabilities to gain sensitive information about your system or your users.
These vulnerabilities can include:
Injection
Broken Authentication
Sensitive Data Exposure
Broken Access control
Cross Site Scripting (XSS)
Insecure Deserialization
PHP also relies on several third-party libraries which can have security vulnerabilities. If the application is using the vulnerable library version, then the application also may be vulnerable too.
Injection
A code injection happens when an attacker sends invalid data to the web application with the intention to make it do something that the application was not designed/programmed to do.
Perhaps the most common example around this security vulnerability is the SQL query consuming untrusted data. You can see one example below:
String query = “SELECT * FROM accounts WHERE custID = ‘” + request.getParameter(“id”) + “‘”;
This query can be made use of by calling up the web page executing it with the following URL: http://example.com/app/accountView?id=’ or ‘1’=’1 causing the return of all the rows stored on the database table.
The core of a code injection is the lack of validation of the data used by the web applications which means that this weakness can be present on almost any type of technology.
Following are the recommendations to prevent SQL injections
Use positive or “whitelist” server-side input validation.
For any residual dynamic queries, escape special characters using the specific escape syntax for that interpreter.
Use LIMIT and other SQL controls within queries to prevent mass disclosure of records in case of SQL injection.
Broken Authentication
A broken authentication can allow an attacker to use manual and/or automatic methods to try to gain control over any account they want in a system — or even worse — to gain complete control over the system. These threats can come in many forms. A web application contains a broken authentication threats if it:
Permits automated threats such as credential stuffing, where the hacker has a list of valid usernames and passwords.
Permits brute force or other automated threats.
Permits default, weak, or well-known common passwords.
Uses common text, encrypted, or weakly hashed passwords.
Has missing or ineffective multi-factor authentication.
Shown session IDs in the URL (e.g., URL rewriting).
Following are the recommended preventive measures.
Where the other possible way is the implementation of multi-factor authentication to prevent automated, credential stuffing, brute force, and stolen credential reuse threats.
Do not ship or make use of any default credentials, particularly for admin users.
Implement weak-password checks
Use a server-side, secure, built-in session manager that generates a new random session ID with high entropy after login. Session IDs should not be in the URL. Ids should also be securely stored and invalidated after logout, idle, and absolute timeouts.
Sensitive Data Exposure
Over the last few years, sensitive data exposure has been one of the most common threat around the world. Some sensitive data that needs protection is Credentials, Credit card numbers, Social Security Numbers, Medical information, Personally, identifiable information (PII), Other personal information. This threat is usually very hard to make use of; however, the consequences of a successful attack are dreadful.
There are two types of data:
Stored data — data at rest
Transmitted data — data that is transmitted internally between servers, or to web browsers
Both types of data should be protected. When thinking about data in transit, one way to protect it on a website is by having an SSL certificate. Not encrypting sensitive data is the main reason why these attacks are still so widespread.
Some of the ways to prevent data exposure are:
Do not store sensitive data unnecessarily.
Discard it as soon as possible or use PCI DSS compliant tokenization or even shorten. Data that is not retained cannot be stolen.
Make sure to encrypt all possible sensitive data at rest.
Ensure up-to-date and strong standardized algorithms, protocols, and keys are in place; use proper key management.
Disable caching for responses that contain sensitive data.
Store passwords using strong adaptive and salted hashing functions with a work factor (delay factor), such as bcrypt
Broken Access Control
Access controls are mainly designed to prevent users from acting outside their intended permissions, when threats exist in these controls, or there are no controls users can act outside of their intended permissions. This may help attackers to steal information from other users, modify data and perform actions as other users. Broken access controls can make applications at a high-risk for compromise, typically resulting in the impact of confidentiality and integrity of data. An adversary can steal information accessed by users of the application, exploit data by performing actions that various user roles can perform within the application, and in certain circumstances compromise the web server.
Common access control vulnerabilities include:
Bypassing access control ensure by modifying the URL, internal application state, or the HTML page, or simply using a custom API attack tool
providing the primary key to be changed to another’s users record, permitting viewing or editing someone else’s account.
upgrading of privilege.
Metadata exploitation, such as replaying or tampering with a JSON Web Token (JWT) access control token or a cookie or hidden field exploited to elevate privileges, or abusing JWT invalidation
CORS misconfiguration allows unauthorized API access.
Force browsing to authenticated pages as an unauthenticated user or to advanced pages as a standard user. Entering API with missing access controls for POST, PUT and DELETE.
The technical recommendations to prevent broken access control are:
Except for public resources, deny by default.
Executing access control mechanisms once and reuse them throughout the application, including minimizing CORS usage.
Model access controls should enforce record ownership instead of accepting that the user can create, read, update, or delete any record.
Defuse web server directory listing and ensure file metadata (e.g. git) and backup files even if they are not present within web roots.
Maintain log access control failures, alert admins when appropriate (e.g. repeated failures).
Developers and QA staff should include functional access control units and integration tests.
Cross-Site Scripting (XSS)
Cross-Site Scripting (XSS) is the most used common singular security threat existing in web applications at large. XSS occurs when an attacker can inject a script, often JavaScript, into the output of a web application in such a way that it is executed in the client browser. This ordinarily happens by locating a means of breaking out of a data context in HTML into a scripting context — usually by injecting new HTML, JavaScript strings or CSS markup. HTML has no shortage of locations in which executable JavaScript can be injected and browsers have even managed to add more. The injection is sent to the web application via any means of input such as HTTP parameters.
Injected JavaScript can be used to accomplish quite a lot: stealing cookie and session information, performing HTTP requests with the user’s session, redirecting users to hostile websites, accessing and manipulating client-side persistent storage, performing complex calculations and returning results to an attacker’s server, attacking the browser or installing malware, leveraging control of the user interface via the DOM to perform a UI Redress (aka Clickjacking) attack, rewriting or manipulating in-browser applications, attacking browser extensions, and the list goes on…possibly forever.
Some preventive measures to reduce the chances of XSS attacks:
Using the frameworks that automatically escape XSS by design.
Escaping untrusted HTTP request data based on the context in the HTML output will resolve Reflected and Stored XSS vulnerabilities.
Put in context-sensitive encoding when modifying the browser document on the client side acts against DOM XSS.
Allowing a content security policy (CSP) is a defense-in-depth mitigating control against XSS.
Insecure Deserialization
There should be a way to transform the in-memory object into a stream of bytes which can be easily stored and shared. That is what the process of serialization is all about. When the game performs the serialization of an object, we say that the object is serialized.
Tumblr media
The following function in php to perform the mutation of object to bytes is as follows:
$my_object = serialize($variable);
Deserialization is the opposite of serialization. In fact, it consists of converting the serialized data into an in-memory representation which the software can then manipulate. If we want to retrieve the state of the serialized character object, it needs to deserialize it first.
Tumblr media
The following function in php to perform the mutation from bytes to object is as follows:
$my_bytes = unserialize($variable);
When a software deserializes user-maintained data without verification, we call it insecure deserialization. If the developer does not perform a verification before deserialization, the insecure deserialization will trigger the attacker’s code.
The best way to protect your web application from this type of risk is not to accept serialized objects from untrusted sources.
Following are some recommendations that you can try to implement:
Performing integrity checks such as digital signatures on any serialized objects to prevent hostile object creation or data tampering.
Impose strict type constraints during deserialization before object creation as the code typically expects a definable set of classes.
Separating and running code that deserializes in low privilege environments when possible.
Logging exceptions and failures, such as where the incoming type is not the expected type, or the deserialization throws exceptions.
Limiting or monitoring incoming and outgoing network connectivity from containers or servers that deserialize.
Monitoring deserialization, alerting if a user deserializes constantly.
Conclusion
Security vulnerabilities are a fact of life. While a security breach can be damaging to your business, there are plenty of ways you can protect your PHP sites and mitigate your risk that don’t require you to be a security genius with the right training, awareness, tools, and practices, you can safely run PHP applications today and in future .
Tumblr media
For more information on the topic go to PHP.
0 notes
t-baba · 5 years ago
Photo
Tumblr media
An Introduction to REST and RESTful APIs
REST is an acronym for Representational State Transfer — an almost meaningless description of the most-used web service technology! REST is a way for two computer systems to communicate over HTTP in a similar way to web browsers and servers.
Sharing data between two or more systems has always been a fundamental requirement of software development. For example, consider buying motor insurance. Your insurer must obtain information about you and your vehicle so they request data from car registration authorities, credit agencies, banks, and other systems. All this happens transparently in real time to determine whether a policy can be offered.
REST Example
Open the following link in your browser to request a random programming joke:
https://official-joke-api.appspot.com/jokes/programming/random
This is a public API implemented as RESTful web service (it follows REST conventions). Your browser will show an awful JSON-formatted programming joke, such as:
[ { "id": 29, "type": "programming", "setup": "There are 10 types of people in this world...", "punchline": "Those who understand binary and those who don't" } ]
You could request the same URL and get a response using any HTTP client, such as curl:
curl "https://official-joke-api.appspot.com/jokes/programming/random"
HTTP client libraries are available in all popular languages and runtimes including Fetch in JavaScript and file_get_contents() in PHP. A JSON response is machine-readable so it can be parsed and output in HTML or any other format.
REST and the Rest
Various data communication standards have evolved over the years. You may have encountered standards including CORBA, SOAP, or XML-RPC, which usually established strict messaging rules.
REST was defined in 2000 by Roy Fielding and is considerably simpler. It's not a standard but a set of recommendations and constraints for RESTful web services. These include:
Client-Server. SystemA makes an HTTP request to a URL hosted by SystemB, which returns a response.
It's identical to how a browser works. The application makes a request for a specific URL. The request is routed to a web server that returns an HTML page. That page may contain references to images, style sheets, and JavaScript, which incur further requests and responses.
Stateless. REST is stateless: the client request should contain all the information necessary to respond to a request. In other words, it should be possible to make two or more HTTP requests in any order and the same responses will be received.
Cacheable. A response should be defined as cacheable or not.
Layered. The requesting client need not know whether it’s communicating with the actual server, a proxy, or any other intermediary.
Creating a RESTful Web Service
A RESTful web service request contains:
An Endpoint URL. An application implementing a RESTful API will define one or more URL endpoints with a domain, port, path, and/or querystring — for example, https://mydomain/user/123?format=json.
The HTTP method. Differing HTTP methods can be used on any endpoint which map to application create, read, update, and delete (CRUD) operations:
HTTP method CRUD Action GET read returns requested data POST create creates a new record PUT or PATCH update updates an existing record DELETE delete deletes an existing record
Examples:
a GET request to /user/ returns a list of registered users on a system
a POST request to /user/123 creates a user with the ID 123 using the body data
a PUT request to /user/123 updates user 123 with the body data
a GET request to /user/123 returns the details of user 123
a DELETE request to /user/123 deletes user 123
HTTP headers. Information such as authentication tokens or cookies can be contained in the HTTP request header.
Body Data. Data is normally transmitted in the HTTP body in an identical way to HTML <form> submissions or by sending a single JSON-encoded data string.
The Response
The response payload can be whatever is practical: data, HTML, an image, an audio file, and so on. Data responses are typically JSON-encoded, but XML, CSV, simple strings, or any other format can be used. You could allow the return format to be specified in the request — for example, /user/123?format=json or /user/123?format=xml.
An appropriate HTTP status code should also be set in the response header. 200 OK is most often used for successful requests, although 201 Created may also be returned when a record is created. Errors should return an appropriate code such as 400 Bad Request, 404 Not Found, 401 Unauthorized, and so on.
Other HTTP headers can be set including the Cache-Control or Expires directives to specify how long a response can be cached before it’s considered stale.
However, there are no strict rules. Endpoint URLs, HTTP methods, body data, and response types can be implemented as you like. For example, POST, PUT, and PATCH are often used interchangeably so any will create or update a record.
REST "Hello World" Example
The following code creates a RESTful web service using the Node.js Express framework. A single /hello/ endpoint responds to GET requests.
Ensure you have Node.js installed, then create a new folder named restapi. Create a new package.json file within that folder with the following content:
{ "name": "restapi", "version": "1.0.0", "description": "REST test", "scripts": { "start": "node ./index.js" }, "dependencies": { "express": "4.17.1" } }
Run npm install from the command line to fetch the dependencies, then create an index.js file with the following code:
// simple Express.js RESTful API 'use strict'; // initialize const port = 8888, express = require('express'), app = express(); // /hello/ GET request app.get('/hello/:name?', (req, res) => res.json( { message: `Hello ${req.params.name || 'world'}!` } ) ); // start server app.listen(port, () => console.log(`Server started on port ${port}`); );
Launch the application from the command line using npm start and open http://localhost:8888/hello/ in a browser. The following JSON is displayed in response to the GET request:
{ "message": "Hello world!" }
The API also allows a custom name, so http://localhost:8888/hello/everyone/ returns:
{ "message": "Hello everyone!" }
The post An Introduction to REST and RESTful APIs appeared first on SitePoint.
by Craig Buckler via SitePoint https://ift.tt/2S0jtmw
0 notes
coding-samuraized · 5 years ago
Text
What serialization is?
source: https://stackoverflow.com/questions/11817950/what-is-data-serialization
Serialization is objects encoding into other language. For example you have an array in PHP like this:
$array = array("a" => 1, "b" => 2, "c" => array("a" => 1, "b" => 2));
And then you want to store it in file or send to other application.
There are multiple choices of languages, but the idea is the same: That array has to be encoded (or translated) into text or bytes, that can be written to file or sent via network. For example, if you
$data = serialize($array);
you will get this:
a:3:{s:1:"a";i:1;s:1:"b";i:2;s:1:"c";a:2:{s:1:"a";i:1;s:1:"b";i:2;}}
This is PHP's particular serializing format that PHP understands and it works vice versa so you are able to use it to deserialize objects. For example, you stored an array in file and you want it back in your code:
$array = unserialize($data);
But you could choose another serialization format, for example, JSON.
$json = json_encode($array);
will give you this:
{"a":1,"b":2,"c":{"a":1,"b":2}}
Result that is not only easily saved, read by human eye or sent via network, but is understandable to almost every other language (Javascript, Java, C#, C++.....)
Conclusion Serialization is object translation to other language, in case you want to store or share data.
Are there any situations, where you cannot do anything, but serialize it?
No. But serialization usually makes things easier.
Are JSON and PHP format the only possible formats? No, no, no and one more time no. There are plenty of formats.
XML which has successors like SOAP, WSDL, etc (those have particular purpose)
Bytes
...
...
...
Your own formats (you can create your own format for serialization and use it, but that is a big thing to do and is not worth it, most of the time)
Tumblr media
0 notes
nancydsmithus · 6 years ago
Text
Programmatically Discovering Sharing Code With oEmbed
Programmatically Discovering Sharing Code With oEmbed
Drew McLellan
2019-11-26T11:00:00+00:002019-11-26T12:06:06+00:00
The web is full of services that host rich content such as videos, images, music and podcasts, maps and graphs, and all manner of different delights. Chances are, when you add your content to a site, it will offer you a way to embed that content in a web page somewhere else.
Sites like YouTube have their own embeddable player that is popular to use in blog posts and even product pages. Soundcloud has code for embedding their music player in your band’s website. Charity fundraisers might upload the route of their big race to a site like Strava, and want to share it on their fundraising site to show their sponsors.
All this is done by finding that Share option on the hosting site and copying out some code that is normally a mix of HTML and JavaScript. That code can then usually be pasted into the destination page, and the hosting site will present a rich representation of the content for all your friends, customers and contacts to see.
So far, so good, and this covers the option for the manual embedding of content pretty well. There is a distinct second use-case however, where the outcome is the same but the route to it is very different.
Sharing Programmatically
Let’s imagine you’re building an app or site that accepts content from a user. That could be something as simple as a basic intranet page for staff to share news with coworkers, or something massive like a whole social network where people can sign up and start posting.
In both cases, you need to work out what to do if the user adds a URL as part of that content. You can imagine the scenario:
Check out this video! https://youtu.be/jw7bRnFbwAI
At this point, as a publishing system, you need to figure out what to do. The first option is to do nothing, and just leave the URL as plain text. That’s not a brilliant idea, as users will generally want to click on the URL and plain text won’t help them get to the page at the other end.
The second option is to turn it into a link. That’s a good solid next step, as users can follow the link and get to the content. But in doing so, they leave your site and might not come back in a hurry.
The best user experience might be to be able to fetch the player for that content and embed it right there instead of just the URL. That would enable users to experience the content right within your site, much like they would on Facebook, for example.
This poses the problem. Given a URL, how can I turn that into the HTML/JavaScript embed code needed to show a rich player on the page?
If it’s a known site like YouTube, I could write some code that uses the YouTube API to fetch the video information and get or build the embed code that way. I could do the same for other video services like Vimeo and VIVO. I can write code to recognize Flickr and Instagram URLs and use their APIs to fetch nice embeddable versions of photographs. And the same for Twitter and tweets. But this is sounding like a lot of work!
What would be ideal is if there was a standardized way of getting from a URL of a piece of content to a block of embed code to show that content on a page. If you’ve been paying attention, you’ll realize that the answer to that is oEmbed.
The Origin Of oEmbed
This was exactly the problem Leah Culver had while working on Pownce (a truly innovative social networking site that was the Betamax to Twitter’s VHS). Pownce wanted to embed rich representations of content into a user’s update stream, but didn’t want to limit support to only the services they’d specifically written code to integrate with. At dinner with colleague Mike Malone, as well as Cal Henderson (who led engineering at Flickr — one of the major providers of such content at the time) and Richard Crowley, they together hashed out an idea for an open standard for getting embed code from a URL. Henderson went away and drafted something up based on the discussion, and oEmbed was born.
Using oEmbed
Here’s how it works.
It starts with the URL that points to a single item of content. That might be a YouTube video, an image, or whatever. Typically this will have been provided by a user of your site or app as part of some content they wish to publish. The first step is to fetch the content of the page at that URL, which should be an HTML page.
If the site hosting the content supports oEmbed, in the <head> section of that page there should be a link element with an oembed content type:
<link rel="alternate" type="application/json+oembed" href="http://www.youtube.com/oembed?url=https%3A%2F%2Fyoutu.be%2Fjw7bRnFbwAI&format=json" title="Inclusive Components with Heydon Pickering" />
A note about XML: oEmbed supports responses in both XML and JSON format. For this article, I’m only considering JSON, because we’re not savages. If you’re in the unfortunate position to need to work with XML, be aware that it is a supported format with the oEmbed spec, although you may find that some providers only offer JSON responses.
This link tag as the rel attribute set to alternate and a type set to either application/json+oembed or text/xml+oembed. It’s this attribute that clues us into the fact that the URL given in the href is actually an oEmbed API endpoint for retrieving the details of the content.
That URL will have usually two parameters: url and format.
Parameter Value url (required) The URL-encoded web address of the content item format The format you’d like the response in. One of either json or xml
Common URL parameters for the initial consumer request
The full specification goes into much more detail here (and you should reference that if creating your own implementation) but these are the two parameters you’ll likely see the most.
So, we’ve got a URL, fetched the page, found an oEmbed link tag with another URL for an API endpoint. Next, we request that new URL, and that returns all the information the service has to provide about that piece of content.
{ "author_name": "Smashing Magazine", "width": 480, "title": "Smashing TV: Inclusive Components with Heydon Pickering (Nov 7th 2019)", "provider_name": "YouTube", "height": 270, "html": "<iframe width=\"480\" height=\"270\" src=\"https://www.youtube.com/embed/jw7bRnFbwAI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>", "provider_url": "https://www.youtube.com/", "thumbnail_url": "https://i.ytimg.com/vi/jw7bRnFbwAI/hqdefault.jpg", "type": "video", "thumbnail_height": 360, "author_url": "https://www.youtube.com/channel/UCSDtqcJ8ZXviPrEcj1vuLiQ", "version": "1.0", "thumbnail_width": 480 }
Now we’re talking! The response gives us lots of information about the content. The version should for the foreseeable future be 1.0, which is the current version of the oEmbed spec. The other information returned depends largely on the value of type.
Response Types
The value of the type key in the response tells you what sort of media you’re going to be embedding.
Value of type What to expect photo A static photo that offers a url, width and height that can be used for a basic img tag video A video player, with html specifying the code required to embed a player on a page, although with a width and height link The best way to deal with this content is just to provide a link after all. The response might have other useful information like a title, but it should just be linked up. rich Some sort of rich content player, which just like the video type returns html, width and height
Aside from dedicated video content, the more common type you’re likely to see in the wild is rich. Even Flickr itself, while still sending a photo response, also supplies html for a rich embeddable ‘player’ for the image, too.
Most of the time, embedding the content in your site is just a case of using the code provided as the html value.
A Note On Security
One thing you might be rightly cautious of is taking an HTML response and embedding it programmatically into a page you host. Without the human step to double-check the code you’re pasting in, there is always potential for that code to be malicious. As such you should take appropriate steps to mitigate the risk.
That might include filtering the URLs to make sure the schemes and domains match those expected, and sandboxing code into an iframe on a different, cookieless domain. You should access the situation in which you’re using the code and make sure that you’re not exposing your self to undue risk.
Getting Started
As important as it is to understand the process when using oEmbed, the reality is that most common languages have libraries available that abstract away the process and make it relatively simple.
For example, the npm packaged oembed provides a very simple interface for making a request based on the content URL and getting the oEmbed response back in return.
First install the package into your project:
npm i oembed
And then request the URL. Here I’m using the URL of a presentation on Notist that I gave about oEmbed. How very meta.
const oembed = require('oembed'); const url = 'https://noti.st/drewm/ZOFFfI'; oembed.fetch(url, { maxwidth: 1920 }, function(error, result) { if (error) console.error(error); else console.log("oEmbed result", result); });
And the response:
{ type: 'rich', version: '1.0', title: 'Understanding oEmbed', author_name: 'Drew McLellan', author_url: 'https://noti.st/drewm', provider_name: 'Notist', provider_url: 'https://noti.st', cache_age: 604800, thumbnail_url: 'https://on.notist.cloud/slides/deck4179/large-0.png', thumbnail_width: 1600, thumbnail_height: 900, html: '<p data-notist="drewm/ZOFFfI">View <a href="https://noti.st/drewm/ZOFFfI">Understanding oEmbed</a> on Notist.</p><script async src="https://on.notist.cloud/embed/002.js"></script>', width: 960, height: 540 }
If you wanted to do the same in PHP, a handy package called embed/embed is available to install via Composer.
composer require embed/embed
And then in your PHP project:
use Embed\Embed; $info = Embed::create('https://noti.st/drewm/ZOFFfI'); $info->title; // "Understanding oEmbed" $info->authorName; // "Drew McLellan $info->code; // "<p data-notist="drewm/ZOFFfI"> ... </script>"
As you can see, with the use of a library the process becomes very simple and you can quickly get from a URL to the embed code, ready to show a rich representation of the user’s content.
Conclusion
oEmbed is a very elegant solution to a very specific problem. You’d be forgiven for thinking that only a few engineers working on big social networks would benefit from this, but in reality, publishing systems where a user might enter a URL are surprisingly common. Find me one back-end engineer who at some point hasn’t needed to build some kind of CMS. We may not think of it in the same terms, but if you accept user input, you should be thinking about what to do if that input contains URLs.
Now that you know about oEmbed (sorry) you’ve got no excuse not to give some serious consideration to how you handle URLs in your future projects.
oEmbed specification
oembed for NodeJS
embed/embed for PHP
“Announcing OEmbed: An Open Standard for Embedded Content,” Leah Culver
Tumblr media
(ra, il)
0 notes
kiasalehi · 6 years ago
Text
Talking About Your Own Work
Talking about your own work can be surprisingly difficult. Sometimes you don’t think to question why something is done a certain way until you have to explain it to someone else, at which point you realize you don’t fully understand what you were doing. Or, more commonly, you have an understanding of the nitty-gritty of a certain framework or library you were using but you aren’t practiced in giving a high-level overview of its purpose, pros and cons, and alternatives to someone who hasn’t worked with it extensively. This is why I love to teach -- and why I like to write blog posts ;) Both require you to put your thoughts into full sentences that give you a more complete and precise understanding of a topic you thought you already understood. 
So, I’m going to write about about my previous work at Houzz to practice just that!
Houzz has two codebases: it was originally built in PHP and jQuery, but has been migrating to an in-house frontend framework that uses Node and React. This frontend framework still makes service calls to the PHP codebase to fetch data, but has its own logic for routing, middleware, etc. Service calls are made using ApacheThrift, which no matter HOW MANY TIMES I explain to someone, I cannot remember a good one-sentence summary of. 
Ok, I looked it up for the 849th time, so here it is: 
Apache Thrift is an interface definition language and binary communication protocol developed by Facebook for “scalable cross-language services development”. (Source)
In other words, Thrift allowed our JavaScript frontend talk to our PHP backend and do type checking on the data that was passed back and forth. It also has the advantage of allowing for binary serialization, in addition to traditional options like JSON and XML. Binary encoding is much faster, making it an ideal choice when transferring data over internal networks (as we are when we make a service call to the backend). Overall, Thrift was a good choice for us because we needed to interface between two codebases in different languages, and speed was a priority. 
Thrift can also be described as an RPC (remote procedure call) framework, but there was hardly room in the definition for that so I am tacking it on now. What does that mean? RPC is a specification for how to interact a server, just like REST is. SOAP (Simple Object Access Protocol) is one implementation you may know that’s frequently juxtaposed with REST. RPC frameworks emphasize operations over resources. This table with some example RPC vs REST endpoints illustrates the point nicely (source):
Tumblr media
Thrift is an RPC framework because you interact with the server via operations (e.g., getVisitorHomepagePhotos), as opposed to interacting via resources and HTTP verbs (e.g., GET /photos?type=visitorHomepage).
So there you have it! I spent a while in the previous posts talking about GraphQL in comparison to REST, but my own work was actually integrating it with an RPC framework.
0 notes