PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 10, 2022

[FIXED] How to automatically switch php versions when cd'ing into another directory bash

 November 10, 2022     bash, composer-php, php     No comments   

Issue

I have multiple projects that I work on.

Some are on php 7.3, most of 7.4 and a single one on 8.1

Having to switch php everytime when I switch projects is a solution I have now, but sometimes I need to do a quick check on another project, and that breaks code running in another project because the global php are updated.

All my projects are composer based, but composer doesn't "spit out" what the most desired php version is.

How can I based on composer.json/lock detect the correct php version to use?


Solution

This script is made with php installed via ppa:ondrej/php. If your php versions are self compiled, and not linked in for example /usr/bin/php7.4 you'll need to modify the paths to the correct paths. This code however does assume the binaries are named php7.x or php8.x

This also requires that there is a composer installed on your system.

Add the following code to your .bashrc file.(nano ~/.bashrc) Explanations of what does what are in the comments in the code.

function do_php() {
    # Path where to find the php binaries
    PHPPATH='/usr/bin'
    
    # PHP versions in order of most used
    declare -a phpversions=("7.4" "7.3" "8.1" "8.0" "7.2" "7.1" "7.0");
    # Get a direct path to composer
    composer_path="$(whereis composer | cut -d  ' ' -f 2)"
    # Loop through all php versions
    for phpversion in "${phpversions[@]}"
      do
        PHP=$PHPPATH/php$phpversion
        # If the given php version is installed
        if [ -f $PHP ]; then
          # Check if it matches the requirements
          SUCCESS=$($PHP $composer_path check-platform-reqs 2>/dev/null | grep php | tr -s ' ' | cut -d ' ' -f 3)
           # If we're matching
           if [ "$SUCCESS" == "success" ]; then
              # Run command with given binary
              $PHP "$@"
              # exit function
              return
           fi
         fi
    done
    
    #Nothing matched, just run with default php and let the programmer deal with the issue
    \php "$@"
}

# Set the alias for php to do_php
alias php='do_php'


Answered By - Tschallacka
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing