Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
Next article icon

How to receive JSON POST with PHP ?

Last Updated : 06 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to retrieve the JSON POST with PHP, & will also see their implementation through the examples. First, we will look for the below 3 features:

  • php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP headers of the request, regardless of the content type.
  • file_get_contents() function: This function in PHP is used to read a file into a string.
  • json_decode() function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object.

It is known that all of the post data can be received in a PHP script using the $_POST[] global variable. But this fails in the case when we want to receive JSON string as post data. To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

Handling JSON POST requests:

// Takes raw data from the request $json = file_get_contents('php://input');  // Converts it into a PHP object $data = json_decode($json);

Example 1: This example uses the json_decode() function that is used to decode a JSON string.

PHP




<?php
  $json = '["geeks", "for", "geeks"]';
  $data = json_decode($json);
  echo $data[0];
?>
 
 
Output: 
geeks

 

Example 2: This example uses the json_decode() function that is used to decode a JSON string.

PHP




<?php
  $json = '{
      "title": "PHP",
      "site": "GeeksforGeeks"
  }';
  $data = json_decode($json);
  echo $data->title;
  echo "\n";
  echo $data->site;
?>
 
 
Output: 
PHP GeeksforGeeks

 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Next Article
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?

A

Archana choudhary
Improve
Article Tags :
  • PHP
  • Web Technologies
  • JSON

