Php executable path setting

Как задать правильный путь в VSCode phpvalidateexecutablePath?

Доброго времени суток, столкнулся со следующей ситуацией. Изучаю PHP (7.1), пишу в Visual Studio Code и использую OpenServer, до недавнего времени не испытывал нужды в отладке и терминале, игнорировав их. Сейчас начал работу с Composer, библиотеками и фреймворками, так что потребность в терминале и отладке появилась. Установил расширение PHP Debug, Xdebug вроде как тоже(Потом оказалось, что он и так предустановлен в ОпенСервере). Все, что требуется, исправил в php.ini и settings.json, но VSC все время выбивает следующее: «Не удается проверить, так как C:\Users\имяпользователя\Program Files (x86)\OpenServer\modules\php\PHP_7.1\php.exe не является допустимым исполняемым PHP-файлом. Используйте параметр php.validate.executablePath, чтобы настроить исполняемый PHP-файл». Бьюсь без преувеличения третий день. Сама строчка в settings.json выглядит так:

"php.validate.executablePath": "C:\\Users\\имяюзера\\Program Files (x86)\\OpenServer\\modules\\php\\PHP_7.1\\php.exe"

Если допустить, что я не накосячил в момент указания пути (несколько раз указывал по-всякому — без толку) и что моя версия PHP в Опенсервере совпадает с папкой, на которую я ссылаюсь (Вроде по всем прошелся — итог один), то на ум приходит только один вариант — OpenServer не дает студии обратиться к папкам у себя без прав администратора. Окей, исправил в свойствах корневой папки OpenServer-a доступ так, что теперь (вроде как) он работает и без прав админа, но Код все еще не может получить доступ. Летом с Питоном таких проблем не было, в json файле все еще висит

"python.pythonPath": "C:\\Users\\имяюзера\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe"

— и никто не ругается, всё работает. Буду очень признателен за помощь, ибо никаких рабочих рекомендаций для себя не нашел.
upd: решение более-менее найдено, если у кого схожая проблема, смотрите комментарии

Простой 7 комментариев

Источник

Set PHP Path in Ubuntu: A Comprehensive Guide with Code Examples

Learn how to set PHP path in Ubuntu with step-by-step instructions and code examples. Install PHP, edit .bash_profile file, and configure php.ini effortlessly. Try it now!

  • Finding the Default Executable Path of PHP in Ubuntu
  • Setting the PHP Path in the rc file, ~/.bashrc
  • Editing the .bash_profile file to Change the Default PHP Command Path
  • Setting the PHP Executable Path in VS Code
  • Installing PHP on Ubuntu and Setting up a Local Programming Environment
  • Editing the php.ini File in Ubuntu to Change PHP Configurations
  • Installing and Switching Between Multiple Versions of PHP in Ubuntu
  • Setting the PHP Executable Path Using an Alias in the .bash_profile File
  • Important Points
  • Helpful Points
  • Other helpful code samples for setting PHP path in Ubuntu
  • Conclusion
  • How to set PHP path in Ubuntu?
  • How to find PHP path in Ubuntu?
  • How to set PHP path Linux?
  • How to enable PHP version in Ubuntu?
Читайте также:  Css border color weight

Are you looking for information on how to set the PHP path in Ubuntu? In this comprehensive guide, we will cover everything you need to know about setting the PHP path in Ubuntu, including finding the default executable path, editing configuration files, installing multiple versions of PHP, and setting up a Local Programming Environment .

Finding the Default Executable Path of PHP in Ubuntu

Before we dive into how to set the PHP path in Ubuntu, let’s first find the default executable path of PHP. To do this, we can use the ‘which php’ command in the terminal.

This command will output the location of the default executable path of PHP in Ubuntu.

Setting the PHP Path in the rc file, ~/.bashrc

To add a new path to the current PHP path in Ubuntu, we can edit the rc file, ~/.bashrc.

export PATH=$PATH:/new/php/path 

This command will add the new PHP path to the current system path.

Editing the .bash_profile file to Change the Default PHP Command Path

To change the default PHP command path in Ubuntu, we can edit the .bash_profile file.

export PATH=/new/php/path:$PATH 

This command will set the new PHP path as the default command path in Ubuntu.

Setting the PHP Executable Path in VS Code

If you are using vs code for php development , you can set the PHP executable path using the ‘php.validate.executablePath’ setting.

This setting will set the PHP executable path for PHP validation in VS Code.

Installing PHP on Ubuntu and Setting up a Local Programming Environment

To install PHP on Ubuntu using the command line, you can use the following command:

After installing PHP, you can set up a local programming environment by installing a web server like Apache or Nginx, and a database like MySQL or PostgreSQL.

Editing the php.ini File in Ubuntu to Change PHP Configurations

To Change PHP Configurations in Ubuntu, you can edit the php.ini file.

sudo nano /etc/php/7.4/cli/php.ini 

This command will open the php.ini file in the nano editor. You can then make any necessary changes to the file and save it.

Installing and Switching Between Multiple Versions of PHP in Ubuntu

To install multiple versions of PHP in Ubuntu, you can use the following command:

sudo apt-get install php7.4 php7.3 php7.2 

After installing multiple versions of PHP, you can switch between them using the update-alternatives command.

sudo update-alternatives --set php /usr/bin/php7.2 

This command will set PHP 7.2 as the default PHP version in Ubuntu.

Setting the PHP Executable Path Using an Alias in the .bash_profile File

To set the PHP executable path using an alias in the .bash_profile file, you can use the following command:

This command will create an alias for the PHP executable path in Ubuntu.

Читайте также:  Html parsing php code

Important Points

When setting the PHP path in Ubuntu, there are some important points to keep in mind.

  • If you are using Apache or Nginx with PHP, you will need to configure the server to use the correct PHP version.
  • You can change the PHP version using the command line by using the update-alternatives command.
  • The location of PHP modules and the php.ini file may vary depending on your Ubuntu distribution.

Helpful Points

PHP is a popular programming language for web development, and there are many resources available to help you get started.

  • The latest version of PHP is PHP 8.
  • Cheatsheets can be a helpful resource for quick reference when working with PHP.
  • Best practices for setting the PHP path in Ubuntu include using the latest version of PHP, keeping configurations up-to-date, and using a local programming environment for development.

Other helpful code samples for setting PHP path in Ubuntu

Open Terminal and run command 1. whereis php 2. Output will be something like "/opt/lampp/bin/php" This is your php location

In Php , for example, php path in ubuntu

whereis phpphp: /usr/bin/php /usr/lib/php /etc/php /usr/share/man/man1/php.1.gzcd /usr/bin/php

Conclusion

In this comprehensive guide, we covered everything you need to know about setting the PHP path in Ubuntu. From finding the default executable path to installing and switching between multiple versions of PHP, we hope this guide has been helpful in setting up your PHP development environment. Remember to always keep your configurations up-to-date and use best practices for PHP development. Happy coding!

Источник

Как добавить путь до PHP в переменную окружения PATH в Windows

Вполне возможно, что вам не приходилось ранее сталкиваться с PATH и выражениями «переменная окружения», поэтому я кратко поясню, что это такое.

Переменная PATH содержит список папок, в которых Windows ищет исполнимые файлы.

В графическом интерфейсе, когда для запуска программ используются ярлыки, значение PATH не очень большое. Но если вы запускаете программу в командной строке, то PATH может пригодиться. Опять же, если вы указываете полный путь до файла, например, C:\Users\Alex\Documents\php.exe, то PATH не используется. Но если, например, вы запускаете программу только по имени файла или просто по имени (без файлового расширения), то запустится ли программа, будет зависеть от содержимого переменной PATH.

К примеру, я в командной строке пытаюсь запустить файл (без указания полного пути)

В этом случае операционная система посмотрит все записи PATH (там может быть указано несколько каталогов). Затем в каждом из этих каталогов Windows попытается найти файл php.exe. Если файл найден, то он будет запущен. Если файл не найден, то будет выведено соответствующее сообщение.

