Browsing all articles in PHP
Dec
11

PHP 6 Features

Author admin    Category IT News, PHP, Programming     Tags

PHP 6′s Status

Several books have already been written and published about PHP 6, such as Professional PHP6 by Edward Lecky-Thompson & Steven Nowicki. Despite this, PHP6 does not exist yet. There is no PHP 6 beta or even alpha. PHP 6 does not exist.

To see that PHP 6 doesn’t exist yet, see PHP’s official Subversion page. Subversion, or svn, is the source code control software used for the development of PHP. There are instructions for getting the code for PHP 5.3 or 5.4, but not for any newer version:

PHP 5.3: svn checkout http://svn.php.net/repository/php/php-src/branches/PHP_5_3 php-src-5.3
PHP 5.4: svn checkout https://svn.php.net/repository/php/php-src/branches/PHP_5_4 php-src-5.4

As you can see here from the branches in the PHP source code the newest branch is PHP_5_3:

  FIRST_UNICODE_IMPLEMENTATION/	 296285	 16 months	 derick	 - Committing my session cookie patch; it's a bug fix and good to have in the h…
...
  PHP_4_4/	 295390	 16 months	 derick	 - Set-up externals for the Zend engine so 4.4 can at least be build from SVN a…
  PHP_5_0/	 284180	 2 years	 gwynne	 one more attempt at ridding us of some of those annoying mime types
  PHP_5_1/	 284180	 2 years	 gwynne	 one more attempt at ridding us of some of those annoying mime types
  PHP_5_2/	 311125	 2 months	 dmitry	 Fixed crash on recursive error handler invocation
  PHP_5_2_WITH_DRCP/	 284180	 2 years	 gwynne	 one more attempt at ridding us of some of those annoying mime types
  PHP_5_3/	 313616	 31 hours	 scottmac	 When we have a blocking SSL socket, respect the timeout option. reading from SS…
  PHP_5_4/	 313646	 3 hours	 stas	 No E_STRICT in production

(Older code branches omitted for brevity.)

There’s no PHP 6 code branch yet. Notice the FIRST_UNICODE_IMPLEMENTATION branch – the story behind this code branch, and why it delayed PHP 6 follows.

What does exist is an official todo for PHP 6, authored by Andrei Zmievski, which includes a rough list of PHP 6 features in the PHP Wiki.

UPDATE 21 July 2011: Now the PHP 5.4 Alpha has been released, a PHP 6 branch may exist for PHP’s developers without showing up on PHP’s public subversion. The code for PHP 5.4 did not show up on the sites above until the PHP 5.4 Alpha was released.

Reasons for Delays to PHP 6

The reasons for the delay to PHP 6 appear to be:

  1. Issues with Unicode support: The development team initially decided to use UTF-16 internally in PHP 6. This causes double memory usage for strings, more CPU usage and increased complexity of coding PHP 6. Using UTF-16 apparently took a lot of fun out of developing PHP, caused tension amongst PHP’s developers and slowed development. The choice to use UTF-16 was aborted by Rasmus Lerdorf, creator of PHP, in 2010. The developers restarted the Unicode implementation.
  2. PHP 5.3 took some PHP 6 features: PHP 5.3 included many of the features slated as desirable for PHP 6. This removed a lot of momentum for PHP 6.
  3. High Hopes: PHP 6 is a major version number change. It’s possible in a major release to make significant changes, including making breaks from the past. Agreeing and delivering major changes can take some time.
  4. Feature Set Not Finalized: Agreement hasn’t been reached on the features in PHP 6.0.
  5. Lack of Urgency: PHP works very well. There are no burning issues forcing the release of PHP 6.
  6. PHP 5.4 takes some PHP 6 features: Rasmus Lerdorf previously stated, when he scrapped PHP 6′s original Unicode implementation, that there may be a PHP 5.4 yet, or PHP may go straight to version 6. Jani Taskinen created a PHP 5.4 development branch on 11 March 2010, but this appears to be due to frustration as being able to move PHP’s development forward. The PHP 5.4 code branch is no longer there. There is however an official PHP 5.4 todo wiki, with Stanislav Malyshev as the tentative release manager. So it looks there will be PHP 5.4, which would push out the PHP 6.0 release further. UPDATE on 24 July 2011: The PHP 5.4 Alpha has been released, and it includes some features originally targeted for PHP 6.0, such as traits and the removal of register_globals and safe_mode.

PHP 6 Features

The likely set of PHP6 features is:

  1. Internationalization: Native Unicode – UTF-8 – to the core (strings, APIs).
  2. Performance: Page level (opcode) caching through moving Alternative PHP Cache (APC) into the PHP core. Native application caching.
  3. Break to label: Sending a break to a label (like a goto).
  4. Enhanced array indexing: Array indexing can be used to substring or take an array slice.
  5. Removed features: Magic quotes will be removed.

The are quite a few more minor features and changes in PHP 6.

[smartwebdeveloper]

Jan
11

43 Tips for Optimizing PHP code

Author admin    Category IT News, PHP, Programming, Tips & Trik     Tags

43 Tips for Optimizing PHP code

Here is the list of 43 short tips you can use for writing an optimized and more efficient PHP code:

  1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  2. echo is faster than  print .
  3. Use echo’s multiple parameters instead of string concatenation.
  4. Set the maxvalue for your for-loops before and not in the loop.
  5. Unset your variables to free memory, especially large arrays.
  6. Avoid magic like __get, __set, __autoload
  7. require_once() is expensive
  8. Use full paths in includes and requires, less time spent on resolving the OS paths.
  9. If you need to find out the time when the script started executing,  INSERT:CONTENT:END SERVER['REQUEST_TIME'] is preferred to  time()
  10. See if you can use strncasecmp, strpbrk and stripos instead of regex
  11. str_replace is faster than  preg_replace , but  strtr is faster than  str_replace by a factor of 4
  12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  13. It’s better to use select statements than multi if, else if, statements.
  14. Error suppression with @ is very slow.
  15. Turn on apache’s mod_deflate
  16. Close your database connections when you’re done with them
  17. $row['id'] is 7 times faster than  $row[id]
  18. Error messages are expensive
  19. Do not use functions inside of for loop, such as  for ($x=0; $x < count($array); $x) The count() function gets called each time.
  20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  21. Incrementing a global variable is 2 times slow than a local var.
  22. Incrementing an object property (eg.  $this->prop++ ) is 3 times slower than a local variable.
  23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  26. Methods in derived classes run faster than ones defined in the base class.
  27. A function call with one parameter and an empty function body takes about the same time as doing 7-8  $localvar++ operations. A similar method call is of course about 15  $localvar++ operations.
  28. Surrounding your string by ‘ instead of “  will make things interpret a little faster since php looks for variables inside  ”…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.
  29. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
  30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
  32. Cache as much as possible. Use memcached – memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
  33. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.Example:

    if (strlen($foo) < 5) { echo "Foo is too short"; }

    vs.

    if (!isset($foo{5})) { echo "Foo is too short"; }

    Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.

  34. When incrementing or decrementing the value of the variable  $i++ happens to be a tad slower then  ++$i . This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t.  ++$i happens to be faster in PHP because instead of 4 opcodes used for  $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  36. Do not implement every data structure as a class, arrays are useful, too
  37. Don’t split methods too much, think, which code you will really re-use
  38. You can always split the code of a method later, when needed
  39. Make use of the countless predefined functions
  40. If you have very time consuming functions in your code, consider writing them as C extensions
  41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
  43. optimizing-debugging php
May
11

PaaS PHP Fog Launches To The Public

Author admin    Category IT News, PHP, Programming     Tags

Like a Heroku for PHP, PHP Fog is launching to the public today in order to help PHP developers deploy and scale their applications in the cloud. Raising $1.8 million in a round lead by Madrona and followed on by First Round, Founders Co-Op and others. PHP Fog launched in private beta in December and is now available for all members of the public.

Aside from focusing solely on PHP, what PHP Fog does differently than Heroku (and all encompassing competitor dotCloud) is that it provides users with an PHP app store, which lets people build out Drupal and WordPress sites without needing to know how to code. The service starts out as free with shared hosting and then ranges from $29 – $249 depending on how many servers you want dedicated.

Says founder Lucas Carlson, “When I started the company I thought, ‘Why isn’t anyone doing this for PHP, it’s a much bigger market?’ Out of the top one million webpages, 330K run PHP and and only 5K run Ruby. This is a much bigger opportunity, and I’ve been lucky because I’ve been able to cash in on this opportunity.”

Since its funding in December, PHP Fog has hired a team of developers (8) and signed up 13,000 people on its beta list; ”It took Heroku a year to sign up 10,000 people and it took us 6 months to sign up 13,000 people, so we’re going twice as fast.”

In addition to hiring and building out more applications, Carlson admits that a name change is in the cards (PHP Fog is the pretty much most boring startup name I’ve ever written about, and I wrote about Shwowp). He has big plans and eventually wants the service to be the “Amazon of PaaS.”

Rolling out to 1,000 people per day over the past week, PHP Fog is currently available for anyone who wants to sign up here.

[detikinet]

Feb
25

Running PHP on IIS 7

Author admin    Category IT News, PHP     Tags

This post provides an step by step approach for deploying a PHP application on an IIS 7 server. The first thing that needs to be done is to make sure that IIS is installed on your machine. You can do this from the Turn Windows Feature On Off option in the Program and Features of Control Panel(In vista).


Here you need to make sure that in the Application Development Features ISAPI extensions and ISAPI Filters are also checked or if it is not check it and press OK. This will install the ISAPI extensions. Also make sure that Internet Information Services is checked.
Now the next step is to download PHP which is available at http://www.php.net/downloads. Or if you are using wamp already the C:/wamp/php works prefectly. You just need to make sure that the php folder contains php5isapi.dll file which is necessary for us.

Now open the php.ini file inside the PHP folder and edit it in a notepad to make the following changes if necessary. Remove the semicolor(;) from to make ;extension=php_mysql.dll to extension=php_mysql.dll and ;extension=php_mysqli.dll to extension=php_mysqli.dll.

You also need to add the location of your PHP directory to the server’s PATH environment variable so that Windows knows where to look for any PHP related executables (such as the PHP extension DLL‘s). To do this Right-click on My Computer, click Properties and on the Advanced tab click Environment Variables. In the Environment Variables dialog box, under System variables highlight the Path variable and click Edit.

Then add the location of your php file and the ext folder following it in the variable value.
Now go to Internet Information Services Manager in the control panel or run C:\windows\system32\inetsrv\inetmgr.exe to get the following screen.
Open the ISAPI filters link and click add.

Now fill the fields as given below.

Click OK, go back and open Handler Mappings and then click Add Script Map. Add the information as shown below i.e. specify the *.php extension and the path of php5isapi.dll file.

After you click ok you get another prompt. Click OK again and now you might need to reboot your PC for the changes to take effect. Or I think restarting IIS will be enough(Restarting IIS:Run->Services.msc->IISadmin).

Now take a php project or a php file. Just write in a file and save it as index.php in a folder(lets say TestPHP)

Now you can put the folder (TestPHP) in C:\inetpub\wwwroot. Now in the browser type http://localhost/TestPHP/index.php . The output will be like this:

Another approach is to create a virtual directory in the IIS default website. For this go the the IIS Manager via control panel.
Click on the default document icon->Add->Add index.php as a default document
Right click on the default website and click Add Application. Specify the physical path and the alias of the project folder.

Now type http://localhost/IISPHP on the browser and you will be getting the same output as above

[abcphp]

Dec
15

Creating Word, Excel and CSV files with PHP

Author admin    Category PHP, Programming     Tags
  • MS Word document
    • Using HTTP headers
    • Using COM objects
    • Using OpenOffice templates
    • Using Zend Framework component phpLiveDocx
  • MS Excel document
    • Using HTTP headers
    • Using COM objects
  • CSV file
    • Using HTTP headers
    • Using fputcsv()

How to create MS Word document

Method 1 – Using HTTP headers

<?php
header(“Content-type: application/vnd.ms-word”);
header(“Content-Disposition: attachment;Filename=document_name.doc”);
echo “<html>”;
echo “<meta http-equiv=\”Content-Type\” content=\”text/html; charset=Windows-1252\”>”;
echo “<body>”;
echo “<b>My first document</b>”;
echo “</body>”;
echo “</html>”;
?>
Method 2 – Using COM objects
// Create new COM object – word.application
$word = new COM(“word.application”);
// Hide MS Word application window
$word->Visible = 0;
//Create new document
$word->Documents->Add();
// Define page margins
$word->Selection->PageSetup->LeftMargin = ’2′;
$word->Selection->PageSetup->RightMargin = ’2′;
// Define font settings
$word->Selection->Font->Name = ‘Arial’;
$word->Selection->Font->Size = 10;
// Add text
$word->Selection->TypeText(“TEXT!”);
// Save document
$filename = tempnam(sys_get_temp_dir(), “word”);
$word->Documents[1]->SaveAs($filename);
// Close and quit
$word->quit();
unset($word);
header(“Content-type: application/vnd.ms-word”);
header(“Content-Disposition: attachment;Filename=document_name.doc”);
// Send file to browser
readfile($filename);
unlink($filename);
Method 3 – Using OpenOffice templates
  1. Create manually an ODT template with placeholders, like [%value-to-replace%].
  2. When instantiating the template with real data in PHP, unzip the template ODT (it’s a zipped XML), and run against the XML the textual replace of the placeholders with the actual values.
  3. Zip the ODT back.
  4. Run the conversion ODT -> DOC via OpenOffice command line interface.
There are tools and libraries available to ease each of those steps.
Method 4 – Using Zend Framework component phpLiveDocx
One of the ways to create DOC files in Linux using PHP is to use the Zend Framework component phpLiveDocx. It allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge.
PhpLiveDocx is completely free to download and use. For more information, please take a look athttp://www.phplivedocx.org/articles/brief-introduction-to-phplivedocx/.
How to create MS Excel document
Method 1 – Using HTTP headers
<?php
header(“Content-type: application/vnd.ms-excel”);
header(“Content-Disposition: attachment;Filename=document_name.xls”);
echo “<html>”;
echo “<meta http-equiv=\”Content-Type\” content=\”text/html; charset=Windows-1252\”>”;
echo “<body>”;
echo “<b>testdata1</b> \t <u>testdata2</u> \t \n “;
echo “</body>”;
echo “</html>”;
?>
Method 2 – Using COM objects
//Create new COM object – excel.application
$xl = new COM(“excel.application”);
//Hide MS Excel application window
$xl->Visible = 0;
//Create new document
$xlBook = $xl->Workbooks->Add();
//Create Sheet 1
$xlBook->Worksheets(1)->Name = “Worksheet 1″;
$xlBook->Worksheets(1)->Select;
//Set Width & Height
$xl->ActiveSheet->Range(“A1:A1″)->ColumnWidth = 10.0;
$xl->ActiveSheet->Range(“B1:B1″)->ColumnWidth = 13.0;
//Add text
$xl->ActiveSheet->Cells(1,1)->Value = “TEXT”;
$xl->ActiveSheet->Cells(1,1)->Font->Bold = True;
//Save document
$filename = tempnam(sys_get_temp_dir(), “excel”);
$xlBook->SaveAs($filename);
//Close and quit
unset( $xlBook);
$xl->ActiveWorkBook->Close();
$xl->Quit();
unset( $xl );
header(“Content-type: application/vnd.ms-excel”);
header(“Content-Disposition: attachment;Filename=document_name.xls”);
// Send file to browser
readfile($filename);
unlink($filename);
How to create a CSV file
Method 1 – Using HTTP headers
<?php
$table = ‘table_name’;
$outstr = NULL;
header(“Content-Type: application/csv”);
header(“Content-Disposition: attachment;Filename=cars-models.csv”);
$conn = mysql_connect(“localhost”, “mysql_user”, “mysql_password”);
mysql_select_db(“db”,$conn);
// Query database to get column names
$result = mysql_query(“show columns from $table”,$conn);
// Write column names
while($row = mysql_fetch_array($result)){
$outstr.= $row['Field'].’,';
}
$outstr = substr($outstr, 0, -1).”\n”;
// Query database to get data
$result = mysql_query(“select * from $table”,$conn);
// Write data rows
while ($row = mysql_fetch_assoc($result)) {
$outstr.= join(‘,’, $row).”\n”;
}
echo $outstr;
mysql_close($conn);
?>
Method 2 – Using fputcsv()
The fputcsv() function formats a line as CSV and writes it to an open file. For more information, take a look at http://php.net/manual/en/function.fputcsv.php.
The code snippet below creates a CSV file of the specified table including its column names and sends it to the browser.
<?php
$table = ‘table_name’;
$filename = tempnam(sys_get_temp_dir(), “csv”);
$conn = mysql_connect(“localhost”, “mysql_user”, “mysql_password”);
mysql_select_db(“db”,$conn);
$file = fopen($filename,”w”);
// Write column names
$result = mysql_query(“show columns from $table”,$conn);
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$colArray[$i] = mysql_fetch_assoc($result);
$fieldArray[$i] = $colArray[$i]['Field'];
}
fputcsv($file,$fieldArray);
// Write data rows
$result = mysql_query(“select * from $table”,$conn);
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$dataArray[$i] = mysql_fetch_assoc($result);
}
foreach ($dataArray as $line) {
fputcsv($file,$line);
}
fclose($file);
header(“Content-Type: application/csv”);
header(“Content-Disposition: attachment;Filename=cars-models.csv”);
// send file to browser
readfile($filename);
unlink($filename);
?>
[advancedphptutorial]
Dec
15

