Script

Filter
2004-12-20

Ta emot formvariabler

Php
Ett sätt att kolla formulärvariabler utan att få felmeddelanden
if (empty($_POST['field']) {
    $field = "Default value";
} else {
    $field = $_POST['field'];
}

/*
Note that empty() does not generate an error if the variable is not set, so this should work fine.
*/ 
2004-12-15

Undvik spam

Javascript
Undvik att agenter samlar upp epostadresser på dina websidor som sedan spammas
<script type="text/javascript"><!--
    user ="me";
    domain ="mydomain.tld"; 
    document.write('<a href="mailto:' + user);
    document.write('@' + domain + '">');
    document.write(user + '@' + domain + '</a>');
// --></script> 
2004-12-07

Gästbok

Php
En komplett enkel gästbok i PHP
<html>
<head>
<title>Gästbok</title>
</head>
<body>
<table border="0" width="400" align="center">
<form action="gastbok.php" method="post">
<tr>
<td colspan="2">Namn...<br />
<input name="namn" type="text"><br />
Skriv i gästboken...<br />
<textarea cols="45" rows="4" name="inlagg" wrap="virtual"></textarea><br>
<input type="submit" value="Skicka"></td>
</tr>
</form>
<?php
$conn = mysql_connect("localhost", "user", "pass");
mysql_select_db("database", $conn);
if (isset($_POST["namn"]) &&  isset($_POST["inlagg"])) {
    $namn = str_replace("'", "''", trim($_POST["namn"]));
    $inlagg = str_replace("'", "''", trim($_POST["inlagg"]));
    if ($namn != "" && $inlagg != "") {
        $sql = "insert into gastbok (namn, inlagg, datum)";
        $sql .= " values('" . $namn . "', '" . $inlagg . "', '" . date("Y-m-d" , time()) .    "')";
        mysql_query($sql, $conn);
    }
}
$sql = "select * from gastbok order by datum desc";
$rs = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($rs)) {
    echo "<tr>\n<td><b>" , htmlspecialchars($row["namn"]), "</b></td>\n";
    echo "<td align=\"right\">", $row["datum"], "</td>\n</tr>\n";
    echo "<tr>\n<td colspan=\"2\">", htmlspecialchars($row["inlagg"]), "</td>\n</tr>\n";
}
mysql_close($conn);
?>
</table>
</body>
</html> 
2004-12-01

Optimera PHP

Php
Gör dina php-sidor snabbare och effektivare
1. Avoid functions if not necessary
2. Use an Optimizer
   a) Zend Performance Suite comes with Zend Optimizer bundled ($)
   b) IonCube's PHP Accelerator
   c) Alternative PHP Cache (APC)
3. RTFM
   Use: echo "Foo ", somefunc(), " Bar";
   Not: echo "Foo " . somefunc() . " Bar";
4. Get your loops right first (most effective)
   a) Dont call functions in condition
   b) No loop-invariants (ie calcultating static values each iteration)
   c) Pre-increment where possible (++$i instead of $i++)
5. Free resources. Use unset(), mysql_free_result()
6. Use the most verbose error level, E_ALL, to track even minor optimizations
7. Disable the extensions you don't use
8. Keep PHP up to date, however:
   The early bird may get the worm, but the second mouse gets the cheese.
9. Cache array data (ie in a variable outside a loop, se 4b)
10.Compress your output
   a) enable output buffering 
   b) Use gzip compression for the buffers
   (set output_buffering to 1 and output_handler to ob_gzhandler in php5.ini)
11.Don't use CGI
12.Don't use dl()
13.Debug your code (error generation takes time and resources)
14.Cache your pages
15.Use persistent connections ( mysql_pconnect() rather than mysql_connect() )
16.Take advantage of new features, ie:
   Use: $contents = file_get_contents("test.txt")
   Not: $contents = implode("\n", file("test.txt"))
17.Avoid mod_access if you can (no .htaccess files)
18.Or, at least, dont have too many subdirectories
2004-12-01

Optimera MySQL

Mysql
Snabba upp och effektivisera din mySQL-databas
1. Prioritise your data:
   DELETE LOW_PRIORITY FROM Table WHERE ID = 235; // Stops the php-script until ready
   SELECT HIGH_PRIORITY FROM Table ORDER BY Name; // Only selects
   INSERT LOW_PRIORITY INTO Table VALUES (Foo);
   INSERT DELAYED INTO Table VALUES (Foo); // Only inserts, queues the query, continues php
   UPDATE LOW_PRIORITY Table SET Password = 'g0d';
2. Defragment data:
   OPTIMIZE TABLE table [, table2, ...]
3. Select as little data as possible:
   Use: SELECT ID FROM usertable WHERE Username = 'TelRev' LIMIT 1;
   Not: SELECT * FROM usertable WHERE Username = 'TelRev';
4. Use shorter queries where possible
5. Spot problems with the EXPLAIN statement
6. Change your hardware (Mem, HD, CPU)
7. Choose your data types carefully
8. Size vs. Speed - Char vs. Varchar
   If you use Char, use it in ALL char fields
   Consider splitting off variable-length fields into other tables
9. Declare fields NOT NULL:
   So MySQL doesnt have to check for it
10.Load data intelligently:
   a) Create the table without any indexing
   b) Add all the fields
   c) Add the indexes
11.Activate the slow query log to spot and change them
   Enable it in (my.cnf)
   Start up MySQL with option
   a) --log-slow-queries = /var/log/wherever/you/want/it
   b) --log-long-format = /var/log/wherever/you/want/it
12.Perform joins carefully
13.Index your data, ie:
   ALTER TABLE mytable ADD INDEX idxmyindex(fieldname)
14.Make sure your indexes are being used, ie:
   SELECT * FROM mytable USE INDEX (Name) WHERE Name = 'Joe' ;
15.Normalize your tables
16.Upgrade MySQL
17.Increase your buffers, and key- and query cache (my.cnf)
   a) set-variable = key_buffer_size=128M
   b) set-variable = sort_buffer_size=8M
18.Check info about mysql
   a) STATUS;
   b) SHOW STATUS;
19.Check the key cache:
   a) MyISAM: SHOW STATUS LIKE '%key_read%'; // 1) from cache 2) from disk
   b) InnoDB: SHOW InnoDB STATUS;            // Buffer pool hit rate
       0 - 80% = Very bad. More RAM?
	  81 - 95% = Not so good. Increase buffer sizes
	  96 - 98% = Good.
	  99+%     = Perfect
20.Lock your tables when appropriate (Take care! Min 100 writes)
   mysql_query("LOCK TABLES mytest WRITE;");
   for ($i = 1; $i < 100000; ++$i) {
     mysql_query("INSERT INTO mytest (Value, Value2, Value3) VALUES ($i, $i, $i);");
   }
   mysql_query("UNLOCK TABLES;");
21.Don't rely on automatic type conversion
22.Benchmarking:
   a) Mysql:
   mysql> select benchmark(int times_to_run_a_query, str expr);
   (Always results in 0 and shows the time in the client program)
   b) PHP:
   print "Start: ", microtime(true);
     for ($i = 1; $i < 100000; ++$i) {
       mysql_query(str expr);
	 }
   print "End: ", microtime(true);
🙂