Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP data://
The data:// wrapper in PHP allows you to embed data directly into your code using the data URI scheme defined in RFC 2397. This is useful for including inline data without external files.
Syntax
data:[media type][;base64],data
Parameters
media type − MIME type of the data (default: text/plain)
base64 − Optional encoding indicator for binary data
data − The actual data content, separated by a comma
Example 1: Basic String Encoding
This example encodes a string to base64 format and reads it using the data:// wrapper −
<?php
$string = "TutorialsPoint India (p) Ltd";
$b64 = base64_encode($string);
echo file_get_contents('data://text/plain;base64,' . $b64);
?>
TutorialsPoint India (p) Ltd
Example 2: Reading File Content
You can read content from a file and encode it using the data:// wrapper −
<?php
$string = file_get_contents("test.txt");
$b64 = base64_encode($string);
echo file_get_contents('data://text/plain;base64,' . $b64);
?>
Note: This example requires a file named "test.txt" to exist in the same directory.
Example 3: HTML Content
Using text/html as media type for HTML content −
<?php
$string = file_get_contents("test.html");
$b64 = base64_encode($string);
echo file_get_contents('data://text/html;base64,' . $b64);
?>
Example 4: Plain Text Without Encoding
You can use data:// without base64 encoding for simple text −
<?php
$data = "Hello World!";
echo file_get_contents('data://text/plain,' . urlencode($data));
?>
Hello World!
Conclusion
The data:// wrapper provides a convenient way to embed data directly in PHP code without external files. Use base64 encoding for binary data and URL encoding for plain text containing special characters.
