Url Encoding - Use rawurlencode not urlencode !

The URL encoding is one the mysterious functions that PHP programmers does use but without knowing all the details behind it. When one wants to create a link dynamically he just use urlencode, and thi is so necessary because in an URl, there is some reserved characters that have sens for the browsers and the the server-side scripts. You should already know the meaning of ? , & and = characters in the query string, if you don't know see this important Wikipedia article http://en.wikipedia.org/wiki/Query_string

But, you may see somewhere that there is a function called rawurlencode, what is that ? Is it a different encoding convention ? The answer is yes and not.
Well, urlencode and rawurlencode are very similar, they do the same encoding except for one character, the Space character !
rawurlencode encodes the space character as %20, while urlencode encodes it as +, here are few use-difference between both, as much as I understand:

1-Path vs Query vars
In the url path, you should encode spaces as %20 and not +, for example if your folder is called "folder one"
this url will work http://www.exemple.com/folder%20one/index.php , and this will not : http://www.exemple.com/folder+one/index.php because in this last the server will search for a folder called folder+one instead of folder one .
But in the GET variables you should prefer the + character to simulate the space, this is what Google is doing ! But whether you use + or %20 in those url variables, ie you use urlencode or rawurlencode, they should both work.

2-PHP vs JavaScript:
Javascript uses the same convention as rawurlencode, so if you want to encode an url with php but you will decode it in javascript, you should use rawurlencode, and here is the reason:

Lets say you encoded "test 1" within php, if you need to "decode" it in JavaScript using decodeURI() function then decodeURI("test+1") will give you "test+1" while decodeURI("test%201") will give you "test 1" as result.

Summary:
The rawurlencode function is the last one, and it should work perfectly in modern systems with less problem. So this is the encoding function to use most of the time ! While urlencode is kept for legacy compatibility, as well as compatibility with Javascript.

Memory problem in PHP simple HTML DOM

I was using PHP Simple HTML dom, a great and free library for parsing html pages and retreiving info from it. I really liked it.. But when it comes to parsing many differents pages of some website in one php script, you will get an error:

Allowed memory size of 67108864 bytes exhausted,

and this is because simple HTML dom don't free up the memory in real time, so the solution is:

Each time you create a dom object ( foe exemple using: $html = file_get_html("http://someurl/"); or  str_get_html... ), then when you don't need it anymore you have to call _destruct:
$html->_destruct();
unset($html);

“Who Is Online” Widget With PHP, MySQL & jQuery

Do you see in some website a nice list of online users ? Do you want to have one in your website ? That should be easy now thanks to this very helpful and easy-to-install widget:

    “Who Is Online” Widget With PHP, MySQL & jQuery

I hope you will like it :)

String Capitalization Functions: strtoupper-strtolower-ucwords.

In php you can easily manipulate the capitalization of your PHP strings, there are ready to use functions that help you to convert yout text to upper case, lower case, or just the first letter of every word to upper case.

<?php

$originalString = "Testing string Capitalization AbCDe";

$upperCase = strtoupper($originalString); // Result: TESTING STRING CAPITALIZATION ABCDE
$lowerCase = strtolower($originalString); // Result: testing string capitalization abcde
$ucTitleString = ucwords($originalString); // Result: Testing String Capitalization Abcde

?>


This does explain everything about how to manipulate capitalization. In fact strtoupper returns the string in upper case, strtolower converts to lower case, and ucwords capitalize the first letter of each word, without making any changes to other characters in the word. (ie tEsT becomes TEsT with ucwords).

If you have any question, I'm ready to help you.

PHP For Loop

When you need to do the same script many times, for exemple you want to send emails to all your users, you don't need to write a php code for each user, you just need to use for Loop which will do it for each one.
This is how:
<?php
for ($userid=1;$userid<=10;$userid++){
send_email($userid);
}
?>

Where send_email() is your own function that send the email to the user with the id as parameter.