Sending HTML Email Using PHP

Author admin    Category PHP, Programming     Tags
<?php
//define the receiver of the email
$to = ‘youraddress@example.com’;
//define the subject of the email
$subject = ‘Test HTML email’;
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date(‘r’, time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = “From: webmaster@example.com\r\nReply-To: webmaster@example.com”;
//add boundary string and mime type specification
$headers .= ”\r\nContent-Type: multipart/alternative; boundary=\”PHP-alt-”.$random_hash.”\”";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
–PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset=”iso-8859-1″
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
–PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset=”iso-8859-1″
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
–PHP-alt-<?php echo $random_hash; ?>–
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print “Mail sent”. Otherwise print “Mail failed”
echo $mail_sent ? “Mail sent” : “Mail failed”;
?>
Dec
15

Sending a Simple Text Email

Author admin    Category PHP, Programming     Tags
<?php
//define the receiver of the email
$to = ‘youraddress@example.com’;
//define the subject of the email
$subject = ‘Test email’;
//define the message to be sent. Each line should be separated with \n
$message = “Hello World!\n\nThis is my first mail.”;
//define the headers we want passed. Note that they are separated with \r\n
$headers = “From: webmaster@example.com\r\nReply-To: webmaster@example.com”;
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print “Mail sent”. Otherwise print “Mail failed”
echo $mail_sent ? “Mail sent” : “Mail failed”;
?>

Dec
15

Encrypt Passwords in the Database

Author admin    Category PHP, Programming     Tags
If you are developing a password-protected web site, you have to make a decision about how to store user password information securely.
What is “secure,” anyway? Realize that the data in your database is not safe. What if the password to the database is compromised? Then your entire user password database will be compromised as well. Even if you are quite certain of the security of your database, your users’ passwords are still accessible to all administrators who work at the Web hosting company where your database is hosted. Scrambling the passwords using some home-brewed algorithm may add some obscurity but not true “security.” Another approach would be to encrypt all passwords in your database using some industry-standard cipher, such as the Message-Digest Algorithm 5 (MD5).
MD5 encryption is a one-way hashing algorithm. Two important properties of the MD5 algorithm are that it is impossible to revert back an encrypted output to the initial, plain-text input, and that any given input always maps to the same encrypted value. This ensures that the passwords stored on the server cannot be deciphered by anyone. This way, even if an attacker gains reading permission to the user table, it will do him no good.
MD5 does have its weaknesses. MD5 encryption is not infallible: if the password is not strong enough, a brute force attack can still reveal it. So, you can ask: “Why should I use MD5 if I know it is not the most secure?” The answer is fairly straightforward: it’s fast, it’s easy, and it can be powerful if salted. The greatest advantage of MD5 is its speed and ease of use.
It is vitally important to understand that password encryption will not protect your website, it can protect your passwords only. If your website does not have sufficient protection, password encryption will not make it safe from cracking. If your system has been cracked, a hacker can inflict a irreparable damage to it and also gain an access to confidential information, including passwords database. But if you store this information encrypted, hackers practically cannot make use of it. Cracking an encrypted password takes a large amount of time and processing power, even on today’s computers.
So, let’s start. First of all, you need to add a new account to your database. The following code allows to do it.

<?php
define(“DB_SERVER”, “localhost”);
define(“DB_USER”, “your_name”);
define(“DB_PASS”, “your_pass”);
define(“DB_NAME”, “your_db”);
define(“TBL_USERS”, “users_table_name”);

$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME, $connection) or die(mysql_error());