Similar Reads

  • PHP Programs
    PHP Programs is a collection of coding examples and practical exercises designed to help beginners and experienced developers. This collection covers a wide range of questions based on Array, Stirng, Date, Files, ..., etc. Each programming example includes multiple approaches to solve the problem. W
    7 min read
  • PHP Basic Programs

    • Different ways to write a PHP code
      The full form of PHP is a Hypertext preprocessor. It was developed by Rasmus Lerdorf. It is a programming language for developing dynamic web applications and interactive websites. It is a server-side scripting language. It is used for establishing a connection between the front-end and database i.e
      2 min read

    • How to write comments in PHP ?
      Comments are non-executable lines of text in the code that are ignored by the PHP interpreter. Comments are an essential part of any programming language. It help developers to understand the code, provide explanations, and make the codebase more maintainable. Types of Comments in PHPPHP supports tw
      1 min read

    • Introduction to Codeignitor (PHP)
      Codeignitor is one of the popular MVC framework of PHP. Most of the developers prefer to make their projects on Codeignitor because of it's lightweight and easy to understand documentation. Some of the features, advantages or why use Codeignitor is given below. Why use Codeignitor? Fast and lightwei
      4 min read

    • How to echo HTML in PHP ?
      While making a web application with PHP, we often need to print or echo few results in form of HTML. We can do this task in many different ways. Some of methods are described here: Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables. Example 1: Th
      2 min read

    • Error handling in PHP
      Prerequisite: Types of Error PHP is used for web development. Error handling in PHP is almost similar to error handling in all programming languages. The default error handling in PHP will give file name line number and error type. Ways to handle PHP Errors: Using die() methodCustom Error Handling B
      3 min read

    • How to show All Errors in PHP ?
      We can show all errors in PHP using the error_reporting() function. It sets the error_reporting directive at runtime according to the level provided. If no level is provided, it will return the current error reporting level. error_reporting(E_ALL) level represents all errors, warnings, notices, etc.
      3 min read

    • How to Start and Stop a Timer in PHP ?
      You can start and stop a timer in PHP using the microtime() function in PHP. The microtime() function is an inbuilt function in PHP which is used to return the current Unix timestamp with microseconds. In this article, you will learn the uses of the microtime() function. Syntax: microtime( $get_as_f
      2 min read

    • How to create default function parameter in PHP?
      The default parameter concept comes from C++ style default argument values, same as in PHP you can provide default parameters so that when a parameter is not passed to the function. Then it is still available within the function with a pre-defined value. This function also can be called optional par
      1 min read

    • How to check if mod_rewrite is enabled in PHP ?
      In PHP, there is an inbuilt function called ‘phpinfo’. By using this function, we can output all the Loaded Modules and see the ‘mod_rewrite’ is enabled or not. Syntax: phpinfo(); Here is a process to check the ‘mod_rewrite’ load module is enabled or not. Note: The local server used here is XAMPP. C
      1 min read

    • Web Scraping in PHP Using Simple HTML DOM Parser
      Web Scraping is a technique used to extract large amounts of data from websites extracted and saved them to a local file in your computer or to a database or can be used as API. Data displayed by most websites can be viewed by using a web browser only. They do not offer the functionality to save a c
      2 min read

    • How to pass form variables from one page to other page in PHP ?
      Form is an HTML element used to collect information from the user in a sequential and organized manner. This information can be sent to the back-end services if required by them, or it can also be stored in a database using DBMS like MySQL. Splitting a form into multiple steps or pages allow better
      4 min read

    • How to display logged in user information in PHP ?
      In social networking websites like Facebook, Instagram, etc, the username and profile picture of the user that has logged in gets displayed in the header of the website, and that header remains constant, irrespective of the webpage the user has opened. Such functionality can be created by using the
      10 min read

    • How to find out where a function is defined using PHP ?
      When we do projects then it includes multiple modules where each module divided into multiple files and each file containing many lines of code. So when we declare a function somewhere in the files and forget that what the function was doing or want to change the code of that function but can't find
      3 min read

    • How to Get $_POST from multiple check-boxes ?
      $_POST is an array of variable names. The program given below illustrates how to write HTML structure for multiple valued checkbox and to get the values of multiple valued checkbox using $_POST in PHP. Note: The name attribute of checkboxes must be the same name and must be initialized with an array
      2 min read

    • How to Secure hash and salt for PHP passwords ?
      Salting and hashing is a technique to store the password in a database. In cryptography, salting means to add some content along with the password and then hashing it. So salt and hash provide two levels of security. Salting always makes unique passwords i.e if there are two same passwords, after sa
      2 min read

    • How to detect search engine bots with PHP ?
      Search engine bots (sometimes called spiders or crawlers) are computer programs(bots) that crawl the web pages. In other words, they visit webpages, find links to further pages, and visit them. Often they map content that they find to use later for search purposes (indexing). They also help develope
      2 min read

    • How to set PHP development environment in windows ?
      What is PHP ? PHP (Hypertext PreProcessor) is a general-purpose programming language developed by Rasmus Lerdorf in 1994 for web development. This is one of the most popular programming language for beginners in web development because of its simplicity, large community and accessibility.Steps to se
      3 min read

    • How to turn off PHP Notices ?
      In PHP, Notices are the undefined variables indicated in the PHP project on a set of lines or particular lines. It usually does not affect or break the functionality of the code written. When PHP notices detect errors, it will display like this: PHP Notice: Use of undefined constant name - assumed '
      2 min read

    • What does '<?=' short open tag mean in PHP ?
      The <php is used to identify the start of a PHP document. In PHP whenever it reads a PHP document, It looks for: <?php ?> It process the codes in between the above tags only and leaves the other codes around them. For example : <?php echo "Hello PHP !"; ?> Output: Hello PHP
      2 min read

    PHP Array Programs

    • Program to Insert new item in array on any position in PHP
      New item in an array can be inserted with the help of array_splice() function of PHP. This function removes a portion of an array and replaces it with something else. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specifi
      4 min read

    • PHP append one array to another
      Given two array arr1 and arr2 and the task is to append one array to another array. Examples: Input : arr1 = [ 1, 2 ] arr2 = [ 3, 4 ] Output : arr1 = [ 1, 2, 3, 4 ] Input : arr1 = [ "Geeks", "g4g" ] arr2 = [ "GeeksforGeeks" ] Output : arr1 = [ "Geeks", "g4g", "GeeksforGeeks" ] Using array_merge func
      2 min read

    • How to delete an Element From an Array in PHP ?
      To delete an element from an array means to remove a specific value or item from the array, shifting subsequent elements to the left to fill the gap. This operation adjusts the array's length accordingly, eliminating the specified element. This article discusses some of the most common methods used
      4 min read

    • How to print all the values of an array in PHP ?
      We have given an array containing some array elements and the task is to print all the values of an array arr in PHP. In order to do this task, we have the following approaches in PHP: Table of Content Using for-each loop: Using count() function and for loop: Using implode():Using print_r() Function
      3 min read

    • How to perform Array Delete by Value Not Key in PHP ?
      An array is essentially a storage element for key-value pairs belonging to the same data type. If keys are specified explicitly, ids beginning from 0 as assigned to the values by the compiler on their own. Arrays allow a large variety of operations, like access, modification, and deletion upon the s
      6 min read

    • Removing Array Element and Re-Indexing in PHP
      In order to remove an element from an array, we can use unset() function which removes the element from an array, and then use array_values() function which indexes the array numerically automatically. Function Usedunset(): This function unsets a given variable. Syntax:void unset ( mixed $var [, mix
      2 min read

    • How to count all array elements in PHP ?
      We have given an array containing some array elements and the task is to count all elements of an array arr using PHP. In order to do this task, we have the following methods in PHP: Table of Content Using count() MethodUsing sizeof() MethodUsing a loopUsing iterator_count with ArrayIteratorUsing ar
      4 min read

    • How to insert an item at the beginning of an array in PHP ?
      Arrays in PHP are a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed
      5 min read

    • PHP Check if two arrays contain same elements
      In this article, we will see how to compare the elements of arrays in PHP, & will know how to apply to get the result after comparison through the examples. In PHP, there are two types of arrays, Indexed array and Associative array. In an Indexed array, the array elements are index numerically s
      4 min read

    • Merge two arrays keeping original keys in PHP
      Merging two arrays in PHP while preserving the original keys can be done using the array_merge or array_replace functions, depending on the desired behavior. Below are the methods to merge two arrays while keeping the original keys in PHP: Table of Content Using + operatorUsing inbuilt array_replace
      4 min read

    • PHP program to find the maximum and the minimum in array
      Finding the maximum and minimum in an array involves determining the largest and smallest values within a given set of numbers. This task is crucial for analyzing data, identifying trends, or filtering outliers. Various methods, from simple traversal to optimized algorithms, can achieve this.Example
      7 min read

    • How to check a key exists in an array in PHP ?
      We have given an array arr and a Key key, the task is to check if a key exists in an array or not in PHP. Examples: Input : arr = ["Geek1", "Geek2", "1", "2","3"] key = "2"Output : Found the KeyInput : arr = ["Geek1", "Geek2", "1", "2","3"] key = 9Output : Key not FoundThe problem can be solved usin
      3 min read

    • PHP Second most frequent element in an array
      Given an array we have to find the second most frequent element present in it. Examples: Input : array(3, 3, 4, 5, 5, 5, 9, 8, 8, 8, 8, 8); Output : Second most frequent element is: 5 Input : array("geeks", "for", "geeks"); Output : Second most frequent element is: for Here are some common approache
      4 min read

    • Sort array of objects by object fields in PHP
      Sorting an array of objects by object fields means organizing the array's objects based on the values of specified properties (fields) within each object, typically in ascending or descending order, to arrange the data meaningfully. Here we have some common approaches: Table of Content Using usort()
      4 min read

    • PHP Sort array of strings in natural and standard orders
      You are given an array of strings. You have to sort the given array in standard way (case of alphabets matters) as well as natural way (alphabet case does not matter). Input : arr[] = {"Geeks", "for", "geeks"}Output : Standard sorting: Geeks for geeks Natural sorting: for Geeks geeks Input : arr[] =
      2 min read

    • PHP | Print the last value of an array without affecting the pointer
      We are given an array with key-value pair, and we need to find the last value of array without affecting the array pointer. Examples: Input : $arr = array('c1' => 'Red', 'c2' => 'Green', 'c3' => 'Blue', 'c4' => 'Black') Output : Black Input : $arr = array('p1' => 'New York', 'p2' =
      2 min read

    • How to merge the first index of an array with the first index of second array?
      The task is to merge the first index of an array with the first index of another array. Suppose, an array is array1 = {a, b, c} and another array is array2 = {c, d, e} if we perform the task on these arrays then the output will be  result array { [0]=> array(2) { [0]=> string(1) "a" [1]=> s
      4 min read

    • How to create a string by joining the array elements using PHP ?
      We have given an array containing some array elements and the task is to join all the array elements to make a string. In order to do this task, we have the following methods in PHP: Table of Content Using implode() Method: Using join() MethodUsing array_reduce()Using a Foreach LoopUsing array_map()
      4 min read

    • How to sort an Array of Associative Arrays by Value of a Given Key in PHP ?
      Each entry in the associative array is characterized by a unique key-value pair. An array can contain singular data types belonging to variables or other arrays as its elements. There are multiple ways to sort an array of associative arrays by the value of a specified key. Table of Content Using the
      6 min read

    • How to make a leaderboard using PHP ?
      The purpose of this article is to make a simple program to create a leaderboard using PHP. Below is the implementation for the same using PHP. The prerequisites of this topic are PHP/MySQL and the installment of Apache Server on your computer. Approach: Step 1: First we will create a HTML table usin
      2 min read

    • How to check an array is multidimensional or not in PHP ?
      Given an array (single-dimensional or multi-dimensional) the task is to check whether the given array is multi-dimensional or not. Below are the methods to check if an array is multidimensional or not in PHP: Table of Content Using rsort() functionUsing Nested foreach LoopUsing a Recursive FunctionU
      4 min read

    • Multidimensional Associative Array in PHP
      PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation. Creation: We can crea
      4 min read

    • How to merge the duplicate value in multidimensional array in PHP?
      To merge the duplicate value in a multidimensional array in PHP, first, create an empty array that will contain the final result. Then we iterate through each element in the array and check for its duplicity by comparing it with other elements. If duplicity is found then first merge the duplicate el
      4 min read

    • Convert multidimensional array to XML file in PHP
      Given a multi-dimensional array and the task is to convert this array into an XML file. To converting the multi-dimensional array into an xml file, create an XML file and use appendChild() and createElement() function to add array element into XML file. Example: First, create a PHP Multidimensional
      2 min read

    • How to search by multiple key => value in PHP array ?
      In a multidimensional array, if there is no unique pair of key => value (more than one pair of key => value) exists then in that case if we search the element by a single key => value pair then it can return more than one item. Therefore we can implement the search with more than one key =
      5 min read

    • How to search by key=>value in a multidimensional array in PHP ?
      In PHP, multidimensional array search refers to searching a key=>value in a multilevel nested array. This search can be done either by the iterative or recursive approach. Table of Content Recursive ApproachIterative ApproachUsing array_filter() FunctionRecursive Approach:Check if the key exists
      4 min read

    • PHP program to find the Standard Deviation of an array
      Given an array of elements. We need to find the Standard Deviation of the elements of the array in PHP. Examples: Input : array(2, 3, 5, 6, 7)Output : 1.5620499351813Input : array(1, 2, 3, 4, 5)Output : 1 The following problem can be solved using the PHP inbuilt functions. The inbuilt functions used
      2 min read

    • PHP program to check for Anagram
      An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. To check for anagrams in PHP, remove spaces, convert to lowercase, sort characters, and compare the sorted strings or arrays. Examples Input : "anagram", "nagaram"
      5 min read

    PHP Function Programs

    • How to pass PHP Variables by reference ?
      By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn't have any effect on either of the variables. Examp
      2 min read

    • How to format Phone Numbers in PHP ?
      In this article, we will learn how to format phone numbers using PHP. When we need to store a phone number then we store the formatting phone number. Using PHP, we can easily format phone numbers. Approach: In this article, we will format the phone number using the preg_match() method. We can use th
      1 min read

    • serialize() and unserialize() in PHP
      In PHP, complex data like arrays or objects can't be stored easily. If you want to keep or use this data across different parts of your script or even after the script ends, the serialize() and unserialize() functions are very helpful. The serialize() function turns complex data into a string format
      3 min read

    • PHP Callback Functions
      In PHP, the callback functions are related to the dynamic behavior and flexibility in code execution. They are used to pass custom logic or functions as arguments to other functions, letting developers change how a function behaves without changing its main structure. This makes the code more reusab
      5 min read

    • PHP Merging two or more arrays using array_merge()
      The array_merge() function in PHP combines two or more arrays into one. It merges the values from the arrays in the order they are passed. If arrays have duplicate string keys, the latter values overwrite earlier ones, while numerical keys are re-indexed sequentially. Syntaxarray array_merge($array1
      2 min read

    • PHP program to print an arithmetic progression series using inbuilt functions
      We have to print an arithmetic progressive series in PHP, between two given numbers a and b both including, a given common arithmetic difference of d. Examples: Input : $a = 200, $b = 250, $d = 10 Output : 200, 210, 220, 230, 240, 250 Input : $a = 10, $b = 100, $d = 20 Output : 10, 30, 50, 70, 90Thi
      2 min read

    • How to prevent SQL Injection in PHP ?
      In this article, we are going to discuss how to prevent SQL injection in PHP. The prerequisite of this topic is that you are having XAMPP in your computer. Why SQL injection occurs? SQL injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements
      3 min read

    • How to extract the user name from the email ID using PHP ?
      Given a string email address, extract the username. Input: ‘[email protected]’ Output: priyank Input: ‘[email protected]’ Output: princepriyank Approach 1: Using PHP strstr() to extract the username from the email address. In this, “@” symbol is the separator for the domain name and user name of
      2 min read

    • How to count rows in MySQL table in PHP ?
      PHP stands for hypertext preprocessor. MySQL is a database query language used to manage databases. In this article, we are going to discuss how to get the count of rows in a particular table present in the database using PHP and MySQL. Requirements: XAMPP Approach: By using PHP and MySQL, one can p
      3 min read

    • How to parse a CSV File in PHP ?
      In this article, we learn to parse a CSV file using PHP code, along with understanding its basic implementation through examples.   Approach: The following approach will be utilized to parse the CSV File using PHP, which is described below: Step 1. Add data to an Excel file. The following example is
      3 min read

    • How to generate simple random password from a given string using PHP ?
      In this article, we will see how to generate a random password using the given string. We have given a string and the task is to generate a random password from it. Example: Input: abgADKL123 Output: abgADKL123 Input: geeksforgeeks Output: egksegsfroeke To achieve this, we use the following approach
      3 min read

    • How to upload images in MySQL using PHP PDO ?
      In this article, we will upload images to the MySQL database using PHP PDO and display them on the webpage.  Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this tutorial, we will be using the WAMP server. Article content: Table StructureDatabase configuratio
      5 min read

    • How to check foreach Loop Key Value in PHP ?
      In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such as Table of Content Using the for-each loop with simple valuesUsing the foreach loop with Key-Value pairsUsing array_keys Function to Access Keys and ValuesUsing array_walk Function for Iteration
      3 min read

    • How to properly Format a Number With Leading Zeros in PHP ?
      A number is essentially a sequence of digits stacked together to form an integer or string. A number can begin with leading zeros. A number can also be looped through and modifications can be made to append or concatenate another sequence of characters into it. Approach 1: Using a for loop for strin
      4 min read

    • How to get a File Extension in PHP ?
      In this article, we will learn how to get the current file extensions in PHP. Input : c:/xampp/htdocs/project/home Output : "" Input : c:/xampp/htdocs/project/index.php Output : ".php" Input : c:/xampp/htdocs/project/style.min.css Output : ".css" Using $_SERVER[‘SCRIPT_NAME’]: $_SERVER is an array o
      2 min read

    • Build a Grocery Store Web App using PHP with MySQL
      In this article, we are going to build a Grocery Store Web Application using PHP with MySQL. In this application, we can add grocery items by their name, quantity, status (pending, bought, not available), and date. We can view, delete and update those items. There will be a date filtering feature wh
      7 min read

    • How to delete text from file using preg_replace() function in PHP ?
      Given a file containing some elements and the task is to delete the content of the file using preg_replace() function. The preg_replace() function is searches the string pattern in the file and if string pattern found then it replace with the required string. In simple words it can modify the conten
      2 min read

    PHP Date Programs

    • How to get the current Date and Time in PHP ?
      To get the current date and time in PHP, use the date() function, which formats UNIX timestamps into a human-readable format. It converts timestamps, measured in seconds since January 1, 1970, into a more understandable representation for users. Syntax: date('d-m-y h:i:s');Parameters: The date() has
      2 min read

    • PHP program to change date format
      You are given a string which contain date and time. Date in dd/mm/yyyy format and time in 12 hrs format.You have to convert date in yyyy/mm/dd format and time in 24 hrs format. Examples: Input : $date = "12/05/2018 10:12 AM" Output : 2018-05-12 10:12:00 Input : $date = "06/12/2014 04:13 PM" Output :
      1 min read

    • How to convert DateTime to String using PHP ?
      Converting a `DateTime` to a string in PHP involves formatting the `DateTime` object into a human-readable format using the `format()` method. This process allows you to represent dates and times as strings in various formats, such as Y-m-d H:i:s. There are some following approaches Table of Content
      4 min read

    • How to get Time Difference in Minutes in PHP ?
      In this article, we will learn how to get time difference in minutes using PHP. We will be using the built-in function date_diff() to get the time difference in minutes. For this, we will be needed a start date and end date to calculate their time difference in minutes using the date_diff() function
      3 min read

    • Return all dates between two dates in an array in PHP
      Returning all dates between two dates in an array means generating a list of all consecutive dates from the start date to the end date, inclusive, and storing each date as an element in an array for easy access. Here we have some common methods: Table of Content Using DatePeriod ClassUsing strtotime
      5 min read

    • Sort an array of dates in PHP
      We are given an array of multiple dates in (Y-m-d) format. We have to write a program in PHP to sort all the dates in the array in decreasing order. Examples : Input : array("2018-06-04", "2014-06-08", "2018-06-05") Output : 2018-06-05 2018-06-04 2014-06-08 Input : array("2016-09-12", "2009-09-08",
      2 min read

    • Return all dates between two dates in an array in PHP
      Returning all dates between two dates in an array means generating a list of all consecutive dates from the start date to the end date, inclusive, and storing each date as an element in an array for easy access. Here we have some common methods: Table of Content Using DatePeriod ClassUsing strtotime
      5 min read

    • How to convert a Date into Timestamp using PHP ?
      The Task is to convert a Date to a timestamp using PHP. The task can be done by using the strtotime() function in PHP. It is used to convert English textual date-time description to a UNIX timestamp. The UNIX timestamp represents the number of seconds between a particular date and the Unix Epoch. Sy
      1 min read

    • How to Add 24 Hours to a Unix Timestamp in PHP?
      The Unix Timestamp is designed to track time as a running total of seconds from the Unix Epoch on January 1st, 1970 at UTC. To add 24 hours to a Unix timestamp we can use any of these methods: Approach 1: Direct Addition of SecondsConvert 24 hours to seconds and add the result to the current Unix ti
      2 min read

    • Sort a multidimensional array by date element in PHP
      Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements. Syntax:
      2 min read

    • Convert timestamp to readable date/time in PHP
      Problem: Convert timestamp to readable date/time in PHP Solution: This can be achieved with the help of date() function, which is an inbuilt function in PHP can be used to format the timestamp given by time() function. This function returns a string formatted according to the given format string usi
      1 min read

    • PHP | Number of week days between two dates
      You are given two string (dd-mm-yyyy) representing two date, you have to find number of all weekdays present in between given dates.(both inclusive) Examples: Input : startDate = "01-01-2018" endDate = "01-03-2018" Output : Array ( [Monday] => 9 [Tuesday] => 9 [Wednesday] => 9 [Thursday] =
      2 min read

    • PHP | Converting string to Date and DateTime
      Converting the string to Date and DateTime uses several functions/methods like strtotime(), getDate(). We will see what these functions do. strtotime() This is basically a function which returns the number of seconds passed since Jan 1, 1970, just like a linux machine timestamp. It returns the numbe
      2 min read

    • How to get last day of a month from date in PHP ?
      Given a date and the task is to print the last day of the month. We will use date() and strtotime() function to get the last day of the month. Used PHP functions: date() function: Format a local time/date.strtotime() function: Parse about any English textual datetime description into a Unix timestam
      2 min read

    PHP String Programs

    • PHP Change strings in an array to uppercase
      Changing strings in an array to uppercase means converting all the string elements within the array to their uppercase equivalents. This transformation modifies the array so that every string, regardless of its original case, becomes fully capitalized. Examples: Input : arr[] = ("geeks", "For", "GEE
      3 min read

    • How to convert first character of all the words uppercase using PHP ?
      To convert the first character of all the words present in a string to uppercase, we just need to use one PHP function i.e. ucwords(). ucwords(string,delimiters)This function takes 2 parameters. The first one is the string which is mandatory. The second parameter is the delimiter. Example 1: [GFGTAB
      3 min read

    • How to get the last character of a string in PHP ?
      In this article, we will find the last character of a string in PHP. The last character can be found using the following methods. Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is "Akshit" Its length is 6, i
      2 min read

    • How to convert uppercase string to lowercase using PHP ?
      Converting an uppercase string to lowercase means changing all capital letters in the string to their corresponding small letters. This is typically done using programming functions or methods to ensure uniformity in text formatting and comparison. Below we have some common approaches Table of Conte
      2 min read

    • How to extract Numbers From a String in PHP ?
      Extracting numbers from a string involves identifying and isolating numerical values embedded within a text. This process can be done using programming techniques, such as regular expressions, to filter out and retrieve only the digits from the string, ignoring all other characters. Here we have som
      3 min read

    • How to replace String in PHP ?
      Replacing a string in PHP involves substituting parts of a string with another string. Common methods include str_replace() for simple replacements, preg_replace() for pattern-based replacements, substr_replace() for positional replacements, and str_ireplace() for case-insensitive replacements. Each
      3 min read

    • How to Encrypt and Decrypt a PHP String ?
      In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt. openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data. Syntax: string openssl_encrypt( string $data, string $method, st
      4 min read

    • How to display string values within a table using PHP ?
      A table is an arrangement of data in rows and columns, or possibly in a more complex structure. Tables are widely used in communication, research, and data analysis. Tables are useful for various tasks such as presenting text information and numerical data.Tables can be used to compare two or more i
      1 min read

    • How to write Multi-Line Strings in PHP ?
      Multi-Line Strings can be written in PHP using the following ways. Using escape sequencesWe can use the \n escape sequences to declare multiple lines in a string. PHP Code: [GFGTABS] PHP <?php //declaring multiple lines using the new line escape sequence $var="Geeks\nFor\nGeeks"; echo $
      2 min read

    • How to check if a String Contains a Substring in PHP ?
      Checking whether a string contains a specific substring is a common task in PHP. Whether you're parsing user input, filtering content, or building search functionality, substring checking plays a crucial role. MethodsBelow are the following methods by which we can check if a string contains a substr
      1 min read

    • How to append a string in PHP ?
      We have given two strings and the task is to append a string str1 with another string str2 in PHP. There is no specific function to append a string in PHP. In order to do this task, we have the this operator in PHP: Table of Content Using Concatenation assignment operator (".=")Using Concatenation O
      4 min read

    • How to remove white spaces only beginning/end of a string using PHP ?
      We have given a string and the task is to remove white space only from the beginning of a string or the end from a string str in PHP. In order to do this task, we have the following methods in PHP: Table of Content Using ltrim() MethodUsing rtrim() MethodUsing a Custom Regular Expression with preg_r
      3 min read

    • How to Remove Special Character from String in PHP?
      We are given a string and the task is to remove special characters from string str in PHP. Below are the approaches to remove special characters from string in PHP: Table of Content Using str_replace() MethodUsing str_ireplace() MethodUsing preg_replace() MethodUsing str_replace() MethodThe str_repl
      2 min read

    • How to create a string by joining the array elements using PHP ?
      We have given an array containing some array elements and the task is to join all the array elements to make a string. In order to do this task, we have the following methods in PHP: Table of Content Using implode() Method: Using join() MethodUsing array_reduce()Using a Foreach LoopUsing array_map()
      4 min read

    • How to prepend a string in PHP?
      We have given two strings and the task is to prepend a string str1 with another string str2 in PHP. There is no specific function to prepend a string in PHP. To do this task, we have the following operators in PHP: Below are the methods to prepend a string in PHP Table of Content Using Concatenation
      2 min read

    • How to replace a word inside a string in PHP ?
      Given a string containing some words the task is to replace all the occurrences of a word within the given string str in PHP. To do this task, we have the following methods in PHP: Table of Content Using str_replace() MethodUsing str_ireplace() Method Using preg_replace() MethodUsing strtr()Using pr
      4 min read

    • How to remove all white spaces from a string in PHP ?
      Given a string element containing some spaces and the task is to remove all the spaces from the given string str in PHP. In order to do this task, we have the following methods in PHP: Table of Content Using str_replace() MethodUsing str_ireplace() MethodUsing preg_replace() MethodUsing explode() an
      4 min read

    • How to count the number of words in a string in PHP ?
      Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches: Table of Content Using str_word_count() MethodUsing trim(), preg_replace(), count() and explode() method. Using trim(), substr_count(), an
      4 min read

    • How to find number of characters in a string in PHP ?
      We have given a string and the task is to count number of characters in a string str in PHP. In order to do this task, we have the following methods in PHP: Table of Content Method 1: Using strlen() MethodMethod 2: Using mb_strlen() MethodMethod 3: Using iconv_strlen() MethodMethod 4: Using grapheme
      3 min read

    • How to get a substring between two strings in PHP?
      To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples: Input:$string="hey, How are you?"If we need to extract the substring between "How" and "you" then the output should be are Output:"Are"Input:Hey, Welcome to Geeks
      5 min read

    • How to get a variable name as a string in PHP?
      Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below: Table of Content Using $GLOBALSUsing $$ OperatorUsing debug_backtrace()Using get_defined_vars() and array_search()Method 1: Using $GLOBALS: It is used to reference all
      3 min read

    • Removing occurrences of a specific character from end of a string in PHP
      There is a lot of options to remove all specific characters at the end of a string. Some of them are discussed below: Using rtrim() functionThis function is an inbuilt function in PHP that removes whitespaces or other characters (if specified) from the right side of the string. Syntax: rtrim( $strin
      3 min read

    • How to convert string to boolean in PHP?
      Given a string and the task is to convert given string to its boolean. Use filter_var() function to convert string to boolean value. Examples: Input : $boolStrVar1 = filter_var('true', FILTER_VALIDATE_BOOLEAN); Output : true Input : $boolStrVar5 = filter_var('false', FILTER_VALIDATE_BOOLEAN); Output
      2 min read

    • Generating Random String Using PHP
      Generating a random string involves creating a sequence of characters where each character is selected unpredictably from a defined set (e.g., letters, numbers, symbols). This process is used in programming to produce unique identifiers, passwords, tokens, or keys for security and randomness in appl
      2 min read

    • How to generate a random, unique, alphanumeric string in PHP
      There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Table of Content Using str_shuffle() FunctionUsing md5() FunctionUsing sha1() FunctionUsing random_bytes() FunctionUsing random_int() in a Custom FunctionUsing uniqid() with more_entropy parameterUsin
      4 min read

    • Remove new lines from string in PHP
      Given a multiple line sentence or statement the task is to convert the whole statement in a single line. See the example below. Examples: Input : Hello welcome to geeksforgeeks.Output : Hello welcome to geeksforgeeks.Remove the new line between Hello and geeksforgeeks.Input : I love geeksforgeeksOut
      2 min read

    • Insert string at specified position in PHP
      Given a sentence, a string and the position, the task is to insert the given string at the specified position. We will start counting the position from zero. See the examples below. Input : sentence = 'I am happy today.' string = 'very' position = 4 Output :I am very happy today. Input : sentence =
      3 min read

    • PHP Program to check a string is a rotation of another string
      Given the two strings we have to check if one string is a rotation of another string. Examples: Input : $string1 = "WayToCrack", $string2 = "CrackWayTo"; Output : Yes Input : $string1 = "WillPower" $string2 = "lliW"; Output : No. The above problem can be easily solved in other languages by concatena
      3 min read

    PHP Classes Programs

    • PHP Access Modifiers
      In object-oriented programming, access specifiers are also known as access modifiers. These specifiers control how and where the properties or methods of a class can be accessed, either from inside the class, from a subclass, or from outside the class. PHP supports three primary access specifiers: p
      3 min read

    • PHP | Constructors and Destructors
      In PHP, constructors and destructors are special methods that are used in object-oriented programming (OOP). They help initialize objects when they are created and clean up resources when the object is no longer needed. These methods are part of the class lifecycle. In this article, we will discuss
      5 min read

    • PHP | Type Casting and Conversion of an Object to an Object of other class
      Given a PHP class object and the task is to convert or cast this object into object of another class. Approach 1: Objects which are instances of a standard pre-defined class can be converted into object of another standard class. Example: <?php // PHP program to show // standard type casting $a =
      3 min read

    • PHP | Type Casting and Conversion of an Object to an Object of other class
      Given a PHP class object and the task is to convert or cast this object into object of another class. Approach 1: Objects which are instances of a standard pre-defined class can be converted into object of another standard class. Example: <?php // PHP program to show // standard type casting $a =
      3 min read

    • How to merge two PHP objects?
      Merging two PHP objects means combining their properties and values into a single object. This is typically done by copying the properties from one object to another, ensuring that both objects' data are preserved in the resulting merged object without overwriting critical values. Here we have some
      2 min read

    • Abstract Classes in PHP
      Abstract classes in PHP are classes that may contain at least one abstract method. Unlike C++, abstract classes in PHP are declared using the abstract keyword. The purpose of abstract classes is to enforce that all derived classes implement the abstract methods declared in the parent class. An abstr
      2 min read

    PHP JSON Programs

    • How to parse a JSON File in PHP?
      We will explore how to parse a JSON file and display its data using PHP. PHP is a server-side scripting language commonly used to process and manipulate data. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for both humans and machines to read and write. It st
      3 min read

    • How to generate Json File in PHP ?
      In this article, we are going to generate a JSON file in PHP by using an array. JSON stands for JavaScript object notation, which is used for storing and exchanging data. JSON is text, written with JavaScript object notation. Structure: {"data":[ { "sub_data1":"value1", "sub_data2":"value2","sub_dat
      3 min read

    • How to Convert JSON file into CSV in PHP ?
      In this article, we are going to see how to convert JSON data into a CSV file using PHP. JSON (JavaScript Object Notation) is a dictionary-like notation that can be used to structuring data. It is stored with the extension .json, for example - geeksforgeeks.json On the other hand, CSV (or Comma Sepa
      2 min read

    • How to Convert XML data into JSON using PHP ?
      In this article, we are going to see how to convert XML data into JSON format using PHP. Requirements: XAMPP Server Introduction: PHP stands for hypertext preprocessor, which is used to create dynamic web pages. It also parses the XML and JSON data. XML stands for an extensible markup language in wh
      3 min read

    • How to Insert JSON data into MySQL database using PHP?
      To insert JSON data into MySQL database using PHP, use the json_decode function in PHP to convert JSON object into an array that can be inserted into the database. Here, we are going to see how to insert JSON data into MySQL database using PHP through the XAMPP server in a step-by-step way. JSON Str
      3 min read

    • How to convert PHP array to JavaScript or JSON ?
      PHP provides a json_encode() function that converts PHP arrays into JavaScript. Technically, it is in JSON format. JSON stands for JavaScript Object Notation. Statement: If you have a PHP array and you need to convert it into the JavaScript array so there is a function provided by PHP that will easi
      2 min read

    • How to receive JSON POST with PHP ?
      In this article, we will see how to retrieve the JSON POST with PHP, & will also see their implementation through the examples. First, we will look for the below 3 features: php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data
      2 min read

    • How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
      In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are g
      2 min read

    PHP File Systems Programs

    • How to Create a Folder if It Doesn't Exist in PHP ?
      We can easily create a folder in PHP, but before that, you have to check if the folder or directory already exists or not. So In this article, you will learn both to Check and Create a folder or directory in PHP.  Methods: file_exists(): It is an inbuilt function that is used to check whether a file
      3 min read

    • How to check if File Exists in PHP ?
      To check whether any file is existing or not then we can use the below-mentioned PHP function. To find the existence of the files, we use file_exists() function. This function is used to check whether a file or directory exists or not. Syntax: file_exists( $path ) Parameters: This function accept on
      1 min read

    • How to write Into a File in PHP ?
      In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function. The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file
      2 min read

    • Deleting all files from a folder using PHP
      In PHP, files from a folder can be deleted using various approaches and inbuilt methods such as unlink, DirectoryIterator and DirectoryRecursiveIterator. Some of these approaches are explained below: Approach 1: Generate a list of files using glob() method Iterate over the list of files. Check wheth
      3 min read

    • How to get file name from a path in PHP ?
      In this article, we will see how to get the file name from the path in PHP, along with understanding its implementation through the examples. We have given the full path & we need to find the file name from the file path. For this, we will following below 2 methods: Using the basename() function
      2 min read

    • How to Log Errors and Warnings into a File in PHP?
      In PHP, errors and warnings can be logged into a file by using a PHP script and changing the configuration of the php.ini file. Two such approaches are mentioned below: Approach 1: Using error_log() FunctionThe error_log() function can be used to send error messages to a given file. The first argume
      3 min read

    • How to extract extension from a filename using PHP ?
      In this article, we will see how to extract the filename extension in PHP, along with understanding their implementation through the examples. There are a few different ways to extract the extension from a filename with PHP, which is given below: Using pathinfo() function: This function returns info
      2 min read

    • How to get names of all the subfolders and files present in a directory using PHP?
      Given the path of the folder and the task is to print the names of subfolders and files present inside them. Explanation: In our PHP code, initially, it is checked whether provided path or filename is a directory or not using the is_dir() function. Now, we open the directory using opendir() function
      2 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences