PHP and MySQL

  

These are my personal notes that I use as a quick help in my work.
You are welcome to read them.

Contents of current page Top-level home page
 
Index  Java Internet Oracle Notes
Linux Basics Web Basics SQL Notes
Informatica Servlets Apache BkpRstore SQL*Plus
Teradata   LDAP Storage PL/SQL
Windows     Tables OEM
UML   Net8 Portal
SQL Server Python perl Performance OLAP
Vmware Visual Basic PHP/MySQL User Mgmt  
Git        
More technical pages here

Contents

 


Introduction

  


  


Basics

Basic script, save with extenion .php

<html>
<head>
  <title>Test PHP</title>
</head>
<body>
  <?php echo '<p>Hello World</p>'; ?>
</body>
</html>

PHP tags are <?php ... ?> or <script language="php">. . .</script> (first form is preferred because it is recognized by XML or XHTML parsers). Use ";" to separate instructions. A last ";" is understood in the closing tag "?>".

# comment until end of line
// comment until end of line
/* comment */

Use <?php phpinfo(); ?> to see system information.

Browser information: <?php echo $_SERVER['HTTP_USER_AGENT']; ?>

Use "if":
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) { echo 'Using Internet Explorer '; }
?>

Forms:

<form action="action.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p>Your age: <input type="text" name="age" /></p>
<p><input type="submit" value="OK"></p>
</form>
-->
Hello, <?php echo $_POST['name']; ?>.
You are <?php echo $_POST['age']; ?> years old.

$_SERVER and $_POST are auto-global variables. Use $_GET for GET method. Or use $_REQUEST for either method. The old variables were $HTTP_*_VARS.

Pour l'installation, voir: http://ch2.php.net/manual/fr/install.php

Install PHP:

 

Main pitfalls:

 


Data Types, Variables

 

Four scalar types of values

Characters

Surround with double-quotes (not single)
ord('a string') gives code of first character in the string
chr(123)
a_string{n}: character at nth position (0 to len-1). Note: curly brackets.
Multiple replacements:
  $search = array("\n", "\r", "\t" );
  $replace = array(" ", " ", "    ");
  return str_replace($search, $replace, $the_text);

For escaping quotes, <, and >, also use htmlspecialchars('a string');

 

Strings

string '...', "..", heredoc (see below)
Casting (string). Also use functions gettype and settype
special characters: (0 () \t (tab = char 9) \\

\n CR = char 10 (0x0A) \$ $
\r LF = char 13 (MS uses \r\n sequence) \"  
\t tab = char 9 \123 Octal number
\\ backslash \x1A3 Hexadecimal

heredoc syntax:
$str = <<<eod
Example of a string
that spans several lines
eod;

Note that with "..." or heredoc syntax, the variables in the string are replaced by their values (each time a $ is encountered). Complex format is: ${var_name surrounded by rounded brackets}or {$var-name}

Extract char from string with: $a_string{offset}. Offset is 0 to len-1. (ex: $a_string='abc'; echo $a_string{2} ---> 'c').
String length: strlen(a-string)

Concatenation: '.' (before: '+')

More string functions: http://ch2.php.net/manual/fr/ref.strings.php

array

$an_array = array("whatever", 1234, "go up", TRUE); // creates an array
$an_array[1] // the 2nd element (first element has index 0)
$an_array[] = 'new element' // adds an element at the end of the array.
$an_array['abc'] = 'new element' // adds an element with key 'abc'.

Index an array with strings (keys):
$an_array = array(one_element => 'whatever', another => 'x')
$an_array[one_element] // returns the element

Multidimensional arrays: $an_array[12][34]

Array functions include: array_merge(), array_slice(), array_shift(), sort()...

see http://ch2.php.net/manual/fr/language.types.array.php

object

see http://ch2.php.net/manual/fr/language.types.object.php

resource

null : <?php $var = Null; ?> (case insensitive)

 

Other

Use var_dump() to find the type of a variable.
Use gettype(var) to display the type
Use is_type(var) to test the variable's type: if (is_int(i)) { i += 4; }
Change types with (cast)var or settype(var)

Variables:
$variable_name (always starts with $, then alphabetic then alphnumeric)

Assign by reference: $ONE_VAR = &$gla; The variable $ONE_VAR now points to the contents of $gla

$a = "ONE_VAR";
$$a = "hello world";
echo $a ; #--> "ONE_VAR"
echo $$a ; #--> "hello world"
echo $ONE_VAR; #--> "hello world" (equivalent to previous line)

Constant (no $, global by definition, names are case sensitive):
define("DBG", TRUE);
define("A_TEXT", "A text...");

Predefined variables:

Predefined constants (only some):

Watch the difference in scope definition:

<?php $a = 1;
      function Test() { echo $a; /* contains null, not same scope */ }
      Test(); ?>

Use of global keyword:
<?php $a = 1;
      function Test() { global $a; /* Refer to global version of $a */
                        echo $a; }
      Test(); ?>

Static variables (the value is assigned at first definition): static $a=value;
Note that the references to static variables may change!

 

Dynamic variables:
$var_to_hold_var_name = 'a_variable_name'; $$var_to_hold_var_name = 'whatever'; // equivalent to '$a_variable_name = 'whatever';'

 


Expressions and Operators

Assignments

$a = 1; # Simple assignement with = (no colon)
$b = ($a=1); # --> $a and $b are assigned 1
$b = $a = 1; # --> $a and $b are assigned 1, parsed right to left

$a++; ++$a;

$a += 3;

Comparisons

Operators

Arithmetic: + - * / % (modulus)

Bitwise operators: & (and), | (or), ^ (xor), ~ (not, unary), << (shift left), >> (shift right)

Logical operators: and && (different precedences), or || (different precedences), xor, ! (not, unary)

Ignore errors: @expression

Execution operator: `` (backticks, not single-quotes): equivalent to shell_exec.

Concatenation: '.' (period), '.=' (concatenating assignment operator)

Array: + (union, right-hand written into left-hand except for duplicate values that remain the same).

$a_variable instanceof A_class: is $a an instance of class A_class ?

Ternary conditional operator: cond ? if-true : if-false;

Note:
if ('') --> false
if (!'') --> true
if ('str') --> true
if (!'str') --> false
if (0) --> false
if (!0) --> true
if (1) --> true
if (!1) --> false

 

Precedence

Associativity Operators
  new
>>>
[
  ++ --
  ! ~ - (int) (float) (string) (array) (object) @
<<< * / %
<<< + - .
<<< << >>
  < <= > >=
  == != === !==
<<< &
<<< ^
<<< |
<<< &&
<<< ||
<<< ? :
>>>
= += -= *= /= .= %= &= |= ^= <<= >>=
<<< and Note: = has higher precedence
<<< xor Note: = has higher precedence
<<< or Note: = has higher precedence
<<< ,

"=" has higher precedence than "and", "or", and "xor". $x = false or true; assigns false to $x. Use $x = false || true; instead

 

 


Control Structures

See language reference

 

 

if, loops, ...

ternary conditional operator (see expressions and operators)
cond ? if-true : if-false;

 

if elseif else (note that "else if" with a space is nested):
if (cond) {
    statement;
}
elseif (cond) {
    statement;
}
else {
    statement;
}

Another syntax that allows ending the php tag and putting html:
if (cond):
    statements;
    # or html:
    ?> ..... <?php
elseif (cond):
    statements; # or html
else:
    statements; # or html
endif;

Switch

switch ($i) {
case 0: echo "i equals 0"; break;
case 1: echo "i equals 1"; break;
case 2: echo "i equals 2"; break
case -2:
case -1: echo "i < 0"; break;
default: ...; }

Remember the breaks

While

while (expr) statement

while (expr):
    statement
    break; # --> exit the loop
    statement
endwhile;

do {
    statements;
    break; # --> exit the loop
    statements;
} while (cond);

 

For

for (start expr; cond; end-of-loop expr) {
    statements;
    break; # --> exit the loop
    statements;
}

for ($i=0; $i<10; print $i, $i++) {...}

for (expr1; expr2; expr3):
    statements
endfor;

Note: separate expressions with comma

foreach

foreach ($an_array as $variable) {
    statements;
    break; # --> exit the loop
    statements;
}

foreach ($an_array as $key => $variable)
    statement

 

continue

continue [n]

Use in the same places as "break", but to end loop then to continue at the start of the new loop.
The parameter n is optional and indicates the number of nested loops to exit. The parameter n is therefore 1 by default.
In a switch, "continue 1" is equivalent to "break". However, "continue 2" exits the switch and any existing loop at the next level.

 

declare

declare (ticks=1) statement

See reference documentation

include, require

include (file-name-or-variable-containing-file-name)
require (file-name-or-variable-containing-file-name)

Include and evaluate a given file.
Include produces a warning in case of failure; require produces a fatal error in case of failure.

include_once (file-name-or-variable-containing-file-name)
require_once (file-name-or-variable-containing-file-name)

Include and evaluate a file only once

Add this before the statement to define the path:
include_path="/php/includes"
For files in the current directory, "./file_name" in the include statement is more efficient.

 

functions

function foo($arg_1, $arg_2, &$arg_by_reference, ... $arg_n=default_value) {
    statements;
    return $retval;
}

Default values only useful in arguments at the end.
Argument by reference with ampersand.
Use & to indicate argument by reference
global $a_variable; tells the function to use a variable declared outside the function; note however that if the value is modified, the "original" value is changed, meaning that a copy is not made.

Conditional functions:

if ($makefoo) {
   function foo() {
     ...echo "I don't exist until program execution reaches me.\n";
   }
}

Function inside function:

function foo() {
   function bar() {
     ...
   }
}

Function names are case-insensitive

return;
return expr;

End execution of function and return the value.

 

 


Classes and Objects

 

See http://ch2.php.net/manual/en/language.oop.php

 

 

Databases - sqlite

Need this in php.ini:
extension=php_pdo.dll
extension=php_sqlite.dll

Correct location of temporary folder: putenv('TMP=C:/temp');

 

PDO - PHP Data Objects

Connection:
try {$dbh = new PDO("sqlite:database_file.db3"); }
catch(PDOException $e) { echo $e->getMessage(); }

Create database in memory: $db = new PDO("sqlite::memory");

For MySQL: $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
For ODBC: $dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\...\a.mdb;Uid=Admin");

close the database connection: $dbh = null;

Execute a statement:
$count = $dbh->exec("INSERT INTO animals(animal_type, animal_name) VALUES ('kiwi', 'troy')");
echo $count;

Query:
foreach ($dbh->query($sql) as $row)
{ print $row['one column'] .' - '. $row['another column'] . '<br />'; }

continue with http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html at the section on fetch modes.

 


Pre-defined Functions

round(), floor(), ceil()
  
gettype()
Get the type of an object
settype
Set the type of an object. Similar to cast, but does not make a copy. Cast makes a copy and does not touch the original object.
(int) or (integer)
Convert to integer
strlen(a-string)
Returns string length
strval(...)
Returns equivalent in string
get_class(..)
returns the name of the class for objects
string strtr ( string str, string from, string to)
Within str, replace characters in from with the characters in to. Ex: strtr(..., "éàè", "eae"). Also use an array with pairs.
int substr_count ( string haystack, string needle)
Returns the number of occurences. Case sensitive.
int strpos ( string haystack, string needle [, int offset])
Return position of first occurence
0 === strpos($h, $n) to test if the first parameter starts with the second
strpos(strA, strB)
Return true if strB is inside strA
substr(str, start_pos [,length])
Return sub-string. Start_pos can be negative.
string substr_replace ( string str, string replacement, int start [, int length])
Replace part of str with replacement. Determine part to replace with start (if negative, then count from the end). Or try SQLite3::escapeString.
trim
sadf
string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]])
Pad with spaces or pad_string until reaching the total length pad_length. pat_type takes: STR_PAD_RIGHT, STR_PAD_LEFT or STR_PAD_BOTH.
strtolower ( string str), strtoupper ( string str)
Convert to lower / upper. Accents handled according to localisation.
string trim ( string str [, string charlist])
Remove spaces, tabs, \n, \r, nul, \x0B. Specify the list of characters to remove with " \t\n..."
htmlspecialchars($a_variable, ENT_QUOTES)
Translate < into &lt;, > into &gt;, " into &quot;, and ' into &#039;
addslashes(str)
Add slashes before single quote ('), double quote ("), backslash (\) and NUL (the NULL byte)
"select ... where x='" . SQLite3::escapeString(str) . "';"
Prepare string for safe inclusion in a SQL statement, in particular by escaping single quotes.
base64_decode -- Decode MIME base64
base64_encode -- Encode MIME base64
get_headers -- Return the headers from an HTTP request
get_meta_tags -- Extract metadata tags from an HTML file
http_build_query -- Generate a request in encoded URL
parse_url -- Parse a URL
rawurldecode -- Decode a URL string
rawurlencode -- Encode URL string according to RFC 1738
urldecode -- Decode URL
urlencode -- Encode URL
Various URL string functions
 
 
 
 
 

Header

Redirection:
header("location:http://www.phpeasystep.com");
or
echo "<meta http-equiv='refresh' content='0;url=http://www.phpeasystep.com'>";

 

 

 


MySQL Installation

 

Reference manual on-line:
http://dev.mysql.com/doc/refman/5.0/en/index.html

 

Installation:

Installation on Ubuntu:

If MySQL is defined as a service, then start and stop the service.

To remove the MySQL service:
"C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld-nt.exe" --remove

 

Some values for mysql.ini:

Installation for Drupal

Installation for Drupal

Check that the host allows database accounts with the following rights:
SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES.

 

Create the MySQL database

In easyphp: entered the admin. SQLadmin actually shows on the same line as phpadmin
in the sqladmin, created a new database drupaldb with utf8_bin: best is to use the use the create db option in databases tab

CREATE DATABASE 'drupaldb' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
drop user 'drupal_username'@'localhost';
CREATE USER drupal_username@localhost IDENTIFIED BY 'drupal_username_pw';
GRANT USAGE ON *.* TO drupal_username@localhost IDENTIFIED BY 'drupal_username_pw'
WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
GRANT SELECT , INSERT , UPDATE , DELETE , CREATE , DROP , FILE, INDEX ,
ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, --(in the part on the right if in GUI)
CREATE VIEW ,SHOW VIEW ,CREATE ROUTINE, ALTER ROUTINE, EXECUTE
ON drupaldb.* TO drupal_username@localhost;

 

I also did:
SET PASSWORD FOR 'root'@ 'localhost' = PASSWORD( '******' )
Don't do it again. I had to reinstall easyPHP

 

Lock-down MySQL

Best practises:

See more at http://www.securityfocus.com/infocus/1726 and http://dev.mysql.com/doc/refman/5.0/en/security-against-attack.html and http://www.builderau.com.au/program/mysql/soa/Six-steps-to-secure-sensitive-data-in-MySQL/0,339028784,339266102,00.htm

 

Backup

mysqldump -uthe_user_name -p -hlocalhost [options] the_db_name > dump_file
The name of database after the options (or --all-database, but beware of a restore that will try to restore the system tables: backup database by database instead). Use root or debian-sys-maint.

Put password in a separate file then do -p`cat a_file` (with backticks, and no space after -p)

Restore by executing the queries in the dump file, or doing cat dump_file | mysql -u debian-sys-maint -p`cat the_file`.


Connection to Databases

 

$conn=odbc_connect('odbc_connection','username','pw', 'optional cursor type');
if (!$conn)
{exit("Connection Failed: " . $conn);}

$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}

while (odbc_fetch_row($rs, optional_row_number))
   {
    $first_column = odbc_result($rs,1);
    $a_variable = odbc_result($rs,"the_field_name");
   }

odbc_close($conn);

More details, see http://us2.php.net/odbc

 

DOS Command Line:
cd C:\....\xampp\mysql\bin
mysql.exe --help

 

Sample code for connecting to database
<script language="php">
$conn=odbc_connect('country_data','','');
if (!$conn)
  {exit("Connection Failed: " . $conn);}
$header_displayed = 0;
$sql="SELECT * FROM country_information";
$rs=odbc_exec($conn,$sql);
if (!$rs)
  {exit("Error in SQL: " . $sql);}
while (odbc_fetch_row($rs))
   {
   if ($header_displayed == 0)
     {// display header
     echo "<table><tr>";
     $num_of_fields = (int) odbc_num_fields($rs);
     //echo "number of fields " . $num_of_fields . gettype($num_of_fields);
     for ($i=1; $i<=$num_of_fields; $i++)
       {echo "<th>" . odbc_field_name($rs, $i) . "</th>";}
     echo "</tr>";
     $header_displayed = 1;
     }
   echo "<tr>";
   for ($i=1; $i<=$num_of_fields; $i++)
     {echo "<td>";
     echo odbc_result($rs,$i);
     echo " </td>";
     }
   echo "</tr>";
   }
echo "</table>";
odbc_close($conn);
</script>

 

First Connection

Connect to a running database with:
mysql -h localhost -u root -p
The more general syntax is (note that the -p requires the password to follow without a space. What follows the space is the database on the server):
mysql -h the_host -u the_user -p the_database
For more recent installations, see under "installation": mysql -u debian-sys-maint -p

Get information about the database:
show databases;
select database(), user(), version();
select host, user, password from mysql.user;

Some basic commands:

show databases;
Display the list of databases on the server
use the_database
Set one of the databases as current
select database();
Display the database that is currently set
create database a_db;
Create a database
SELECT table_schema, table_name, table_type FROM information_schema.tables WHERE table_schema = 'MYSQL';
Get metadata
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

ADODB - database abstraction library for PHP

http://adodb.sourceforge.net/
http://phplens.com/lens/adodb/tute.htm
http://adodb.sourceforge.net/#docs

 


MySQL Functions

 

Functions

curdate()
The current date
current_date
The current date
now()
Current date and time
user()
Current user
version()
Database version

Wildcards: % and _ (percent sign and underscore)

To load from a tab-delimited file, use:
LOAD DATA LOCAL INFILE 'C:\\the_path...\\the_data.txt'
INTO TABLE the_data
LINES TERMINATED BY '\r\n';