Another exemple to For Loop, let's say you want to count 1+2x2+3x3+...+nxn, this is how you can do it:
<?php
$n=10;
$t=0;
for ($i=1;$i<=$n;$i++){
$t+=$i*$i; // the same as $t=$t+$i*$i
}
?>


So how For loop works ?

1. Set a counter variable to some initial value (i.e $i=0).
2. Check to see if the conditional statement is true(i.e $i<=10).
3. Execute the code within the loop.
4. Increment a counter at the end of each iteration through the loop(i.e $i++, or $i+=1, ou $i=$i+1) .

And this is how to do it:
for ( initialize a counter; conditional statement; increment a counter){
do this code;
}


The php loop will help you a lot in php programming, and there are other ways to do loops other that For, like while.

PHP Validate Email Address: Email Validator

When working with forms and interacting with your visitors, you may want to verify if your visitor entered an email address in the right field, and if it is valide or not.

Most of people who are new to php world, just verify if the text box of the email address is filled or not, without verifying the syntax of the email address...

Something like this they use:
if (isset($_POST['email'])) {
// do something
}


But when you want to develop a php website in the best way, taking care of all little details, you should think what happens when your user does make a mistake in the email address, writing something like this: his_email@gmailcom, or his_emailgmail.com or even he writes ssdfsff (like many people do), I'm sure you would like to inform him and ask him to correct his email address, you maybe also want to check if the domain name of his email address is valid, you can't accept an email like this: blahblah@dfsjhbhjjqsdqq.fdf .

So here is the php script I think you should use everytime you have a form with 'email address' input :
<?php
function validate_email($email) {

   //check for all the non-printable codes in the standard ASCII set,
   //including null bytes and newlines, and exit immediately if any are found.
   if (preg_match("/[\\000-\\037]/",$email)) {
      return false;
   }
   $pattern = "/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD";
   if(!preg_match($pattern, $email)){
      return false;
   }
   // Validate the domain exists with a DNS check
   // if the checks cannot be made (soft fail over to true)
   list($user,$domain) = explode('@',$email);
   if( function_exists('checkdnsrr') ) {
      if( !checkdnsrr($domain,"MX") ) { // Linux: PHP 4.3.0 and higher & Windows: PHP 5.3.0 and higher
         return false;
      }
   }
   else if( function_exists("getmxrr") ) {
      if ( !getmxrr($domain, $mxhosts) ) {
         return false;
      }
   }
   return true;
} // end function validate_email
?>
 


Now you can use this function with the email address you want to verify as parameter, and it will return you true if it valide and false if it is not.
This nice function will not know if an email exist really or not, it just verifies the syntax and the domain name, for example will not know that qsddsfqsdsdfqsdsqdsqd@gmail.com is not valide, but knows that qsqsdsq@dfsfsqdqsdqd.com is an invalid email address .

I hope this help you a lot.
Please leave comments or link to us if you think this is usefull :)

PHP Random code Generator

This is a very simple-to-use php function that help you generate random codes in very easy way, you will need this function to generate random passwords, confirmation links,...

So, this is it:
<?php
function createRandomPassword() {
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;
    while ($i <= 9) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}
?>


That's it!
There are many options you can play with, for example you can choose the characters to generate code from: $chars ="1234567890" will generate numeric code; $chars = "abcdefghijkmnopqrstuvwxyz023456789"; will generate alphanumeric codes. In fact the code will be generated randomly from the list of characters in $chars.

You can also change the lenght of the generated code by changing the value in "while ($i <= 9)", 9 here means you will get a code with 10 characters, as this counter (while) starts from 0 to 9. If you do "while ($i <= 7)" you will get 8 characters code.

This is the easiest and the best way to generate random code from php. I will always provide the best PHP scrips :)

If you like my blog, please give a link to us from your website, I will appreciate that :)

PHP Get browser Language

In php you can get the language of your visitor, this is very helpful if you have many versions of your website for different languages.