function addNewUser($username, $password){
global $connection;
$password = md5($password);
$q = “INSERT INTO “.TBL_USERS.” VALUES (‘$username’, ‘$password’)”;
return mysql_query($q, $connection);
}
?>

Now, when a new user completes the registration form, his password will be encrypted automatically.
After that we should write code that validates a given username/password pair.
<?php
function checkUserPass($username, $password){
global $connection;

$username = str_replace(“‘”,”””,$username)
$password = md5($password);
// Verify that user is in database
$q = “SELECT password FROM “.TBL_USERS.” WHERE username = ‘$username’”;
$result = mysql_query($q, $connection);
if(!$result || (mysql_numrows($result) < 1)){
return 1; //Indicates username failure
}
// Retrieve password from result
$dbarray = mysql_fetch_array($result);
// Validate that password is correct
if($password == $dbarray['password']){
return 0; //Success! Username and password confirmed
}
else{
return 1; //Indicates password failure
}
}
?>

And what if you already have users’ database ready and want to start using encrypted passwords? To do it, you need to write encypt.php script with the following code and run it in your browser.
<?php
define(“DB_SERVER”, “localhost”);
define(“DB_USER”, “your_name”);
define(“DB_PASS”, “your_pass”);
define(“DB_NAME”, “your_db”);
define(“TBL_USERS”, “users_table_name”);
define(“FLD_USER”, “username_field_name”);
define(“FLD_PASS”, “password_field_name”);

set_magic_quotes_runtime(0);

$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME, $connection) or die(mysql_error());

$q = “SELECT “.FLD_PASS.”,”.FLD_USER.” FROM “.TBL_USERS.”";
$result = mysql_query($q, $connection);

$total=0;
$enc=0;

$doencrypt=false;
if (@$_REQUEST["do"]==”encrypt”)
$doencrypt=true;

while($data = mysql_fetch_array($result))
{
if ($doencrypt)
{
$total++;
if (!encrypted($data[0]))
{
$q=”UPDATE “.TBL_USERS.” SET “.FLD_PASS.”=’”.md5($data[0]).”‘ where “.FLD_USER.”=’”.
str_replace(“‘”,”””,$data[1]).”‘”;
mysql_query($q, $connection);
}
$enc++;
}
else
{
$total++;
if (encrypted($data[0]))
$enc++;
}
}

function encrypted($str)
{
if (strlen($str)!=32)
return false;

for($i=0;$i<32;$i++)
if ((ord($str[$i])<ord(’0′) || ord($str[$i])>ord(’9′)) && (ord($str[$i])<ord(‘a’) || ord($str[$i])>ord(‘f’)))
return false;

return true;
}
?>

