Php server windows or linux

PHP-скрипт – определить, работает ли Linux или Windows?

У меня есть PHP-скрипт, который может быть помещен в систему Windows или Linux-систему. Мне нужно запускать разные команды в любом случае.

как я могу определить, в какой среде я нахожусь? (желательно что-то php, а не умные системные хаки)

Извините извините!! скрипт запускается из командной строки .

Проверьте значение постоянных документов PHP_OS .

Это даст вам различные значения в Windows, такие как WIN32 , WINNT или Windows .

См. Также: Возможные значения для: PHP_OS и php_uname Документы :

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') < echo 'This is a server using Windows!'; >else

Вы можете проверить, является ли каталог seperator / (для unix / linux / mac) или \ на окнах. Постоянное имя DIRECTORY_SEPARATOR

if (DIRECTORY_SEPARATOR == '/') < // unix, linux, mac >if (DIRECTORY_SEPARATOR == '\\') < // windows > 
if (strncasecmp(PHP_OS, 'WIN', 3) == 0) < echo 'This is a server using Windows!'; >else

кажется немного более элегантным, чем принятый ответ. Однако вышеупомянутое обнаружение с DIRECTORY_SEPARATOR является самым быстрым.

Обратите внимание, что PHP_OS сообщает ОС, на которых был построен PHP , что не обязательно является той же ОС, что и в настоящий момент.

Если вы находитесь на PHP> = 5.3 и вам просто нужно знать, работаете ли вы в Windows или нет, то Windows может проверить, является ли одна из определенных для Windows констант , например:

$windows = defined('PHP_WINDOWS_VERSION_MAJOR'); 

Для обнаружения этого может использоваться функция php_uname .

Это должно работать в PHP 4.3+:

if (strtolower(PHP_SHLIB_SUFFIX) === 'dll') < // Windows >else < // Linux/UNIX/OS X > 

Основные предопределенные константы: http://us3.php.net/manual/en/reserved.constants.php, которая имеет PHP_OS (string) .

Или если вы хотите определить ОС клиента:

Читайте также:  Простые скрипты для linux

Согласно вашему редактированию вы можете ссылаться на это имя дублирующего PHP-сервера из командной строки

string php_uname ([ string $mode = "a" ] ) 

‘s’: название операционной системы. например. FreeBSD.

Согласно предопределенным константам: User Contributed Notes Volker и rdcapasso, вы можете просто создать вспомогательный класс следующим образом:

if(System::getOS() == System::OS_WIN) < // do something only on Windows platform > 

Чтобы определить, является ли это Windows, OS X или Linux:

if (stripos(PHP_OS, 'win') === 0) < // code for windows >elseif (stripos(PHP_OS, 'darwin') === 0) < // code for OS X >elseif (stripos(PHP_OS, 'linux') === 0) < // code for Linux > 

stripos в этом конкретном случае немного медленнее, чем substr , но он достаточно эффективен для такой небольшой задачи и более изящный.

Вы можете проверить, существует ли константа в PHP> 5.3.0 ( вручную )

if (defined('PHP_WINDOWS_VERSION_BUILD')) < // is Windows > 

Ранее этот метод использовался в Symfony. Теперь они используют другой метод :

'; foreach ($_SERVER as $k => $v)< echo "" . $k ."" . $v . ""; > echo "" ?> 

Это весь массив $ _SERVER … поскольку ArtWorkAD отметил, что с помощью ключа HTTP_USER_AGENT вы можете явно извлечь ОС.

Источник

what difference it makes when coding PHP on windows and linux [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.

I worked/working in core Java, PHP and have strong intention to learn Python and A.I. related languages. But always I do coding (PHP, Java) on windows platform (I feel pity about it myself..) . Always I wanna work in Linux environment. But I wonder what difference it makes. Someone explain me that please. And please provide some good books for linux learning. I checked google for it. But there comes books in different varieties of it (Administration, Linux programming etc.,). So to just do coding in PHP on linux platform what level of book I should read for linux. Note: I am zero in Linux knowledge and I am interested in Linux programming too.

Читайте также:  Mp4 to vob converter linux

@senad: well there are some php functions that dont work in a windows environment (strptime for example)

Windows is case-insensitive but linux is not. so u have to take care about your directory path and file names.

5 Answers 5

My best recommendation is to create a mini project for yourself and dive in. It won’t be easy by any means, but the hands on experience will help you learn. Maybe, take one of your existing PHP or Java applications and attempt to get it working in Linux. As a starting point, you’ll need LAMP for PHP, and Tomcat for your java applications if they’re web based. You might want to start first with a very user friendly OS such as Ubuntu. Then move on to RHEL (CentOS is free).

The biggest differences that I’ve found are the communities and the cost. The cost difference is a common debate between people in businesses concerning achieving business needs with open source or proprietary solutions. When I mention the communities, in my experience, I’ve always found that open source projects tend to have more robust communities that feel, in my words, «real». Some of the proprietary communities feel like their driven by $$$ and marketing. However, that is just my opinion.

On a side note, since expanding Linux knowledge on my resume, I have had a lot more job opportunities.

Thanks for the answer. Exactly. I’ve a planned a website to build . decided to do it using LAMP stack.

I can see two questions from your text:

1) Does PHP programming on Linux differ from PHP programming on Windows?

Читайте также:  Zipping files in linux command line

Answer: No, it does not. There may be other tools that you work with, but even on Windows you have plenty of choices (from a simple Notepad to an IDE). Lots of tools (e.g. IDEs like NetBeans or Eclipse) are available on both platforms, which makes the switch to Linux even easier. If you want to run the Script on your local machine, you could install a basic LAMP (Linux Apache MySQL PHP) configuration on your system, comparable to e.g. XAMPP on Windows. Or you could install just the php-cli (command line interface), without the complete webserver, if you want to run only some scripts in command line.

2) Is Linux difficult to use?

Answer: No, it is not 🙂 The best way to find it out is to get e.g. the very user-friendly Linux Distribution Ubuntu and try it on your own. You can run the System as a Live CD without installing anything, if you want to test things. After working a bit with Linux, you get quickly used to it and even developing applications shouldn’t be that hard.

I can’t recommend any books, though. Maybe someone else can.

Источник

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