How to get and set php.ini variables through terminal

I want to change some php.ini (php5.6) variables through the terminal. Example: I need to get the post_max_size value (that for now is 8M), display it in the terminal, change it to 2048M and display it again.

How could I do that?


Solution 1:

Get:

grep '^post_max_size ' php.ini

Replace:

sed -i 's,^post_max_size =.*$,post_max_size = 2048M,' php.ini

Note that it's a good idea to create a backup of php.ini before running sed:

cp php.ini php.ini.bak

Solution 2:

I assume you have the values in your php.ini stored one per line and separated by = with or without surrounding spaces. Neither the variable names nor the values contain a =.

To print the post_max_size value (choose one):

<php.ini awk -F"= *" '/^ *post_max_size/{print$2}'
<php.ini sed '/^ *post_max_size/!d;s/.*= *//'
<php.ini grep -oP '^ *post_max_size *= *\K.*'

To change the post_max_size value to 2048M creating a backup called php.ini.bak:

sed -i.bak '/^ *post_max_size/s/=.*/= 2048M/' php.ini

Explanations

  • <php.ini awk -F"= *" '/^ *post_max_size/{print$2}'
    • <php.ini – let the shell open php.ini and assign it to the program's stdin, this has a number of advantages, see here
    • -F"= *" – set = followed by zero or more space characters as the field delimiter
    • /^ *post_max_size/{print$2} – from the line beginning with post_max_size print field 2
  • <php.ini sed '/^ *post_max_size/!d;s/.*= *//'
    • /^ *post_max_size/!ddelete every line except the one beginning with post_max_size
    • s/.*= *//substitute everything before = and zero or more space characters after it by nothing (= delete it)
  • <php.ini grep -oP '^ *post_max_size *= *\K.*'
    • -oP – print only the matched parts of a matching line and use Perl-compatible regular expressions (PCRE)
    • ^ *post_max_size *= *\K.* – search for a line beginning with post_max_size and = surrounded by zero or more space characters, then remove the text matched so far from the overall regex match (\K) and match everything after it
  • sed -i.bak '/^ *post_max_size/s/=.*/= 2048M/' php.ini
    • -i.bak – change the file in place making a backup with the extension .bak
    • /^ *post_max_size/… – in the line beginning with post_max_size, do
    • s/=.*/= 2048M/substitute = and everything after it with = 2048M