<html>
<head><title>Encrypt passwords</title></head>
<body>
Total passwords in the table – <?php echo $total; ?><br>
<?php if($enc==$total && $total>0) { ?>
All passwords are encrypted.
<?php } else if($total>0) { ?>
Unencrypted – <?php echo $total-$enc; ?><br><br>
Click “GO” to encrypt <?php echo $total-$enc; ?> passwords.<br>
WARNING! There will be no way to decipher the passwords.<br>
<input type=button value=”GO” onclick=”window.location=’encrypt.php?do=encrypt’;”>
<?php } ?>
</body>
</html>

[advancedphptutorial]
Dec
15

Connect to MS SQL Server database

Author admin    Category PHP, Programming     Tags
<?php
$myServer = “localhost”;
$myUser = “your_name”;
$myPass = “your_password”;
$myDB = “examples”; //connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die(“Couldn’t connect to SQL Server on $myServer”);
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die(“Couldn’t open database $myDB”); //declare the SQL statement that will query the database
$query = “SELECT id, name, year “;
$query .= “FROM cars “;
$query .= “WHERE name=’BMW’”; //execute the SQL query and return records
$result = mssql_query($query);

$numRows = mssql_num_rows($result);
echo “<h1>” . $numRows . ” Row” . ($numRows == 1 ? “” : “s”) . ” Returned </h1>”; //display the results
while($row = mssql_fetch_array($result))
{
echo “<li>” . $row["id"] . $row["name"] . $row["year"] . “</li>”;
}//close the connectionmssql_close($dbhandle);
?>

Connect with a DSN
DSN stands for ‘Data Source Name’. It is an easy way to assign useful and easily rememberable names to data sources which may not be limited to databases alone. If you do not know how to set up a system DSN read our tutorial How to set up a system DSN.
In the example below we will show you how to connect with a DSN to a MSSQL Server database called ‘examples.mdb’  and retrieve all the records from the table ‘cars’.
<?php
//connect to a DSN “myDSN”
$conn = odbc_connect(‘myDSN’,”,”);

if ($conn)
{    //the SQL statement that will query the database
$query = “select * from cars”;   //perform the query
$result=odbc_exec($conn, $query);

echo “<table border=\”1\”><tr>”;   //print field name
$colName = odbc_num_fields($result);
for ($j=1; $j<= $colName; $j++)
{
echo “<th>”;
echo odbc_field_name ($result, $j );
echo “</th>”;
}   //fetch tha data from the database
while(odbc_fetch_row($result))
{
echo “<tr>”;
for($i=1;$i<=odbc_num_fields($result);$i++)
{
echo “<td>”;
echo odbc_result($result,$i);
echo “</td>”;
}
echo “</tr>”;
}

echo “</td> </tr>”;
echo “</table >”;   //close the connection
odbc_close ($conn);
}
else echo “odbc not connected”;
?>

Connect without a DSN (using a connection string)
Let see a sample script to see how ADODB is used in PHP:
<?php
$myServer = “localhost”;
$myUser = “your_name”;
$myPass = “your_password”;
$myDB = “examples”; //create an instance of the  ADO connection object$conn = new COM (“ADODB.Connection”)
or die(“Cannot start ADO”); //define connection string, specify database driver$connStr = “PROVIDER=SQLOLEDB;SERVER=”.$myServer.”;UID=”.$myUser.”;PWD=”.$myPass.”;DATABASE=”.$myDB;
$conn->open($connStr); //Open the connection to the database
//declare the SQL statement that will query the database
$query = “SELECT * FROM cars”; //execute the SQL statement and return records
$rs = $conn->execute($query);

$num_columns = $rs->Fields->Count();
echo $num_columns . “<br>”;

for ($i=0; $i < $num_columns; $i++) {
$fld[$i] = $rs->Fields($i);
}