You can get the language of your visitor in this way:
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
?>


This will give you the 2letter language code, ie: en for english and fr for french .

In fact $_SERVER['HTTP_ACCEPT_LANGUAGE'] will get all language the user prefer to use, in order. So substr() will give you the first choice, you can also get the second choice, the third ...

Having the language of your visitor will let you display custom page depending on his language, for example if someone's language is french, you will have $lang="fr" , then you can redirect him to www.yoursite.com/fr/ or yoursite.com/?lang=fr to show him your website in french, or show him things related to french language, whatever your website is about.

PHP $_REQUEST

You probably already know that you can get variable from a html form in php using $_GET and $_POST, you use $_GET if the html form is like: <form name="name" action="form.php" method="get"> and use $_POST if it is <form name="name" action="form.php" method="post">.

But what if you want your php to work for both post and get datas in the same time, to precess the form whatever it was in post method or get method, you will then think to use if conditions to check whether of two methods was used:

if (isset($_POST['var']))
// process data...
if (isset($_GET['var']))
// process data in the same way...

BUT there is a little and usefull solution: $_REQUEST, because $REQUEST can get any form field value, whatever it was GET or POST method, it does not care.

This means that $_REQUEST['var'] = $_POST['var'] if the form was in post method, and $_REQUEST['var'] = $_GET['var'] if the form was get. ('var' is the field name you want to get its value)
So now you will not care what method the form use :)

You can also use isset() with $_REQUEST, for example:
if (isset($_REQUEST['var'])) is the same than if ( isset($_POST['var']) or isset($_GET['var']) )

I hope this little tip will help you, we will provide best php tips, scripts as well as php tutorials.

PHP send mail SMTP authentification

this is a very complete php send mail script, with authentification ofcourse.
You can choose the smtp server, use your username and password, and can send a html email.

This script does not use php mail() function, it's all from scrach.





function authSendEmail($from, $namefrom, $to, $nameto, $subject, $message)
{

$smtpServer = "smtpout.europe.secureserver.net";
$port = "25";
$timeout = "30";
$username = "username@mailserver.com";
$password = "mypassword";
$localhost = "localhost"; //hosting server
$newLine = "\r\n";

$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 515);
if(empty($smtpConnect))
{
$output = "Failed to connect: $smtpResponse";
return false;
} else {
$logArray['connection'] = "Connected: $smtpResponse";
}

//Request Auth Login

fputs($smtpConnect,"AUTH LOGIN" . $newLine);

$smtpResponse = fgets($smtpConnect, 515);


//Send username

fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Send password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Say Hello to SMTP
fputs($smtpConnect, "HELO $localhost" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Email From
fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Email To
fputs($smtpConnect, "RCPT TO: $to" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//The Email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Construct Headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
//Add these two lines if you have any problem
//$headers .= "To: $nameto <$to>" . $newLine;

//$headers .= "From: $namefrom <$from>" . $newLine;


fputs($smtpConnect, "To: $nameto <$to>\nFrom: $namefrom <$from>\nSubject: $subject\n$headers\n\n$message\n.\n");
$smtpResponse = fgets($smtpConnect, 515);

// Say Bye to SMTP
fputs($smtpConnect, "QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

return true;
}

?>

That's it, just copy this mail SMTP authentification function and change configuration variables values to your own (smtpserver, port, username, password, ...).

ob_start - save php output to a string - The PHP output buffering

I want to share this great php utility: the output buffering, it is sometimes very usefull. So what it does ?
The PHP output buffering will save all the server outputs ( html and php prints) to a string variable.

So to start buffering, use ob_start(); this will keep saved any output.
Then you use $variable = ob_get_clean(); to stop buffering, and copy the buffer content to the variable.

Here are few samples of the use of ob_start() and ob_get_clean()


<?php ob_start(); //Turn on output buffering ?>
Hello world, <a href="http://www.blogger.com/myotherpage.php">link</a>
<div class="style">Content</div>
<?php $var = ob_get_clean(); //copy current buffer contents into $message variable and delete current output buffer ?>


Now the content of the variable $var should be:

Hello word, <a href="http://www.blogger.com/myotherpage.php">link</a>
<div class="style">Content</div>


Another example (with php outputs buffered)

<?php ob_start(); ?>
Hello world, <?php echo "My Website"; ?>
Thank you.
<?php $var = ob_get_clean(); ?>


And this will be the content of $var:
Hello world, My Website
Thank you.

That's all !

PHP send HTML email, The complete php mail sending script

The last post by me was about a very easy way to send an email with php. But as it is simple, it will only send text email, not html.

If you want a complete mail sending script, that send in html, this is what you have to use:

<?php
//here the receiver of the email
$to = 'receiver@example.com';
//here 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: myemail@mysite.com\r\nReply-To: myemail@mysite.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.
$message ='
--PHP-alt-'.$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-'.$random_hash.'--';

//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";
?>

The script is with comments, to tell you what exactly each instruction does :)

So as you see, we added:
Content-Type: text/html; charset="iso-8859-1"
to the message body ($message), this way the mail client of the receiver will know that the email is in html.

There are also few other changements that are nor really very necessary like the boundary string, but it is better to use them :)

PHP mail() - send email with php

Sending email with php is very simple, few lines of code and it works.
You need to send email using php when you have a comment or contact us form, where your visitors contact you via a web page form, and you get the message to your email address, or when you have a signup / registration form and you want to send automatically a confirmation link or a welcome message to your new users.

This is how you send email using php:
<?php
$TO = "someone@something.com";
$h  = "From: me@mywebsite.com";
$message = "my message here";
mail($TO, $subject, $message, $h);
Header("Location: http://mysite.com/thankyou.html");
?>

That's it ! mail() function have 3 required parameters and one optional.
$To is the receiver email address, $subject is the subject and $message is the body of your message.
$h is optional, is the header you will send, it contains the sender email address ("FROM: me@mysite.com")

I will post next how to send a html email, and how to use SMTP Authentication which means how to choose the smtp server and use your username and password to use that server.

PHP Post data to url with curl

I know you will need sometimes to use a php code to send data (text) to an url using POST method, just like it was sent by a form.
So all you have to do now, is to copy this function and use it, you have to specify the url and the data to post and it goes !

<?php
function post_content($url,$nfields,$fields_string)  
{
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch,CURLOPT_POST,$nfields);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)');  
    ob_start();  
    curl_exec ($ch);  
    curl_close ($ch);  
    $string = ob_get_contents();  
    ob_end_clean();  
    return $string;      
}
?>

How this will work ? It's very easy:
1- First you need to know what url you want to post to using curl
2- You need to know what are the names of variables to post (textarea, checkbox..)
3- Their number
4-And their values

This is a quite easy exemple:
if the original form has these fields: textarea1, textarea2, and sends to "www.site.com/page.php", like this example:
<form name="form1" method="post" action="www.site.com/page.php">
  <textarea name="textarea1"></textarea>
  <textarea name="textarea2"></textarea>
</form>

You should use this function in this way:
post_content("http://www.site.com/page.html",2,"textarea1=value1&textarea2=value2")

$nfields=2 because you have two fields (textarea1 and textarea2) ,
$fields_sring = "textarea1=value1&textarea2=value2" because you want to post two variables ( fields values) value1 for the field textarea1 and value2 for the field textarea2, you have to write always "&" between each couple of fieldname-value.

What does this all mean, and for what ?
With this function you will be able to "assimilate" the use of the form and the submit button, and this mean you will be able to get the content of the page www.site.com/pahe.php without using the form, because php can't use a form :)

That's all !

HTML code directly in IF Conditions

This is the most amazing thing in php conditions, and exactly the if statement.
In a php condition, you can put directly a html code without the echo function :)

