Carbonized Blog » PHP http://carbonize.co.uk/wp Just a bunch of stuff Sat, 09 Aug 2014 07:58:45 +0000 en-US hourly 1 http://wordpress.org/?v=308 Random Character Generation in PHP and JavaScript http://carbonize.co.uk/wp/2012/02/08/random-character-generation-in-php/ http://carbonize.co.uk/wp/2012/02/08/random-character-generation-in-php/#comments Wed, 08 Feb 2012 16:29:07 +0000 http://carbonize.co.uk/wp/?p=486 I wrote this function in response to someone else’s attempt on a forum I was asked to join. It basically generates a string of random letters and numbers with the letters being in both upper and lower case. It is easy to edit it to only use upper or lower case letters or even add symbols as well. I initially wrote it in PHP and then rewrote it in JavaScript as well.

function randomString($strLen = 32)
{
  // Create our character arrays
  $chrs = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
 
  // Just to make the output even more random
  shuffle($chrs);
 
  // Create a holder for our string
  $randStr = '';
 
  // Now loop through the desired number of characters for our string
  for($i=0; $i<$strLen; $i++)
  {
    $randStr .= $chrs[mt_rand(0, (count($chrs) - 1))];
  }
  return $randStr;
}

Using it is simply a case of calling it and specifying how long to make the string otherwise it uses the default length of 32 characters.

echo randomString(12);

To also make it use symbols you just change the array_merge to


// If we want letters, numbers and symbols
$chrs = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9), array('!','£','$','%','^','&','*','(',')','-','=','+','@','#','~','?'));

Now for the JavaScript version. JavaScript has neither a range() function nor an easy way to shuffle an array so the code here is a little longer.

function randomString(len) {
  // Just an array of the characters we want in our random string
  var chrs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
              'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
              '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
 
  // Check that a length has been supplied and if not default to 32
  len = (isNaN(len)) ? 32 : len;
 
  // The following section shuffles the array just to further randomise the output
  var tmp, current, top = chrs.length; 
  if(top)
  {
    while(--top) 
    { 
      current = Math.floor(Math.random() * (top + 1)); 
      tmp = chrs[current]; 
      chrs[current] = chrs[top]; 
      chrs[top] = tmp; 
    }
  }
 
  // Just a holder for our random string
  var randomStr = '';
 
  // Loop through the required number of characters grabbing one at random from the array each time
  for(i=0;i<len;i++) 
  {
    randomStr = randomStr + chrs[Math.floor(Math.random()*chrs.length)];
  }
 
  // Return our random string
  return randomStr;
}
]]>
http://carbonize.co.uk/wp/2012/02/08/random-character-generation-in-php/feed/ 0
Sending email via SMTP using PHP http://carbonize.co.uk/wp/2011/10/24/sending-email-via-smtp-using-php/ http://carbonize.co.uk/wp/2011/10/24/sending-email-via-smtp-using-php/#comments Mon, 24 Oct 2011 11:08:51 +0000 http://carbonize.co.uk/wp/?p=472 A couple of my users contacted me to say that their host had disabled sendmail and required any scripts they use to now use SMTP to send emails. This resulted in me quickly reading all I could about SMTP and the result is this slightly rough script I am sharing. It’s pretty self explanatory. Put your SMTP server details in the $mailCfg array. Next simply call the smtpMail function which uses the same variables as the standard PHP mail() function but with two additional variables. The additional variables are the email address we are sending from and $mailCfg. I could of put $mailCfg as a global but this way you can include the script in a different script and store the required information where ever you want. The from address is important as most SMTP servers will reject the message if it’s not included.

Just remember the code is far from perfect and was created to do a simple job.

It also has one nice extra function you might find useful…

The directMail function will look up the recipients SMTP server and try to deliver the email directly to it thereby bypassing the need for you to have access to an SMTP server to send through. Just remember your host may frown upon the use of this function.

/*
 * SMTP Email Sending
 * By Stewart Souter
 * Date Created: Thurs, 11 August 2011 17:15:37 GMT
 * Last Updated: Fri, 19 August 2011 10:54:35 GMT 
 * email: [email protected]
 * 
 * By using this script you are agreeing to leave this
 * comment and agreement in place and untouched. If you
 * use any part of this code you must make it clear where
 * it came from and give credit where it is due.
 */
 