echo “<table>”;
while (!$rs->EOF)  //carry on looping through while there are records
{
echo “<tr>”;
for ($i=0; $i < $num_columns; $i++) {
echo “<td>” . $fld[$i]->value . “</td>”;
}
echo “</tr>”;
$rs->MoveNext(); //move on to the next record
}

echo “</table>”; //close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();

$rs = null;
$conn = null;
?>

To create ‘examples’ database on your MSSQL Server you should run the following script:
CREATE DATABASE examples;
USE examples;
CREATE TABLE cars(
id int UNIQUE NOT NULL,
name varchar(40),
year varchar(50),
PRIMARY KEY(id)
);

INSERT INTO cars VALUES(1,’Mercedes’,’2000′);
INSERT INTO cars VALUES(2,’BMW’,’2004′);
INSERT INTO cars VALUES(3,’Audi’,’2001′);

[advancedphptutorial]
Dec
15

Using Cookies in PHP

Author admin    Category PHP, Programming     Tags
A cookie is a message given to a Web browser by a Web server. The browser stores the message in a small text file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, the cookie is sent back to the server too.

There are a wide variety of things you can do with cookies. They are used to store information about user, visited pages, poll results and etc. The main purpose of cookies is to identify users and possibly prepare customized Web pages for them.
  • How to Create a Cookie?
  • How to Retrieve a Cookie Data?
  • How to Delete a Cookie?
Normally cookies are used only to store small amounts of data. Websites can read the values from the cookies and use the information as desired. In addition to the information it stores, each cookie has a set of attributes that helps ensure the browser sends the correct cookie when a request to a server is made.
Even though cookies are not harmful some people do not permit cookies due to concerns about their privacy. In this case you have to use Sessions.
How to Create a Cookie?
PHP cookies can be set using the setcookie() function. The syntax is as follows:
setcookie(name[, value[, expire[, path[, domain[, security]]]]])
  • [name] The cookie name. The name of each cookie sent is stored in the superglobal array $_COOKIE.
  • [value] The  cookie value. It is associated with the cookie name.
  • [expire] The time after which the cookie should expire in seconds
  • [path] Specifies the exact path on the domain that can use the cookies.
  • [domain] The domain that the cookie is available. If not domain is specified, the default value is the value of the domain in which cookie was created.
  • [security] Specifies whether the cookie will be sent via HTTPS. A value of 1 specifies that the cookie is sent over a secure connection but it doesn’t mean that the cookie is secure. It’s just a text file like every other cookie. A value of 0 denotes a standard HTTP transmission.
In the example below, we will create a cookie named “myCookie” and assign the value “PHP Tutorial” to it. We also specify that the cookie should expire after one hour and that the cookie is available for all pages within a Tutorials directory.
<?php
setcookie(“myCookie”, “PHP Tutorial”, time()+3600, “/tutorials”);
?>
There’s one important item to mention about using cookies. Because of the way cookies work within HTTP, it’s important that you send all cookies before any output from your script. This requires that you place calls to this function before any output, including tags as well as any whitespace. If you don’t, PHP will give you a warning and your cookies will not be sent.
How to Retrieve a Cookie Date?
Now the cookie is set and we need to retrieve the information. As mentioned above the name of each cookie sent by your server accessed with the superglobal array $_COOKIE. In the example below we retrieve the value of the cookie and print out its value on the screen.
<?php
echo “The cookie value is “.$_COOKIE['myCookie'];
?>
This would show up on the page as: “myCookie value is PHP Tutorial”.
How to Delete a Cookie?
By default, the cookies are set to be deleted when the browser is closed. We can override that default by setting a time for the cookie’s expiration but there may be occasions when you need to delete a cookie before the user closes his browser, and before its expiration time arrives. To do so, you should assure that the expiration date is in the past. The example below demonstrates how to do it (setting expiration time 1 minute ago):
<?php
setcookie(“myCookie”, “”, time()-60);
?>
Follow us on Twitter! Follow us on Twitter!
[Powered by Android]

Blogroll

Google Search :)

Calendar

April 2014
M T W T F S S
« Mar    
 123456
78910111213
14151617181920
21222324252627
282930  

Archives

Recent Posts