По сути, что-то дописывать в переменную PATH нужно только тем, кто много работает с командной строкой. К примеру, вы программист и размещаете свои программы в папке C:\MyApps и при этом вы часто запускаете свои утилиты командной строки. В этом случае вы можете добавить C:\MyApps в PATH и после этого для запуска программ из этой папки вам уже не нужно будет каждый раз вводить полное имя (например, C:\MyApps\parser.exe), а достаточно будет в командной строке ввести только имя файла:

Нужно ли в Windows добавлять PHP в переменную окружения

При установке и настройке PHP в Windows необязательно добавлять в PATH путь до PHP, но это рекомендуется делать.

Читайте также:  Object property access php

Во-первых, вы сможете запускать PHP используя сокращённую запись:

C:\Server\bin\PHP\php.exe my_script.php

Во-вторых, ряд расширений (которые включаются в файле php.ini) работают некорректно, если вы не прописали в PATH путь до PHP; в том числе, это касается такого довольно популярного расширения как cURL. По идее — это какой-то баг этих расширений или PHP, но нам самим придётся исправлять ситуацию, поскольку эта проблема существует уже много лет.

Как добавить PHP в системные переменные среды

Нажмите кнопку Windows (это которая раньше была кнопкой «Пуск»), начните набирать «Изменение системных переменных среды»

и откройте соответствующее окно настроек.

Там нажмите «Переменные среды», откроется:

В окне «Системные переменные» найдите и кликните на Path, потом нажмите «Изменить»:

Далее «Создать» и впишите туда «C:\Server\bin\PHP\»:

Поднимите запись в самый Вверх:

Закройте все окна с сохранением сделанных изменений.

Источник

PHP in Visual Studio Code

Visual Studio Code is a great editor for PHP development. You get features like syntax highlighting and bracket matching, IntelliSense (code completion), and snippets out of the box and you can add more functionality through community-created VS Code extensions.

Linting

VS Code uses the official PHP linter ( php -l ) for PHP language diagnostics. This allows VS Code to stay current with PHP linter improvements.

Tip: Using XAMPP? Install the full version of PHP in order to obtain the development libraries.

There are three settings to control the PHP linter:

  • php.validate.enable : controls whether to enable PHP linting at all. Enabled by default.
  • php.validate.executablePath : points to the PHP executable on disk. Set this if the PHP executable is not on the system path.
  • php.validate.run : controls whether the validation is triggered on save (value: «onSave» ) or on type (value: «onType» ). Default is on save.

To change the PHP settings, open your User or Workspace Settings ( ⌘, (Windows, Linux Ctrl+, ) ) and type ‘php’ to filter the list of available settings.

show PHP settings

To set the PHP executable path, select the Edit in settings.json link under PHP > Validate: Executable Path, which will open your user settings.json file. Add the php.validate.executablePath setting with the path to your PHP installation:

Windows

 "php.validate.executablePath": "c:/php/php.exe" > 

Linux and macOS

 "php.validate.executablePath": "/usr/bin/php" > or  "php.validate.executablePath": "/usr/local/bin/php" > 

Snippets

Visual Studio Code includes a set of common snippets for PHP. To access these, hit ⌃Space (Windows, Linux Ctrl+Space ) to get a context-specific list.

PHP Snippets

PHP extensions

There are many PHP language extensions available on the VS Code Marketplace and more are being created. You can search for PHP extensions from within VS Code in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) then filter the extensions dropdown list by typing ‘php’.

Searching for PHP in the Extensions view

Disable built-in PHP support

To disable the built-in PHP smart completions in favor of suggestions from an installed PHP extension, uncheck PHP > Suggest: Basic, which sets php.suggest.basic to false in your settings.json file.

Debugging

PHP debugging with XDebug is supported through a PHP Debug extension. Follow the extension’s instructions for configuring XDebug to work with VS Code.

Next steps

Read on to find out about:

Источник

Оцените статью