$mailCfg['Server']    = '';    // Servername
$mailCfg['User']      = '';    // SMTP username if needed
$mailCfg['Pass']      = '';    // SMTP Password if needed
$mailCfg['Port']      = 25;    // SMTP server port. 25 is the usual and 465 if using SSL
$mailCfg['popServer'] = '';    // Name of the pop server. Leave empty if POP Auth not required
$mailCfg['popPort']   = 110;   // Port for the pop server. 110 is the usual and 995 if using SSL
$mailCfg['SSL']       = 0;     // Does your SMTP server need you to use SSL or TLS? 0 = no, 1 = SSL, 2 = TLS
 
// This function delivers the email directly to the recipients mail server so bypassing the need for your own
function directMail($mailTo, $mailSubject, $mailMsg, $mailHeaders = '', $mailFrom = '', $mailCfg)
{
  if(empty($mailFrom))
  {
    return false; // No from address == no sending
  }
  $mailParts = explode('@', $mailTo);  // Seperate the parts of the email address
  @getmxrr($mailParts[1], $mxHosts, $mxWeight); // Get the MX records for the emails domain
  for($i=0;$i<count($mxHosts);$i++) // Put the records and weights into an array
  {
      $mxServers[$mxHosts[$i]] = $mxWeight[$i];
  }
  asort($mxServers); // Sort the array so they are in weighted order
  foreach($mxServers as $key => $value)
  {
    $mailCfg['Server'] = $key; // Set the SMTP server to the current MX record
    if(smtpMail($mailTo, $mailSubject, $mailMsg, $mailHeaders, $mailFrom, $mailCfg)) // Send the email using the MX server
    {
      return true;  // The email was successfully sent
    }
  }
  return false;  // Houston we have a problem
}
 
