Php server vs code настройка

Настройка редактора Visual Studio Code для разработки на PHP

Пора перейти от слов к действиям и познакомиться с Visual Studio Code поближе. В этом посте представлена поэтапная настройка VS Code для разработки на PHP.

  1. Скачать и установить Visual Studio Code.
  2. Настройть статистический анализ кода на PHP в параметрах пользователя.
  3. Скачать и установить расширение PHP Debug с портала Visual Studio Marketplace.
  4. Настройть расширение PHP Debug для использования XDebug.

Скачайте и установите Visual Studio Code

  • Бесплатный: да, VS Code полностью бесплатен, никаких приписок мелким шрифтом.
  • Кроссплатформенный: доступны версии VS Code для Windows, Linux и OS X.
  • Легковесный: VS Code, в отличие от Visual Studio, — не полнофункциональная среда IDE, а редактор кода. Он поддерживает ряд мощных функций, характерных для IDE, например, IntelliSense, отладку и интеграцию с системой управления исходным кодом Git.

После загрузки установите редактор на своем компьютере. Подробные инструкции по установке доступны здесь. Теперь можно открыть окно командной строки, запустить Visual Studio Code и начать редактировать файлы в папке.

image

Если вы откроете файл с расширением .php, Code поймет, что это файл на языке PHP. Тип файла можно изменить и вручную: щелкните кнопку Language Mode в правом нижнем углу окна редактора или последовательно нажмите клавиши Ctrl+K и M.

image

Встроенные функции работы с PHP

VS Code поддерживает множество языков, в том числе PHP. На портале Visual Studio Marketplace доступны расширения VS Code, обеспечивающие поддержку дополнительных языков. Для PHP работает подсветка синтаксиса, определение парных скобок и фрагменты кода.

Когда вы начнете набирать код в файле PHP, то заметите автоматическое срабатывание цветового выделения синтаксиса, определения парных скобок и функции IntelliSense.

image

Настройка статического анализа PHP

По умолчанию VS Code будет проводить статический анализ кода на PHP в ходе проверки при сохранении файла. Для этого используется исполняемый файл php. Если вы работаете с VS Code впервые, то получите сообщение об ошибке, в котором сказано, что исполняемый PHP файл не обнаружен.

image

Необходимо указать путь к исполняемому файлу PHP на вашем компьютере. Для этого следует изменить файл настроек (в VS Code существуют различные уровни файлов настроек, подробнее см. в документации). В нашем примере мы настроим параметры PHP глобально для пользователя.

Откройте пользовательские настройки с помощью панели команд: нажмите F1, введите «user» и нажмите Enter.

image

Откроется два документа JSON. В документе слева содержатся настройки по умолчанию, в документе справа — пользовательские настройки. В пользовательских настройках можно переопределить настройки по умолчанию. Чтобы включить статический анализ кода PHP, необходимо изменить значения трех параметров.

image

Чтобы настроить путь к исполняемому файлу PHP, укажите его в файле пользовательских настроек:

Читайте также:  Lists in html emails

image

После этого функция проверки будет включена для всех файлов PHP. Некорректный код PHP будет подчеркнут красным (в примере ниже пропущена точка с запятой).

image

Настройка отладки

Расширение PHP Debug (спасибо Феликсу Беккеру!) добавляет в VS Code поддержку отладчика XDebug. Установите расширение через панель команд VS Code: нажмите F1, введите «install ext», нажмите Enter, введите «PHP Debug» и вновь нажмите Enter. После установки расширения может потребоваться перезапуск VS Code.

image

Обратите внимание: это расширение использует отладчик XDebug. Поэтому для его работы необходимо установить XDebug. Скачать XDebug можно здесь (для Windows выбирайте 32-разрядную non-thread-safe версию).
Затем внесите в файл php.ini следующие настройки. Я установил XDebug в подкаталог ext установочной папки PHP. Если вы выбрали для XDebug другой каталог установки, убедитесь, что параметр zend_extension содержит правильное значение.

image

Убедитесь, что корневой раздел веб-сервера соответствует вашему проекту. Тогда при каждом запросе файла PHP XDebug будет предпринимать попытку подключения к порту 9000 для отладки.
Чтобы начать отладку, откройте вкладку Debugging в VS Code.

image

Щелкните значок шестеренки, чтобы сформировать файл launch.json, который позволит VS Code начать сеанс отладки XDebug.

image

Чтобы начать отладку, нажмите F5 или щелкните зеленую стрелку на вкладке Debugging. Чтобы задать точку останова в исходном коде, выберите строку и нажмите F9.

image

Теперь, когда вы откроете определенную веб-страницу, VS Code остановит выполнение исходного кода в заданной точке. В области слева отобразится информация о переменных, стеке вызовов и т. п.

image

Заключение

Visual Studio Code обладает отличной встроенной поддержкой PHP, а расширение PHP Debug добавляет возможность отладки кода на PHP. Все эти инструменты являются бесплатными и кроссплатформенными.

На портале Visual Studio Marketplace доступны и другие расширения для работы с PHP.

Полезные ссылки

  • Visual Studio 2015: бесплатные предложения для разработчиков
  • Дополнительные и бесплатные инструменты и службы в программе Visual Studio Dev Essentials
  • Лабораторные работы по разработке, тестированию и управлению жизненым циклом ПО для Visual Studio 2015

Источник

PHP Server

PHP Server

Buy Me a Coffee at ko-fi.com

Host / serve current workspace (or subfolder) with PHP.

Getting started

  • CTRL + SHIFT + P and searching for PHP Server: Serve project command
  • Clicking on vscode’s editor button (icon on the top-right corner)
  • Right-clicking on vscode’s editor when a .php or an .html is open.

To stop the server, the PHP Server: Stop project command can be executed likewise.

Commands

All commands can be executed by pressing CTRL + SHIFT + P and typing the name of the command.

Command Notes
PHP Server: Serve project
PHP Server: Stop project
PHP Server: Reload server Stops the running server and starts it again.
PHP Server: Open file in browser Quickly opens the URL of the active file in the browser. If the server is not running, this command will fail.

Settings

Setting Default Notes
phpserver.autoOpenOnReload true Enable/disable automatic opening of server’s URL in the browser after server has been reloaded.
phpserver.browser null App used to open the server URL. If empty, it will use the default browser.
You can put any browser name here as long as it’s installed in your machine (e.g. google-chrome , firefox , chromium-browser . )
phpserver.ip localhost Server’s ip/hostname (e.g. localhost , 0.0.0.0 . )
phpserver.phpConfigPath null Path to php.ini file. If empty, the extension uses the default path.
phpserver.phpPath null Path to PHP executable. If empty, the extension will try to get the path from the $PATH environment variable.
phpserver.port 3000 Server’s port number.
phpserver.relativePath «.» Path relative to project. This is useful when you want to serve a different folder than the one from current workspace.
phpserver.router null Path to custom router script that will be used by PHP server. Example.
If a custom router script is used on a Windows machine, there will be no console output unless a logger like this is included in the script.
Читайте также:  Css эффект появления блока

Requirements

Источник

Как запустить php server в vs code?

Поясните пожалуйста начинающему в php, что требуется сделать, чтобы запустить расширение PHP Server в VS CODE.

5f512277d5c0d520889128.png

При запуске расширения всплывают окна с ошибками:

5f5122b50d5cd566783421.png

Ошибки отсылают к файлу settings.json:

pton

У меня php установлен отдельно. В нете есть статьи как поставить php на windows
Обязательно добавьте путь к исполняемому файлу php.exe в переменную PATH в настройках windows

"php.validate.enable": true, "php.validate.run": "onSave", "php.validate.executablePath": "D:/ospanel/modules/php/PHP-7.2/php.exe",

Прописываете путь к Вашему исполняемому файлу php

Теперь при сохранении файла VSCode сам будет проверять его на ошибки php

daniloneil

Итого:
после установки php на windows переименовываем php.ini-production в php.ini;
раскомментим (убираем знак 😉 перед строчками:

extension=php_curl.dll; extension=php_gd2.dll; extension=php_mbstring.dll; extension=php_openssl.dll; extension=php_pdo_mysql.dll; extension=php_pdo_sqlite.dll; extension=php_sqlite3.dll.

Источник

Configuring Visual Studio Code to use PHP and PHP (Web) Server)

Install any other PHP packages Visual Studio recommends as well.

Install PHP Debug and PHP Intelephense as well to make editing code easier.

Testing it works

We need a php file.

Save it as filename.php the filename can be anything. The extension .php will tell the webserver to run the php interpreter on this file.

In the top right of Visual Studio Code you should see a blue PHP Icon.

Now we want to add some code to our php file.

PHP files combine HTML and PHP script to create dynamic pages.

PHP is a programming language in its own right.

Enter the code below into your file.

echo will print to the html file. Here we are creating the date and printing ‘Hello World’

Click the Blue PHP button to serve (run) the page.

We end up with a very bland webpage.

Modify your page so that it contains the code below.

This example integrates HTML and PHP.

Note that you can include HTML inside strings to print.

The server is already running at the moment. Clicking the Blue button will give an error.

Right click on the background of the php file and select Reload Server. You can also stop the server here.

Note that our page now has some html formatting

Читайте также:  Break all loops in python

We now have a working webpage and a development PHP Web Server.

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

Cookie Duration Description
cookielawinfo-checbox-analytics 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Analytics».
cookielawinfo-checbox-functional 11 months The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category «Functional».
cookielawinfo-checbox-others 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Other.
cookielawinfo-checkbox-necessary 11 months This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category «Necessary».
cookielawinfo-checkbox-performance 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Performance».
viewed_cookie_policy 11 months The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

Источник

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