Note on permissions of php files: You don't have to use 'chmod 0755' under UNIX or Linux; the permissions need not be set to executable. Again, this is more like a html file than a cgi script. The only mandatory requirement is that the web server process has read access to the php file(s). With many Linux systems, it is popular for Apache to run under the 'apache' account. Given that HTML and other web files, like php, are often owned by user 'root' and group 'web' (or another similar group name), acceptable permissions might be those achieved with 'chmod 664' or 'chmod 644'. The web server process, running under the 'apache' account, will inherit read only permissions. The 'apache' account is not root and is not a member of the 'web' group, so the "other" portion of the permissions (the last "4") applies.
Sua primeira página PHP
Crie um novo arquivo chamado ola.php e coloque-o em seu diretório root do seu servidor web (DOCUMENT_ROOT) com o seguinte conteúdo:
Exemplo #1 Nosso primeiro script PHP: ola.php
<html>
<head>
<title>PHP Teste</title>
</head>
<body>
<?php echo "<p>Olá Mundo</p>"; ?>
</body>
</html>
Use o seu navegador para acessar o arquivo pelo endereço de seu servidor web, ao final do endereço coloque o arquivo "/ola.php" como referência. Quando o desenvolvimento é local você usará uma url como esta http://localhost/ola.php ou http://127.0.0.1/ola.php mas dependendo da configuração do seu servidor web. Entretanto isto está fora do escopo deste tutorial, veja também as diretivas DocumentRoot e ServerName dos arquivos de configuração do seu servidor web. (no Apache o nome do arquivo é httpd.conf). Se tudo foi configurado corretamente, o arquivo irá ser interpretado pelo PHP e irá mostrar a seguinte mensagem de saída no seu navegador:
<html> <head> <title>PHP Teste</title> </head> <body> <p>Olá Mundo</p> </body> </html>
Note que isto não é como em um script CGI. O arquivo não precisa ser executável ou especial em nenhum aspecto. Pense nesse arquivo como um arquivo HTML normal mas com a diferença que ele pode conter algumas tags especiais a mais que permitem a você fazer coisas mais interessantes do que somente páginas HTML estáticas.
Este exemplo é extremamente simples e você realmente não precisa usar o PHP para criar uma página como esta. Tudo o que ele faz é mostrar uma mensagem Olá Mundo usando a declaração echo do PHP.
Se você tentar rodar este exemplo e ele não mostrar nenhuma mensagem de saída, ou aparecer uma caixa de diálogo pedindo para você salvar o arquivo, ou você ver o arquivo em formato de texto, há uma grande chance do seu servidor não ter o PHP habilitado. Peça ao seu administrar para habilitar o PHP para você, usando o capítulo de Instalação do manual. Se você está desenvolvendo localmente, também leia o capítulo indicado acima para ter certeza de que configurou tudo corretamente. Se os problemas continuarem a persistir, não hesite em usar uma das várias formas de » ajuda que o PHP pode lhe oferecer.
O objetivo do exemplo é mostrar o formato especial das tags do PHP. Neste exemplo nós usamos <?php para indicar que à partir daquele ponto começa um código PHP. Então nós colocamos uma declaração de fechamento para indicar que o script PHP acabou, usando a tag ?>. Você pode usar o PHP em qualquer parte do seu código HTML, e também pode usar várias tags de abertura e fechamento no mesmo arquivo. Para mais detalhes, leia a seção do manual que fala da sintaxe básica do PHP.
Nota: Uma Nota sobre os Editores de Texto
Há muitos editores de textos e Integrated Development Enviroments (IDEs) que você pode usar para criar, editar e gerenciar arquivos PHP. Uma lista parcial destas ferramentas pode ser vista na » Lista de Editores para PHP. Se você gostaria de recomendar algum editor, por favor visite o endereço acima e pergunte ao administrador do site para adicionar o seu editor à lista. Ter um editor que colora as sintaxes das tags pode ser muito útil.
Nota: Uma Nota sobre os Processadores Word
Processadores Word como o StarOffice Write, Microsoft Word e Abiword não são boas escolhas para editar arquivos PHP. Se você deseja usar um desses para testar seus scripts, você precisa verificar se você está salvando os arquivos como TEXTO PLANO ou o PHP não irá ser capaz de ler e executar o seu script.
Nota: Uma Nota sobre o Bloco de Notas do Windows
Se você está escrevendo seus scripts PHP usando o Bloco de Notas do Windows, você precisará verificar que os arquivos estão sendo salvos com a extensão .php. (O Bloco de Notas do Windows adiciona automaticamente a extensão .txt aos arquivos a não ser que você siga um dos passos a seguir para previnir isto). Quando a caixa de diálogo Salvar estiver aberta e você for digitar o nome do seu arquivo, coloque o nome do arquivo entre aspas (i.e. "ola.php"). Uma alternativa, é você clicar na lista drop-down 'Documentos de Texto' na caixa de diálogo salvar e alterar para "Todos os tipos de arquivos". Você agora pode digitar o nome do seu arquivo sem usar as aspas.
Agora que você criou com sucesso um script simples em PHP, é hora de criar o mais famoso dos scripts PHP! Uma chamada à função phpinfo() e você verá todas as informações sobre seu sistema e configurações disponíveis como a de Variáveis Pré-definidas, módulos carregados pelo PHP, e as opções de configuração. Tire algum tempo para ver e rever estas importantes informações.
OS X users editing in TextEdit will need to make sure their TextEdit preferences are set to allow plain text files. Under the TextEdit pull-down menu, choose PREFERENCES, then under NEW DOCUMENT ATTRIBUTES in the window that pops up, click PLAIN TEXT.
Then, in the section of that same window called "saving," DESELECT "append .txt extension to plain text files." This will allow you to save your files with a .php extension.
Then close the PREFERENCES window. You're good to go.
document_root variable is located in your web server configuration file
If you save your code as UTF-8, make sure that the BOM (EF BB BF) is not present as the first 3 bytes of the file otherwise it may interfere with the code if the PHP need to be run before any output (e.g. header()).
Well, but PHP file ownership is important when server has safe_mode enabled - HTTP server checks it, uses it to set UID of process which executes it, or may even refuse to execute such a file - e.g. if one user is owner of main PHP file, and the main file includes another, owned by other user, this is considered to be security violation (quite reasonably).
On Windows, if file extensions can be hidden, you may not SEE that you have accidently saved a file as 'Text Documents' (and that the browser has added '.txt' to the end of your 'page.html', resulting in 'page.html.txt'.) You still see only 'page.html' even though it's really 'page.html.txt'. Also, if you try to rename it, it won't work because it's not overwriting the '.txt' part and not changing the filetype.
By the way, the hiding of file extensions is ALSO a way malicious crackers get you to click on an executable virus, fooling you into thinking it's an innocent document. You should always be able to view the extensions of all files on your system.
To view all extensions, open Windows Explorer. Click the 'Tools' menu, then 'Folder Options'. In the dialog box that appears, click the 'View' tab. In the 'Advanced Settings Box', scroll down to 'Hide extensions for known file types' and click the checkbox next to it to REMOVE THE CHECKMARK. Click the 'Apply to All Folders' button near the top of the dialog. This may or may not take a few minutes. Then click the 'OK' button to close the dialog.
Now, if something accidentally gets saved as the wrong filetype, resulting in another file extension automatically appended to the one you typed, you will see it and be able to rename it.
Of course, a badly-named file can be renamed simply by using 'Save As' and saving it as the proper filetype, but if you can't see the file extension, you may not know that is the problem. Also, renaming is easier than opening, resaving as a new filetype, and then deleting the old version!