// This function connects to the SMTP server and does the AUTH if needed. Can also do a POP login if server requires that.
function smtpMail($mailTo, $mailSubject, $mailMsg, $mailHeaders = '', $mailFrom = '', $mailCfg )
{
  if(empty($mailFrom))
  {
    return false; // No from address == no sending
  }
  $timeout = '30'; // How long to keep trying to connect
  $localhost = 'localhost'; // How to identify ourselves
  $logArray = array(); // For storing the replies
 
  /* * * * POP Login if required * * */ 
 
  if(!empty($mailCfg['popServer'])) // Can't really do POP Auth without a server
  {
    $ssl = ($mailCfg['SSL'] != 0) ? (($mailCfg['SSL'] == 1) ? 'ssl://' : 'tls://') : ''; // If SSL or TLS add it
    $popConnect = @fsockopen($ssl.$mailCfg['popServer'], $mailCfg['popPort'], $errno, $errstr, $timeout); // Connect
    if(!$popConnect) // If we fail to connect...
    {
      $logArray['POPconnect'] = $errstr . '(' . $errno . ')'; // Log the given reason...
      logMailError($logArray); // And output to the log file.
      return false;
    }
    else
    {
      $logArray['POPconnect'] = @fgets($popConnect, 515)); // POP servers only return single line replies. Or should.
      if(!mailPackets('AUTH LOGIN', $popConnect, 'SMTPauth')) //Request Auth Login
      {
        return false;
      }
      if(!mailPackets('USER ' . $smtpUser, $popConnect, 'POPuser')) // Send username. POP is plaintext
      {
        return false;
      }    
      if(!mailPackets('PASS ' . $smtpPass, $popConnect, 'POPpass')) // Send password, again in plaintext
      {
        return false;
      }
      if(!mailPackets('QUIT', $popConnect, 'POPquit')) // Say bye to the server
      {
        return false;
      }    
      fclose($popConnect); // Close connection
    }
  }
 
  /* * * * End of POP Login * * * * */
 
  /* * * * Start of SMTP stuff * * * */
 
  $ssl = ($mailCfg['SSL'] != 0) ? (($mailCfg['SSL'] == 1) ? 'ssl://' : 'tls://') : ''; // Set the encryption if needed
  $smtpConnect = @fsockopen($ssl.$mailCfg['Server'], $mailCfg['Port'], $errno, $errstr, $timeout); // Connect
  if(!$smtpConnect) // If we fail to connect...
  {
    $logArray['SMTPconnect'] = $errstr . '(' . $errno . ')'; // Add the reason to the log...
    logMailError($logArray); // Then output the log
    return false;
  }
  else
  {
    $cnectKey = 0; // A counter for when we receive multiple lines in reply
    do
    {
      $smtpResponse = @fgets($smtpConnect, 515); // Get the reply
      $cnectKey++; // Increment the counter
      $logArray['SMTPconnect' . $cnectKey] = $smtpResponse; // Log the response
      $responseCode = substr($smtpResponse, 0, 3); // Grab the response code from start of the response
      // If we get an error terminate the connection and log the results so far
      if($responseCode >= 400)
      {  
        logMailError($logArray, $smtpConnect);
        return false;
      }        
    }  
    while((strlen($smtpResponse) > 3) && (strpos($smtpResponse, ' ') != 3)); // Loop until we get told it's the last line
      $ehlo = mailPackets('EHLO ' . $localhost, $smtpConnect, $logArray, 'SMTPehlo'); // Let's try using EHLO first
      if($ehlo != 250) // Server said it didn't like EHLO so drop back to HELO
      {
        if(!mailPackets('HELO ' . $localhost, $smtpConnect, $logArray, 'SMTPhelo')) // Send HELO. No EHLO means server doesn't support AUTH
        {
          return false;
        }
      }
      if(!empty($mailCfg['User']) && ($ehlo == 250)) // We have a username and server supports EHLO so send login credentials
      {
        if(!mailPackets('AUTH LOGIN', $smtpConnect, $logArray, 'SMTPauth')) // Request Auth Login
        {
          return false;
        }
        if(!mailPackets(base64_encode($mailCfg['User']), $smtpConnect, $logArray, 'SMTPuser')) // Send username
        {
          return false;
        }
        if(!mailPackets(base64_encode($mailCfg['Pass']), $smtpConnect, $logArray, 'SMTPpass')) // Send password
        {
          return false;
        }
      }
      if(!mailPackets('MAIL FROM:<' . $mailFrom . '>', $smtpConnect, $logArray, 'SMTPfrom')) // Email From
      {
        return false;
      }
      if(!mailPackets('RCPT TO:<' . $mailTo . '>', $smtpConnect, $logArray, 'SMTPrcpt')) // Email To
      {
        return false;
      }
      if(!mailPackets('DATA', $smtpConnect, $logArray, 'SMTPmsg')) // We are about to send the message
      {
        return false;
      }
      // First lets make sure both the message and additional headers do not contain anythign that might be seen as end of message marker
      $mailMsg = preg_replace(array("/(?<!\r)\n/", "/\r(?!\n)/", "/\r\n\./"), array("\r\n", "\r\n", "\r\n.."), $mailMsg);
      $mailHeaders = (!empty($mailHeaders)) ? "\r\n" . preg_replace(array("/(?<!\r)\n/", "/\r(?!\n)/", "/\r\n\./"), array("\r\n", "\r\n", "\r\n.."), $mailHeaders) : '';
      // Create the default headers, attach any additonal headers
      $mailHeaders = "To: <".$mailCfg['To'].">\r\nFrom: <".$mailCfg['From'].">\r\nSubject: ".$mailCfg['Subject']."\r\nDate: " . gmdate('D, d M Y H:i:s') . " -0000".$mailHeaders;
      if(!mailPackets($mailHeaders."\r\n\r\n".$mailMsg."\r\n.", $smtpConnect, $logArray, 'SMTPbody')) // The message
      {
        return false;
      }
      mailPackets('QUIT', $smtpConnect, $logArray, 'SMTPquit'); // Say Bye to SMTP server
      fclose($smtpConnect); // Be nice and close the connection
      return true; // Return the fact we sent the message
  }
}
 
