-
Notifications
You must be signed in to change notification settings - Fork 1
TutorialPhp
Note: this tutorial has been copied from http://www.phpfreaks.com/tutorials/60/1.php and http://www.freewebmasterhelp.com/tutorials/php/ I made a local copy so you can access it during class time
PHP stands for Hypertext Preprocessor and is a server-side language. This means that the script is run on your web server, not on the user's browser, so you do not need to worry about compatibility issues. PHP is relatively new (compared to languages such as Perl (CGI) and Java) but is quickly becomming one of the most popular scripting languages on the internet.
PHP can be embedded in a html page. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
PHP scripts are always enclosed in between two PHP tags. This tells your server to parse the information between them as PHP:
<?php
PHP Code In Here
?>
The first PHP script you will be writing is very basic. All it will do is print out all the information about PHP on your server. Type the following code into your text editor:
<?php
phpinfo();
?>
As you can see this actually just one line of code. It is a standard PHP function called phpinfo which will tell the server to print out a standard table of information giving you information on the setup of the server.
One other thing you should notice in this example is that the line ends in a semicolon. This is very important. As with many other scripting and programming languages nearly all lines are ended with a semicolon and if you miss it out you will get an error.
Place this script in the directory public_html in your account.
To output text in your PHP script is actually very simple. As with most other things in PHP, you can do it in a variety of different ways. The main one you will be using, though, is print. Print will allow you to output text, variables or a combination of the two so that they display on the screen.
The print statement is used in the following way:
print("Hello world!");
I will explain the above line:
print is the command and tells the script what to do. This is followed by the information to be printed, which is contained in the brackets. Because you are outputting text, the text is also enclosed instide quotation marks. Finally, as with nearly every line in a PHP script, it must end in a semicolon. You would, of course, have to enclose this in your standard PHP tags, making the following code:
<?php
print("Hello world!");
?>
Which will display:
Hello world!
on the screen.
To start off usingPostgreSQL from PHP, You'll first need to connect to it. This is accomplished with the pg_connect() function. This function is pretty straightforward and only expects one argument, the connection string. The connection string contains all of the information needed to connect to the database. The arguments available for connection_string includes host, port, tty, options, dbname, user, and password. The way you would usually connect to your database is as follows:
<?php
/* dbname is the name of the database you're connecting to
* user is the PostgreSQL user you're going to connect as
* password is the password for the user you're connecting as
*/
pg_connect("dbname=databasename user=username password=password host=localhost") or die("Couldn't Connect: ".pg_last_error());
// what pg_last_error() does is return the last error that occured, so you should always die with that to know what happened
echo "I did it";
?>
Lets create our first table. We will make a script to do this, demonstrating the use of pg_query(). Lets make a table named "Contacts" with the fields 'name','surname', and 'email'. To do this, use the following query:
<?php
/* We're using the query
* CREATE TABLE contacts
* (
* name varchar(50),
* surname varchar(50),
* email varchar(50)
* )
*/
pg_connect("dbname=dbname user=user password=password host=localhost") or die("Couldn't Connect ".pg_last_error()); // Connect to the Database
/* Use the Query */
$query = "CREATE TABLE contacts
(
name varchar(50),
surname varchar(50),
email varchar(50)
)";
$query = pg_query($query); // Execute the Query
if($query)
echo "Table Created"; // Check to see if The Query Worked.
else{
echo "An error Occured! ".pg_last_error();
}
?>
If there was any error In using that script, then check to see if you supplied the correct username and password, and also check to see that PostgreSQL is running. Also be very careful to only execute that script once and then delete it. Otherwise you will get errors saying that there is already a table named 'contacts'.
Now that you've set up your table, its time to insert some records, your database should look something like this:
Database name: Contacts name | surname | email
Now its time to use the pg_query function again. We will this time insert some information into our database. We will use the SQL Command 'INSERT' to do this, its syntax is as follows: INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....) table_name is the name of the table, in the parenthesis you can specify which columns you want to insert into. For values, you will put what you want to insert into the database. so INSERT INTO contacts VALUES('John','Smith','johnsmith@domain.com') would insert John as the first name, Smith as the last name, and johnsmith@domain.com as the e-mail address. Lets try writing a script now to do this.
<?php
pg_connect("dbname=databasename user=username password=username host=localhost") or die("Couldn't Connect".pg_last_error());
$query = "INSERT INTO contacts VALUES('John','Smith','johnsmith@domain.com')";
$query = pg_query($query);
if($query)
echo "inserted successfully!";
else{
echo "There was an error! ".pg_last_error();
}
?>
That should've done what we wanted to, otherwise you should backtrack and try remaking the table. If that was successful, which it should have been, lets go on to insert a few more records. In fact, Why don't we make a form based inserter? We shall start off with a basic form
<form method="POST">
Name: <input type="text" name="name"><br />
Surname: <input type="text" name="surname"><br />
Email Address: <input type="text" name="email"><br />
<input type="submit">
</form>
Now we shall add the actual inserts to our form. We will first check to see if all fields were filled out, and then insert into the database, so the following should do the trick.
<?php
if($_REQUEST['name'] && $_REQUEST['surname'] && $_REQUEST['email']) // Check to see if All of the Fields were Filled Out
{
pg_connect("dbname=test user=miusuario password=mipassword host=localhost")
or die("Couldn't Connect".pg_last_error());
$query = sprintf("INSERT INTO contacts VALUES('%s','%s','%s')",$_REQUEST['name'],$_REQUEST['surname'],$_REQUEST['email']); // Form the Query
/* Quick Lesson on Sprintf:
* Sprintf Will take a string and format it. In this case I use %s which means that the Next parameter will be A string, and It
* Should be put into wherever the %s is. The parameters will fill the %s's respectively
*/
// echo $query;
// Uncomment the previous line to see what $query Contains. Everything that follows is just some simple error checking.
$query = pg_query($query);
if($query)
echo "You were successfully added to the database!";
else
echo "Some Error Occured! ".pg_last_error();
}
else{ // If we dont have all of the fields, show the form
?>
<form METHOD="POST" ACTION="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name"><br />
Surname: <input type="text" name="surname"><br />
Email Address: <input type="text" name="email"><br />
<input type="submit">
</form>
<?php
}
?>
And Voila! We have a form to Insert into our database! By reading the comments, you should fully understand what each part of this script does
The action of this form is echo $_SERVER['PHP_SELF'], which will print the name of the current file. So That this will work no matter what your filename is, as long as the extension is .php
Excellent, Now that we can add to our database, the only thing that we really need to do now is to VIEW all of the database entries. We can do that using the SELECT Command in SQL. Keep in mind we're still using the pg_query() function. If we wanted to show all of the database fields, we could make a script that'll select all(* in SQL) of the entries.
<?php
pg_connect("dbname=test user=miusuario password=mipassword host=localhost")
or die("Couldn't Connect".pg_last_error());
$query = "SELECT * FROM contacts";
$query = pg_query($query);
while($row = pg_fetch_array($query,NULL,PGSQL_ASSOC))
{
// print_r($row);
// Uncomment the preceding line to see the entire array.
echo "Name: ".$row['name']."<br />";
echo "Surname: ".$row['surname']."<br />";
echo "E-Mail Address: ".$row['email']."<br /><br />";
}
?>
Now don't be afraid if you don't understand every part of this. I just used the function pg_fetch_array() to fetch the results from the query Into an associative array. The keys of the array are named after the column names of the table. so $row['name'] will contain whatever was in the "name" column of our table. simple, isn't it? The $query Variable is the Query that you want to fetch. NULL is the row number, when you specify NULL, then the function will just skip that parameter. In the last parameter, the one that says PGSQL_ASSOC, that chooses what type of array It will return. PGSQL_ASSOC will have arrays with the column names as keys. PGSQL_NUM will return a numerated array, and PGSQL_BOTH will return both. As a final note, you can replace all of those echo's with a print_r() to see the entire array.
The only thing left for you to know the basics, is the update command, which is pretty straightforward. It's syntax is UPDATE table_name SET column_name = new_value WHERE column_name = some_value So "UPDATE contacts SET email = 'HIDDEN' WHERE surname = 'smith'" would do it and set the email to "HIDDEN" to anybody with the last name 'Smith'. simple, huh?
$query = "SELECT * FROM usr WHERE uid ='$uid' AND pass = '$passh'";
$result = pg_query($conn, $query);
The above is part of source code implementing user authentication. $uid in the first line is the user ID to be provided by the user. $passh is a hash value the web application calculates based on the password the user enters. In the first line, the web application uses these variables to compose an SQL statement and assigns them to $query. The pg_query() function in the second line is a PostgreSQL function provided by PHP and executes ”$query “, which is the SQL statement set in the first line. This sample program, however, lacks escaping process for the $uid value, which allows an attacker to launch SQL injection attacks by inserting a specially-crafted value that would turn into a malicious SQL statement.
If a web application does not perform escaping for the values passed by the external parameters, it may cause execution of unexpected SQL statements. For example, suppose a user enters [taro’--] as user ID, the SQL statement to be sent to the database will be the following:
SELECT * FROM usr WHERE uid = 'taro'--' AND pass ='eefd5bc2...'
The single quote (‘) used in the SQL statement above is a special character, which defines a string literal by enclosing a data string within a pair of single quotes. Likewise, two consecutive hyphens (--) are a special character which tells the database to ignore everything that comes after it as comments. Which means the database will ignore [’ AND pass = eefd5bc2..] when the value [taro’ --] is set in $uid. As a result, the SQL statement to be sent to and executed by the database would become like this.
SELECT * FROM usr WHERE uid = 'taro'
What it means is that if a user account ”taro” does exist in the database, the attacker could log in without knowing taro’s corresponding password.
Use the functions that support binding mechanisms Use the pg_prepare() function or the pg_execute() function instead of the pg_query() function.
$result = pg_prepare($conn, "query", 'SELECT * FROM usr WHERE uid=
$1 AND pass=$2);
$result = pg_execute($conn, "query", array($uid, $passh));
The pg_execute() function executes the prepared statement the pg_prepare() function has created. When the placeholders are used in a prepared statement, the pg_execute() function converts each element of the third argument ($uid and $passh in this case) into a string and set them in the corresponding placeholders (called “binding”) and executes the completed SQL statement. The use of placeholders saves you from explicitly performing escaping.
The pg_prepare() function and the pg_execute() function are PostgreSQL functions provided in PHP 5.1.0 and later and supported only by PostgreSQL 7.4 and later. The pg_prepare() function generates a prepared statement. Its third argument is an SQL statement where the variables are referred to using the placeholders (bind variables) $1, $2... without actual value.
Use the function equipped with a placeholder capability Use the pg_query_params() function instead of the pg_query() function.
$result = pg_query_params($conn, 'SELECT * FROM usr WHERE uid = $1
AND pass = $2', array($uid, $passh));
The pg_query_params() function is a PostgreSQL function provided in PHP 5.1.0 and later and supported only by PostgreSQL 7.4 and later. The pg_query_params() function is equipped with a placeholder capability. It takes an SQL statement in which placeholders ($1, $2...) are used as the second argument and the actual values for the placeholders as the third argument. The use of placeholders saves you from explicitly perform escaping.
Use an escape function
Use the pg_escape_string() function and perform escaping for all elements in an SQL statement to be executed by the pg_query() function.
$query = "SELECT * FROM usr WHERE uid = '".pg_escape_string($uid)."'
AND pass = '".pg_escape_string($passh)."'";
$result = pg_query($conn, $query);
The pg_escape_string() function is a PostgreSQL function provided in PHP 4.2.0 and later and supported only by PostgreSQL 7.2 and later. It will escape the special characters designated in PostgreSQL. You can write an escape function yourself but it will be difficult to cover all the special characters that have a unique meaning in PostgreSQL, thus not recommended. In the code above, $passh goes through escaping process as well. $passh is a hash value calculated from the password and unlikely to be exploited in SQL injection attempts. Nevertheless, we recommend performing escaping for these internally processed elements like $passh as well. This will save you from checking all elements whether or not you should perform escaping for them. With a complex program, it may be impractical to actually do that. We recommend that you uniformly perform escaping for all the elements that make up an SQL statement.
Logging With PHP (FROM http://www.devshed.com/c/a/PHP/Logging-With-PHP/1/)
Logging data to a file in PHP can be as simple or as complex as you want to make it. Break it down, though, and it all comes down to these three simple lines of code:
<?php
// open file
$fd = fopen($filename, "a");
// write string
fwrite($fd, $str . "\n");
// close file
fclose($fd);
?>
Fundamentally, logging data to a file consists of three steps:
- Open the target file (or create it if it doesn't already exist);
- Append your data to the end of the file;
- Close the file.
You can encapsulate this as a function,
--possible problem adding at the same time
<?php
function logToFile($filename, $msg)
{
// open file
$fd = fopen($filename, "a");
// write string
fwrite($fd, $msg . "\n");
// close file
fclose($fd);
}
?>
and then use it liberally within your code as and when required.
<?php
function logToFile($filename, $msg)
{
// open file
$fd = fopen($filename, "a");
// write string
fwrite($fd, $msg . "\n");
// close file
fclose($fd);
}
$conn = pg_connect("dbname=databasename user=username password=password host=localhost");
if (!$conn)
{
logToFile("my.log", "Could not connect to database");
die("Could not connect to database");
}
?>
You can make the function a little more professional by having it automatically append the date and time of the log message to the log file as well:
<?php
function logToFile($filename, $msg)
{
// open file
$fd = fopen($filename, "a");
// append date/time to message
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
// write string
fwrite($fd, $str . "\n");
// close file
fclose($fd);
}
?>
Here's an example of the output:
[2002/11/25 06:02:43] Could not connect to database
<?php
// this starts the session, must be first thing in a file
session_start();
// Function to display form
function showForm($errorName=false,$errorEmail=false,$errorMesg=false){
if ($errorName) $errorTextName = "Please enter your name!";
if ($errorEmail) $errorTextEmail = "Please enter a valid email address!";
if ($errorMesg) $errorTextMesg = "Please leave a longer message!";
// consider using $_SERVER['PHP_SELF'];
echo '<form action="form.php" method="POST"><table>';
// Display name field an error if needed
echo '<tr><td>Name: </td><td><input type="text" value = "'. $_SESSION['name'] . '" name="name"></td></tr>';
if ($errorName) echo "<tr><td colspan='2'>$errorTextName</td></tr>";
// Display email field an error if needed
echo '<tr><td>Email:</td><td><input type="text" value = "'. $_SESSION['email'] . '" name="email"></td></tr>';
if ($errorEmail) echo "<tr><td colspan='2'>$errorTextEmail</td></tr>";
// Display message field an error if needed
echo '<tr><td>Message:</td><td><textarea name="mesg"> '. $_SESSION['mesg'] . ' </textarea></td></tr>';
if ($errorMesg) echo "<tr><td colspan='2'>$errorTextMesg</td></tr>";
echo $_SESSION['mesg'];
echo '<tr><td><input type="submit" name="SubmitForm" value="Send"></td></tr>';
echo '<form>';
}//function end
if (!isset($_POST['SubmitForm'])) {
showForm();
}
else {
//Init error variables
$errorName = false;
$errorEmail = false;
$errorMesg = false;
$_SESSION['name'] = isset($_POST['name']) ? trim($_POST['name']) : '';
$_SESSION['email'] = isset($_POST['email']) ? trim($_POST['email']) : '';
$_SESSION['mesg'] = isset($_POST['mesg']) ? trim($_POST['mesg']) : '';
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_SESSION['email'])) $errorEmail = true;
if (strlen($_SESSION['name'])<3) $errorName = true;
if (strlen($_SESSION['mesg'])<10) $errorMesg = true;
// Display the form again as there was an error
if ($errorName || $errorEmail || $errorMesg) {
showForm($errorName,$errorEmail,$errorMesg);
} else {
echo 'Submission was success!';
}
}
?>
Ejemplo de clase para usar Postgresql (FROM http://blog.netmasters.cl/clase-para-conectar-php-con-postgresql/)
File with dabase related data
<?php
////////////////////////////////
// Datos de conexion al servidor
////////////////////////////////
// nombre del servidor de postgre SQL
$cfg->servidor = "localhost";
//puerto de conexion, por defecto es el 5432
$cfg->puerto = 5432;
//nombre de la base de datos a usar
$cfg->nombreBD = "C_11";
//nombre de usuario de la db
$cfg->nombreDeUsuario = "alumnodb2";
//contraseña de conexion a la db
$cfg->contrasena = "eps1";
?>
Postgres class
<?php
require("inc.config.php");
//--------------------------------------------------------//
// Display de Errores de PHP //
//--------------------------------------------------------//
// Para solo desplegar errores personalizados descomentar
// Para desplegar todos los errores descomentar
// ini_set('error_reporting', 'all');
//--------------------------------------------------------//
class db {
var $servidor;
var $puerto;
var $nombreBD;
var $nombreDeUsuario;
var $contrasena;
var $enlace;
var $resultado;
var $consulta;
function db(){
global $cfg;
$this->servidor = $cfg->servidor;
$this->puerto = $cfg->puerto;
$this->nombreBD = $cfg->nombreBD;
$this->nombreDeUsuario = $cfg->nombreDeUsuario;
$this->contrasena = $cfg->contrasena;
// conexion automatica al crear el objeto, para tareas no hay problema
// para produccion no es recomendable, es ideal conectar solo al momento
// de usar el objeto.
// Ejemplo:
// $objDB = new db();
// $objDB->connect();
//
$this->connect();
}
function connect(){
$sConn = "host=$this->servidor port=$this->puerto dbname=$this->nombreBD user=$this->nombreDeUsuario password=$this->contrasena";
$enlace = pg_connect($sConn);
$stat = pg_connection_status($enlace);
if($stat === PGSQL_CONNECTION_OK){
$this->enlace = $enlace;
return true;
} else {
$this->setError("ERROR: al conectar a la base de datos","die");
}
}
function query($sentenciaSQL){
if($this->consulta = pg_query($this->enlace,$sentenciaSQL)){
return true;
}else{
$stat = pg_connection_status($this->enlace);
if($stat === PGSQL_CONNECTION_OK) {
$errMen = pg_last_error($this->enlace);
$errMen = $errMen."<br>EN LA CONSULTA: \"".$sentenciaSQL."\"";
}else{
$errMen = "ERROR AL EJECUTAR: \"".$sentenciaSQL."\"<br>NO CONECTADO A LA BASE DE DATOS";
}
$this->setError($errMen,false);
}
}
function objeto(){
if($this->resultado = pg_fetch_object($this->consulta)) {
return $this->resultado;
} else {
return false;
}
}
function asociado(){
if($this->resultado = pg_fetch_assoc($this->consulta)) {
return $this->resultado;
} else {
return false;
}
}
function fetch(){
if($this->resultado = pg_fetch_array($this->consulta)){
return $this->resultado;
}else{
// entra en este caso cuando se acaban los registros
// no por error, es para que termine el while.
return false;
}
}
function num(){
if($numFilas = pg_num_rows($this->consulta)){
return $numFilas;
}else{
$this->setError(pg_last_error($this->enlace),false);
}
}
function free(){
if(pg_free_result($this->consulta)){
return true;
}else{
$this->setError("ERROR: al liberar el resultado",false);
}
}
function close(){
if(pg_close($this->enlace)) {
return true;
}else{
$this->setError("ERROR: al cerrar la conexion",false);
}
}
function setError($errMen,$return){
if($return){
die(); //detiene totalmente la ejecucion del script php
}else{
return false; //devuelve false para control externo del error
}
}
}// Fin Clase
?>
how to use the class
<?php
include ("class.db.php");
$db = new db;
$consulta = $db->query("SELECT grupo_nombre FROM grupo");
while ( $datos = $db->fetch($consulta) ) {
print $datos['grupo_nombre'] . '<br>' ;
}
?>
-- Main.RobertoMarabini - 30 Nov 2008