Use "\N" in the data file to indicate a null.
Escape the quotes: \' and \"

 


MySQL User Management

 

 

See users who have logged in:
select host, user from mysql.user;

Create a user:
CREATE USER 'a_user'@'localhost' [IDENTIFIED BY 'password'];
GRANT ALL ON db_name.* TO 'a_user'@'localhost' [WITH GRANT OPTION];

Set the password on Windows (the_user_name is blank for the anonymous user):
SET PASSWORD FOR 'the_user_name'@'localhost' = PASSWORD('newpwd'); (only local connection)
SET PASSWORD FOR 'the_user_name'@'%' = PASSWORD('newpwd');
(connection from any server)
Set the password on UNIX (the_user_name is blank for the anonymous user):
SET PASSWORD FOR 'the_user_name'@'localhost' = PASSWORD('newpwd');
SET PASSWORD FOR 'the_user_name'@'the_host_name' = PASSWORD('newpwd');

Get the host hame from: select host, user from mysql.user;

Another option for setting the password is (the_user_name is blank for the anonymous user):
UPDATE mysql.user SET Password = PASSWORD('newpwd') WHERE User = 'the_user_name';
FLUSH PRIVILEGES;

The FLUSH PRIVILEGES forces MySQL to read the grant tables.

Delete a user:
DELETE FROM mysql.user WHERE Host={'localhost' | 'the_host_name'} AND User = 'the_user_name';
FLUSH PRIVILEGES;

The users are defined by their username and their host. The host is a hostname, "localhost" or an IP address.
Privileges are determined for connection and for executing statements.

 

 


PHP

mysql_connect ( 'localhost:3306', 'username', 'pw'[, bool new_link [, int client_flags]] )
Connection to the server. Instead of localhost, put the name of the server (and the appropriate port number). The default values for the username and the password will enable not entering the username and password here. "bool_new_link" is used for multiple connections.
 
 
 
 
 
 
mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]] )

 

 

 


Kohana

 

 

Installation

Modify these files:

 


Drupal

 

 

Links

Try this:
http://support.bryght.com/adminguide/how-to/dynamic-web20-brochure-site-in-an-hour

read http://drupal.org/node/165706 : Using the theme layer (Drupal 6.x)

continue page 17

CSS

When working with style sheets, make sure CSS aggregation is disabled. It is located in "Administer > Site configuration > Performance". When it is enabled, any alterations will not be reflected on your site until the aggregated styles are cleared. You can enable it again when you're done. The .info file is cached. Adding or removing any styles will not be noticed until it is cleared. (Do not confuse this with the theme registry.) To have it cleared, do one of the following:

Show active menu item
.menu .leaf .active {border:1px solid #D2691E;}

Dropdown menus:
http://drupal.org/node/190263

 


Drupal 8

 

 

Installation

Some links

 


Drupal - User Management

 

 

User Management

Protect user id 1 account (uid1). Do not use it for regular users

User management

When defining the automatic email that goes out to new users,
!username, !site, and !date are placeholders

See more at http://drupal.org/node/132202

Roles

all defined users also get the permissions for authenticated users
Authenticated user should get all that an anonymous user has, plus more
Create roles for specific modules or types of users
Assign combinations of roles to the users

 


Drupal - Content and Content Types

 

 

Content

see modules to enable funcationality
see administer > content management to configure the modules
see create content
see administer > user management > permissions to configure permissions by role
The type of content that users can create is determined in
user management > permissions > node module

Content types

See Home > Administer > Content management
For book, in workflow settings, choose "Published", "Create new revision"
Enable the attachments

Look at existing content in
Home > Administer > Content management
Here, see new content that has to be published.
Publish both by setting the "published" option and by defining a menu label

 

Filters and Input Formats

An input format is an ordered collection of filters. Filters modify a text. Many options, such as filtering out un-wanted HTML tags. The original text is saved in the database
The core filters are:

See site configuration > input formats
Then choose which filters to apply when defining content

I can use an HTML filter in another input format and define a separate list of tags

Forums

Containers and forums are inside each other
Publish at least one forum to see the menu appear

Comments

Comments are added to nodes. Comments are a different content type.

Comments are possible in many places.
You can view all comments to unpublish or delete. Unpublish keeps but hides
unpublished comments are in the approval queue (see upper right)

Each content type has different default settings for the associated comments
See each content type separately

Story

Seems best for small news articles.

Books

create new book pages: create content >> book page.
administer individual books (choose a book from list): administer >> content >> books.
set workflow and other global book settings at administer >> settings >> content types >> book page.
enable the book navigation block: administer >> block.
control who can create, edit, and maintain book pages at administer >> access control.

Attachements in a book page show as a list of attachments

Upload files

enable/disable uploads for individual content types at administer >> settings >> content types.
administer storage location of uploaded files at administer >> settings in the File system settings area.
configure file size, file extensions, and other user role defaults at administer >> settings >> file uploads.
control who can upload and view attached files at administer >> access control.

Spam Prevention

Filters:
External Links
Gotcha - Contact Spam Catcher: makes a form more resistent to spam

Comment forms, contact forms and signup pages are all susceptible to spam.
- Comment Moderation
made simpler via the contributed module called Notify.
- CAPTCHA
- Anti-Spam Services
typically need to sign up with the service for a free API key which allows you to
send requests to their servers.

Taxonomy

Use default views based on taxonomy:
Display the one of the nodes for the term, copy the path that accompanies every node, and make a menu item out of it.

Create pages based on taxonomy. This groups several posts together on one page.

 


Drupal Installation

 

 

Created a sub-directory html under www: www/html

Sub-directory name: build the new directory name from the site's URL. For example 'sites/example.com/settings.php' (omit the 'www.' if users access site at http://example.com/).

Installed the database: see Drupal MySQL

In the database defiition: add the database host in the advanced options

For server permissions, set the following at the beginning of the process:
chmod o+w sites/default/files
chmod o+w sites/default/setting.php
After the database creation, protect the setting.php file with read-only permissions (the installation process will prompt you):
chmod 444 sites/default/settings.php
See also http://drupal.org/server-permissions

 

Other installations

Copy the 'default' directory and modify the 'settings.php' file as appropriate. Build the new directory name from the site's URL.

When using a non-standard port, the port number is treated as the deepest sub domain. In the case http://www.example.com:8080/, the sub-directory is sites/8080.www.example.com/.

Clone a Site

Removed a line in the database backup

First created the database with the phpadmin gui (see in MySQL notes): imported the script using the import on the target database

Restored the database by executing the sql backup file in the phpadmin gui. Upload the complete SQL file instead of pasting the contents in the window. See the import tab.

Moved the files to the drupal directory

In sites/default/settings.php:
$db_url = 'mysql://drupal_username:the_pw@localhost/the_drupaldb';
$base_url = 'http://localhost/drupal';

I can see the main page, but the menus do not work. It is because I have to add the as ?q=

If file system is private or outside the path, then define the new path in Home > Administer > Site configuration > File system. See also "File System" further below in this section.

 

Basic Configuration

Language: enable the language module then configure in http://website/admin/settings/language. Add language from drop down.

The general layout is defined both in "blocks" (http://website/admin/build/block), in the configuration of individual themes, and in http://website/admin/build/themes/settings

 

Move the Root Directory

Clean URLs

Enable it if possible. I could not on my PC
(If stuck and can't return to previous configuration, go here: ?q=admin/settings/clean-urls)

Error pages

Create a page (create content > page)
Note the link
In the error reporting page, set the 404 page to the link above

File System

public is recommended
If private, the path should be outside of the document root.
Put fully qualified path
The directory must be writable: chmod a+w .
Also temp dir

Test uploading: enable the upload module in the modules section.

The temporary directory is defined in
Home > Administer > Site configuration > File system

Create a file called favicon.ico in the Windows Icon (.ico) format. put the file in the root of drupal and in the misc folder.

 

 


Drupal - Modules

 

 

Recommended modules

Some references

Installing Modules

Images

It looks like image module allows better management of the thumbnail on the teaser and bigger picture in the main story, whereas imce allows ckeditor to make a nice page.

help with image cache:
http://drupal.org/node/224913
http://drupal.org/node/163561

Image module with Image assist, the Gallery module, and Acidfree

Also see:

CKeditor

Two downloads are necessary:

For the component, go to the CKeditor homepage http://www.ckeditor.net/download to download the latest version. Extract the files to sites/all/modules/ckeditor/ckeditor/ and make sure that the directory sites/all/modules/ckeditor/ckeditor/editor and the file sites/all/modules/ckeditor/ckeditor/ckeditor.js exist. Refer to the readme.txt for more information.

The correct directory structure is:
modules
   ckeditor
      ckeditor.module
      ckeditor
         _samples
         editor
         COPY_HERE.txt
         ckconfig.js
         ...

Documentation in http://docs.ckeditor.net/ckeditor/Users_Guide. Also, see small reference.
Configure in: Administer > Site configuration > CKEditor

Note that config.php at sites\all\modules\fckeditor\fckeditor\editor\filemanager\connectors\php does not like the aliases that I set up with XAMPP. It worked better in prod where there were no aliases.
Make sure that security is set up in the file: $Config['Enabled'] = true ;

Background for the editor: In the CKEditor profiles (I guess each profile), under "CSS". For "Editor CSS", choose CKEditor default

Define the ckeditor permissions in both places:
access ckeditor permission in http://website/admin/user/permissions
assign ckeditor roles to the drupal roles

 

IMCE

First define the profiles in IMCE.
CKEditor and IMCE: In the CKEditor profiles (I guess each profile), under "File Browser Setting". Choose IMCE in File browser type drop-down (Image dialog)

You may have to add the <img> tag to the input filter.

Image Module

Galleries under content management
"Image" is also a content type
See "image toolkit" under Administer > Site configuration > Image toolkit and "images" under Administer > Site configuration > Images
In each of the existing content types (page, story, or other), enable the ability to attach images

The images are stored in the directory defined in "filesystem", which is in the sub-directory defined in "site configuration > images"

I guess there is an implicit view: the link shows at the bottom of one of the pages displaying an image: ...image/tid/3

Misc. Notes on Modules

 

 


Drupal - XAMPP

 

 

 

 

 

xampp admin is in http://localhost/xampp/

Location of configuration files . Also has other tips.

Security: http://localhost/security/

In Xampp
CREATE DATABASE 'the_database_name' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Create user the_user_name/the_password
SELECT, INSERT, UPDATE, DELETE,
CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES,
LOCK TABLES (in the part on the right)
CREATE USER 'the_user_name'@'localhost' IDENTIFIED BY '*****';

GRANT SELECT , INSERT ,UPDATE ,DELETE ,CREATE ,DROP ,FILE ,INDEX ,ALTER ,CREATE TEMPORARY TABLES ,
LOCK TABLES ,CREATE VIEW ,SHOW VIEW ,CREATE ROUTINE, ALTER ROUTINE,
EXECUTE ON * . * TO 'the_user_name'@'localhost' IDENTIFIED BY '*****'
WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

imported the script using the import on the target database

The page http://drupal.org/node/75537 gives suggestions on installing drupal with xampp

Defined %your_drupal_files% as C:\chris_bis\projects\barpcv\wwwroot

Edit C:\chris_bis\projects\barpcv\wwwroot\sites\default\settings.php
$db_url = 'mysql://drupaluser:dr123@localhost/the_database_with_drupal_tables';
$base_url = 'http://localhost/drupal';

Edited
...\xampp\apache\conf\extra\httpd-xampp.conf

Alias /drupal "...\wwwroot/"
<directory "...\wwwroot">
AllowOverride All
# AllowOverride All FileInfo changed Nov 26
# AllowOverride AuthConfig FileInfo
Order allow,deny
Allow from all
#AllowOverride AuthConfig FileInfo The AuthConfig did not seem to work.
</directory>

Edited ...\xampp\apache\conf\httpd.conf
Uncommented the line with "LoadModule rewrite_module modules/mod_rewrite.so"

Edited ...\wwwroot\.htaccess
Uncommented the list:
RewriteBase /drupal

In local XAMPP, set the local directory to "tmp_files" in
Home > Administer > Site configuration > File system
admin/settings/file-system
which corresponds to ....\wwwroot\tmp_files

Have to use version 1.7.1 of xampp, because of compatibility between PHP version and drupal

I had to edit the file [path_to_xampp]/apache/conf/httpd.conf.
See http://drupal.org/node/43545
Move the line and remove the # at the beginning:
LoadModule rewrite_module modules/mod_rewrite.so
to just above or below
#LoadModule cache_module modules/mod_cache.so

If the mod_rewrite change does not work, you also need to check that AllowOverride All is set for the directory Drupal is in. Do this in httpd.conf or extra/httpd-xampp.conf

When downloading a new site, you must keep the hidden .htaccess file too

 


Drupal - Navigation

 

 

Navigation

Link: http://drupal.org/node/55610

Primary/Secondary Navigation
administer >> themes
only way to add horizontal navigation without directly embedding it in the template.
not consistent among templates or Drupal versions: text area in the template to enter HTML or fields are given for menu text and link targets.
Some templates provide the CSS to create a tabbed look if you use <ul>/<li> markup
Breadcrumbs do not work

The Menu Module (part of Drupal base installation, called core)
external websites not always supported
Breadcrumbs do work down to the content level. reflect the menu hierarchy except at the final content page


The Book Module
hierarchical organization module, making it an option for site navigation.
Breadcrumbs work

Taxonomy
not navigation, but a classification system

Hard-Coded HTML Block

administer menus at administer >> menus.
add a menu at administer >> menus.
add a menu item at administer >> menus >> add menu item.
modify menu settings (in particular, to specify a menu to use for primary or secondary links) at administer >> settings >> menus.
manage menu blocks at administer >> blocks.

The navigation menu does not appear in the barpcv sub theme. I can't figure out why.
I started modifying the barpcv.css
Is it because there is no content yet?
Will I have to overwrite the page template?

Menus

Three default menus
Add more in
administer > site building > menus > menus
They only show when you tell where in the blocks it should appear

In the settings:
default menu for content: this is where new content appears by default

The path
<front>
refers to the front page. Set the parent to one of the menus. Expanded makes no sense since you only want the front page

The primary links are displayed in the upper right by default in the default theme, but this depends on the theme.
The primary links may not even be displayed!
Secondary links can be set the source for secondary links to be the primary links. Then the children of any selected
primary link item will show in the secondary links
I did this. The secondary links in the header did this behavior. But not the secondary links on the side bar (which I added)

I added an item on all menus to adminstrate that menu

Note that on the DHTML menu, repeating a link makes it show both as a parent item and a child of itself
This is important because clicking on the main link just opens and closes it and does not lead to a page with DHTML

base URL

shown in Home > Administer > Site configuration > Site information
The part in the text box is the relative address
This defines the default page

..../?q=forum in the link for a given page means put the part after the = sign in the path

menu:

put many of the items as sub-items so that the menu fits on one line put secondary menu in the header. the header is actually the top part of the main section

Set:

Source for secondary links: primary links (in drop down)
In Home > Administer > Site building > Menus

Primary links and Secondary links are also enabled at the theme level: see the theme configuration

 


Drupal - Themes

 

 

Editing
C:\chris_bis\projects\barpcv\wwwroot\sites\all\themes\a3_atlantis\style.css

Installing Themes

The process of installing a theme is very similar to the process of installing a new module with two key
differences. First, you upload the theme to the 'sites/all/themes' folder on your webserver. Second, in
order to activated the new theme you need to click on the Themes link under the Site Building section.
Once there you should see a list of all the available themes for your site.
Drupal allows you to have multiple themes enabled at any given time, but only one can be the default
theme. Users that are not logged in will always see the default theme when they visit the site. So take a
second after making theme changes to ensure you have the proper theme set as the default theme.

Zen theme

See http://drupal.org/node/201428

Upgrade the theme:
If you are replacing the Zen theme on a live server, place your site in maintenance mode.
Download the latest Zen from http://drupal.org/project/zen
Remove the zen folder from your Drupal installation.
Unpack the downloaded file and place the new zen folder in your Drupal installation in the same place as the previous zen theme used to be.
Turn off maintenance mode.

Sub-themes:
zen and your sub-theme will be installed in sites/all/themes/

To clear the theme registry, do one of the following things:
Clear button located at "Administer > Site configuration > Performance".
With devel block enabled (comes with devel module), click the "Empty cache" link.
The API function drupal_rebuild_theme_registry.

the image file path starts with sites/all/....

The following are also enabled at the theme level: see the theme configuration:

Display

Enable or disable the "submitted by Username on date" text when displaying posts in the configuration page of the themes.

 


Drupal - Maintenance

 

 

Backup Database

Backup a database in phpadmin

Backup a database on command line

mysqldump -uroot_user -p the_database_name > the_file_name.sql
(No spaces between the letter in the option and the content. Empty -p option for password forces a prompt for the password.

http://www.pair.com/support/knowledge_base/authoring_development/using_mysql.html

Get the password from the $db_url parameter in sites/default/settings.php file

Recover

See also Drupal - Installation.

Upgrade a theme

Upgrade the site

Preparation

This is the actual update

The modules are installed in sites\all\modules.
The files for the general installation of Drupal contain no files for

Logging

View watchdog logs at Administer >> Logs >> Recent log entries (admin/logs/watchdog).
Configure the length of time logs are archived at Administer >> Site configuration >> Error reporting (admin/settings/error-reporting).