// This function sends the actual packets then logs the reponses and parses the reponse code
function mailPackets($sendStr,$mailConnect,&$logArray,$logName = '')
{
  $newLine = "\r\n"; // LEAVE THIS ALONE  
  $keyCount = 0;  // Just an incremental counter for when we get more than a single line response
  @fputs($mailConnect,$sendStr . $newLine); // Send the packet 
  do // Start grabbing the responses until we either get a terminal error or told we are at the end
  {
    $mailResponse = @fgets($mailConnect, 515); // Receive the response
    $keyCount++; // Incrememnt the key count
    $logArray[$logName . $keyCount] = $mailResponse; // Put the response in to the log array
    $responseCode = substr($smtpResponse, 0, 3); // Grab the response code from start of the response
    // Check for error codes except on ehlo, auth, and user details as they are not always fatal
    if((($logName != 'SMTPauth') && ($logName != 'SMTPuser') && ($logName != 'SMTPehlo') && ($logName != 'SMTPpass')) && ($responseCode >= 400))
    {  
       logMailError($logArray,$mailConnect);
       return false;
    }
    elseif((substr($responseCode, 0, 1) == 4) || ($responseCode >= 521) && ($logName != 'SMTPehlo'))
    {  
       logMailError($logArray,$mailConnect);
       return false;
    }
  }
  while((strlen($mailResponse) > 3) && (strpos($mailResponse, ' ') != 3)); // Loop until we get the end response
  return $responseCode; // Return the response code
}
 
function logMailError(&$logArray, $mailServer = false)
{
  if($mailServer)
  { 
    fclose($mailServer); // Be nice and close the connection
  }
  $fd = @fopen ('smtplog.txt', 'a'); // open the log file
  $mailResults = print_r($logArray, true); // Create a nice printable version of logArray
  @fwrite($fd,$mailResults); // Write the log
  @fclose ($fd); // Close the file
}
]]>
http://carbonize.co.uk/wp/2011/10/24/sending-email-via-smtp-using-php/feed/ 0
Gzipping your pages to save bandwidth http://carbonize.co.uk/wp/2009/02/13/gzipping-your-pages-to-save-bandwidth/ http://carbonize.co.uk/wp/2009/02/13/gzipping-your-pages-to-save-bandwidth/#comments Fri, 13 Feb 2009 00:26:11 +0000 http://www.carbonize.co.uk/Blog/archives/54-guid.html Ok I’ve been playing with Javascript frameworks like Jquery and Prototype. Now by default Jquery is 54KB and Prototype is 130KB (at the time of writing this). As you can see these are not small files. Now this is where gzip comes in. An easy way to describe gzip is that your server zips up the file before sending it to the web browser and the web browser then unzips it. Anyway by gzipping these two files using some PHP I have got Jquery down to 19KB and prototype down to 30KB!!!!

So we have Jquery:
Original Size: 54 KB
Gzipped Size: 19 KB
Data Savings: 64.81%

and prototype:
Original Size: 131 KB
Gzipped Size: 30 KB
Data Savings: 77.1%

All testing done using mod_zip test.

Anyway on to the code.

Ok to send something gzipped we need to use PHP’s buffer and so one of the first things we need to do is turn it on.

<?php
ob_start('ob_gzhandler');
?>

We would then just put our Javascript (or normal HTML) after the ?>

The ob_gzhandler is a function in PHP that checks if a browser supports gzip compression or not and if it doesn’t then PHP will not gzip the buffer.

Finally we tell PHP that we are done with the buffer and we want it to flush the buffer. Flush just means it sends the contents of the buffer to the browser and then closes the buffering.

<?php
ob_end_flush();
?>

And that’s it. So in a nutshell.

<?php
 ob_start('ob_gzhandler');
?>
 
<!-- Your Javascript or HTML here (or even PHP code) -->
 