This is what I'm talking about, with echo function, then without.:



if ($condition == 'something') {
echo '
My Website...
'; } else { echo '
My Website...
'; } ?>
With the new way I'm talking about, the script will be like this:




 if ($condition = 'something') {?>
<div class="style1">My Website...<div>
 } else { ?>
<div class="style2">My Website2...<div>
 }?>




Now  why this can be useful ?
In fact, when you are using a html editor like dreamweaver, you will be able to design easily the html code in the if statement, you can add tables, images, div, change colors ... directly using the design view, or when you use the code view you can see the html code highlighted (like in the exemple above) wich believe me will help you a lot and make your programming so much easier !


Thank you.

PHP forms

Using PHP With HTML Forms

We use forms to interact with the website visitor, we can get and save his name, email address, comments, and even his purchased item, color of the item, his street address.
The form is made in two steps: creating a html form to be visible in the browser of the visitor, and creating a php script that will process the form, such as sending email, saving name and email in database, ...

The complete Tutorial is here: PHP Forms

Tutorials-Planet.com

I'm moving to Tutorials-planet.com, you can find there all php articles, tutorials and script you need to be a successfull php programmer.
All php sources should be here
PHP tutorials include strings, variables, functions, arrays and form tutorials, other tutorials are coming !

Free web hosting services

Every one who want to start online business, need a very cheap or free web hosting to start with.

Many companies online provide a good free web hosting services, and they may differ by their:
  • Disk Space
  • Data Transfer / bandwidth
  • databases
  • email services
  • usable languages: php/asp/perl ...
All are free, but only the file hosting is free, and surely not the domain name. In every web hosting plan, you need to buy your own domain name ( whatever from your hosting company or another company ), or, for your quick start and testing, you can use their free subdomain like: yourname.theirdomain.com or myphpsource.blogspot.com where blogger (blogspot) is the hosting company who offer free subdomain.

I collected for you the best free web hosting services, with their reliable/dedicate server. Where you can apply for a free subdomain along with the hosting, or attach your own domain name to their servers.


-> orgfree.com
they offer good webhosting, with ftp, web-based file manager, php, mysql database, but they add their own ads to all your pages, which not seems to be good for many people. see orgfree.com.

-> zymic.com
This is an excellent free web hosting service with 6000 MB hosting space, php, 5 MySQL databases, ftp & file manager ...
They are also ad-free hosting so they do not add their ads to your pages, and they also provide you with quality free templates for your new website. See their details here.

-> Gofreeserve.com
Gofreeserve.com is my best at all ! 99.9% server uptime, it's a reliable webhosting service: 1000 MB hosting space, 15 Add-on domains, 15 Sub domains, Website Builder, Webmail (RoundCube), 15 MySQL databases, php MyAdmin, no ads and much more in their free hosting plan that you can see here.

-> 50gigs.net
50gigs.net is also a good webhosting, 5000 MB hosting space, 50 Add-on domains, 50 Sub domains, Website Builder, free RoundCube Webmail, MySQL databases, no ads. You can see more here.

I will post more and more good and free webhosting services, or cheap hosting, or reliable.

Connect to Mysql Database

Connecting to the mysql database is done in two steps:
  1. Connecting to a mysql server, it's the most of time installed in the same server where php is, so we uselocalhost as address of mysql server.

    mysql_connect("localhost", "username", "password") or die(mysql_error());
    echo "Connected to MySQL Server";

    Some times, when you are running a server in your own computer and not a hosting service provider's, you can connect with just indicating username "root" with no password, and some times is no need to enter an username. It's all depend on your current mysql configuration.

  2. After you are connected to a mysql server, you need then to connect to a mysql database:

    mysql_select_db("database-name") or die(mysql_error());
    echo "Connected to Mysql Database";

So now you are completely connected to your database, and you can read/send data from/to it. But if a problem occurs, the "or die(mysql_error());" help you to find the error and hundle it.