<?php
ob_end_flush();
?>
]]>
http://carbonize.co.uk/wp/2009/02/13/gzipping-your-pages-to-save-bandwidth/feed/ 1
Using The PHP mail Function http://carbonize.co.uk/wp/2008/01/29/using-the-php-mail-function/ http://carbonize.co.uk/wp/2008/01/29/using-the-php-mail-function/#comments Tue, 29 Jan 2008 13:48:42 +0000 http://www.carbonize.co.uk/Blog/archives/35-guid.html Ok been a while since I posted anything so thought I would post my tutorial on using the PHP mail() function. I have basically copied my tutorial word for word from the Lazarus forum.

This is a brief (or not) tutorial on using the PHP mail() function to send emails from your scripts.

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

Let’s break that down. The bool means that the PHP mail function returns either true or false depending on if it was successful or not. The rest is pretty self explanatory. string $to is where we put the email address we want to send to. string $subject is where we put the emails subject and string $message is where we put our message. The string part just means that this variable will be treated as a string when used. We will cover $additional_headers a bit later and won’t even touch on $additional_parameters.

Ok so we want to send an email to Bill Gates with the subject Windows Linux and our message is When is it coming out?. The function we would use looks like this

<?php
mail(‘[email protected]’, ‘Windows Linux’, ‘When is it coming out?’);
?>


This would suit our needs but there are some things you need to know. Firstly this email will be sent as plain text so any HTML tags in the message would be displayed in the message. Second this email would have our servers address as the from address. Before I continue I would like to just briefly touch on the point that you can send to multiple address by putting them in the to section separated by a comma like ‘[email protected],[email protected]’. So now let us make it appear to come from our email address [email protected].

<?php
mail(‘[email protected]’, ‘Windows Linux’, ‘When is it coming out?’, ‘From: [email protected]’);
?>

As you can see we added a header to our email. The header is From and says what address the email was sent from. We could also use the format From: "Our Name" <[email protected]> so that it also has our name. This is fine and would suit most of your email sending needs but what if you want to send HTML? Then we need some more headers. They are MIME-Version and Content-type. So now our function looks like:

<?php
mail(‘[email protected]’, ‘Windows Linux’, ‘When is it coming out?’, "From: [email protected]\nMIME-Version: 1.0\nContent-type: text/html; charset=iso-8859-1");
?>

You will see I switched from using single quotes to double for the headers. This is because we need to separate the different headers with a new line marker (\n) and this does not work when using single quotes. I won’t say a lot about what the MIME type means. You can read up on that HERE. The Content-type says that the email is sent as text but is to be treated as HTML. Part of the Content-type is charset. This tells the email reader what character set to use when displaying the email. You will only have to change this if you are sending your email in a language other than English. Now when our recipient reads the email the word When will be bold.

You can also use the headers section to send carbon copies and blind carbon copies of the email to people by using CC: emailaddress and BCC: emailaddress respectively. You still need a main email address to send to though for these to work.

Now some might argue that you should use \r\n for separating the headers but in my experience just \n on it’s own is fine and will be understood by all email clients where as \r\n may cause problems.

Just a few notes.

If you are ending an email in a language other than English you may need to set the character set even for plain text. This is done the same as above but just replace the text/html with text/plain.

You can use variables for the relevant parts of the email. For example.

<?php
$recipient = ‘[email protected]';
$subject = ‘Windows Linux';
$message = ‘When is it coming out?';
$headers = ‘From: [email protected]';

mail($recipient, $subject, $message, $headers);
?>

As I also said earlier the mail function returns TRUE or FALSE depending on if it is successful in sending or not. So we can add some error checking like

<?php
if (@mail(‘[email protected]’, ‘Windows Linux’, ‘When is it coming out?’, ‘From: [email protected]’))
{
echo ‘Your mail was successfully sent';
}
else
{
echo ‘There was a problem and the email did not get sent';
}
?>

You may wonder what the @ is for in front of the mail. The @ before a function tells PHP not to display any error messages that may result from running that function. It just keeps things tidy as we are error checking anyway.

And that’s about it for the basic usage of the PHP mail() function. Next time I will explain how to send emails that are both HTML and plain text so that our recipient can read it regardless of their email reader. I will also explain about adding attachments to your emails and displaying attached images inside the body of the email.

]]>
http://carbonize.co.uk/wp/2008/01/29/using-the-php-mail-function/feed/ 0