Today is Sunday
September 5, 2010

Search Results Category: PHP

August 3, 2010

Finding and Verifying U.S. Dollar amounts with PHP

by Chris — Categories: Coding, PHP — Tags: , 1 Comment

Ok so the idea is you have a user input form. In that form you have your users providing a dollar amount of some sort. But how do you verify this dollar amount is correct. Meaning is it a numeric value, is it in a dollar format, etc.. Well with this little function I hope to help you achieve finding out a little easier that the posted variable is indeed a valid dollar amount or not.

function verifyMoney($what){
   if (preg_match('#^[0-9]+(\.[0-9]{0,2})?$#', $what)){
     $monkey = number_format($what, 2);
     return $monkey;
   }else{ return FALSE; }
}

What this will do is if the dollar amount is not both numeric and in a dollar format (ie: 0.00) it will return false, otherwise it will return what its given.

Demo:
Good: 1,502.38
Bad: 10O.00 came back false.

Example of usage:

$goodmoney = "1502.38";
$badmoney = "10O.00";

if(verifyMoney($goodmoney) !== FALSE) {echo "Good: ".verifyMoney($goodmoney);}else{echo "The Dollar amount you have entered is not valid";}
echo "<br />";

if(verifyMoney($badmoney) == FALSE) {echo "Bad: ".$badmoney." came back false.";}else{echo "The Dollar amount you have entered is valid";}

How to use PHP mail() with HTML and CSS

by Chris — Categories: Coding, PHP — Tags: 1 Comment

The  php mail() function. Such a simple function with so much versatility. Now I know, I know.. trust me I know! There are dozens of tutorials out there on the subject of PHP mail() and its functionality. But how many of them are based off the core concept, and how to use it statically at best with hard coded variables. Example…

$email = "myemail@exmple.com";
$subject4email = "This is a Subject";
$message4email = "Thanks for triggering this email to be sent";
mail($email, $subject4email, $message4email);

How many “php mail” tutorials have you seen like that today while searching for your solution? Chances are they are long winded but up the ally of just giving you the above mentioned code.

Well with this short post I intend on showing you a way many people spend hours searching for to end up sitting on forums eventually waiting for an answer that may never come. PHP’s mail() function is great. But as mentioned above almost all people who give tutorials on the subject show the most core basic concept. Which is fine if you plan to send your self emails in plain text. What I want to show you here is based on the ever growing demand for wanting to send something a bit fancier to your users or even yourself (if your like me, even personal statistics and logs have to look ascetically pleasing even if its only me who will ever see it). So in this post I will give you the core basics of how to code a HTML based template using CSS and standard HTML for use with Email and being sent through PHP. Mind you basic. Im not going to provide you with a fully custom tailored solution. I want to leave it open a bit so you can build on it with ease. This example could be used for example if you have an automated mail to go to new members on your site but its far from limited to the idea of just that.

Full Code:

$mydomain = "somedomain.net";
$username = $selectusers;
$email_who = $selectusersemails;
$titlesubject = $mymessagetitle;
$messagebody = $mymessage;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
  <head>
<title>' . $titlesubject . '</title>
</head>
<style type="text/css">
<!--
body {background: #edebea;}
#wrapper {background: #fff;border: 4px solid #ddd;}
-->
</style>
</head>
<body><table width="650" id="wrapper">
<tr>
<td>Your Sites Image Logo or slogan or text or link</td>
<td>Dear '.$username.'</td>
<td>'.$messagebody.'</td>
<td>Footer information, copyrights, other..</td>
</tr>
</table>
</body>
</html>
';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=us-ascii' . "\r\n";
$headers .= 'From: noreply@'. $mydomain . "\r\n";
$headers .= 'Reply-To: noreply@'. $mydomain . "\r\n";
$headers .= '1\r\nX-MSMail-Priority: High' . "\r\n";
$headers .= 'X-Mailer: Monkey Tooth Productions Mailer v1.0.0' . "\r\n";
mail($email_who, $titlesubject, $message, $headers);

Now with the above You can see sending an HTML based email through PHP’s mail() function is not as hard as one would have thought, yet its a pain in the arse to find information on (or was when I last looked some time ago, but then again I still see it asked in forums a lot so either way I suppose).

Now as you can see as I mentioned before this is thee absolute core concept of sending an HTML based email with CSS with PHP

$username = $selectusers;
$email_who = $selectusersemails;
$titlesubject = $mymessagetitle;
$messagebody = $mymessage;

The above four variables can be set to anything and set through any means you choose whether is something through a database query or hard coded in to a combination of the two. However only two of the four above are required with the above mentioned script. Those being $titlesubject and $email_who but you can populate them however you wish. The other two $messagebody and $username are solely for the sake of example within the $message variable.

Now its worth mentioning as you can see I added a variable for the domain $mydomain All though you could use anything its suggested that you keep it specific to your domain the main reason I added this one variable is if you look at the script you will notice that its called a few times within the headers for example. I figured one place to edit it is easier than several. Main reason you want to keep it specific to your domain is well despite what you change it to the email ISP provider will be able to track it back to your domain. So making it something different will only trigger the email provider to throw it in the spam folder. All in all since I mention the spam concept It is possible to have all your emails land directly in the spam box of any give email you send But that will almost always be due to your choice of $messagebody variable in this example. I say this because I have been using this concept for years now with very little feedback of my messages landing in someone spam bin. Mind you I specify mine as I am careful with my messages. I keep them low key with little to no references that can trigger a spam filter into throwing the email into a spam folder.

Prevention Tips try not to use to many links in your emails sent if you have to try to use full urls as you would for the link itself to go to as the links text as well if they match its good use a spell check on your message prior to sending to many misspelled words can be bad to.

Convert a Unix Timestamp to MySQL DATETIME Timestamp with PHP using date()

Well if your like me you like to diversify your usage of timestamps or just like me as well when I first got into coding with PHP I didn’t know much about how to properly mesh PHP with a MySQL Database, and to be quite frank the tutorials out there at the time and even currently (Well the ones with any search engine rankings at least) Still show how us to use a time() based timestamp on many of our elements. However a couple key issues with that now a days is if your going to make any site about anything with any form of user end input, feedback, or otherwise your going to eventually need to use a database for it. Or a part there of at the very least, that said if your using older timestamps like the time() function generates then you already know the problem. Actually you must know if your skimming through this post. Now where the time() function seems like the best bet as its the easiest to do math with for things like session time outs, its not typically prime for so many of mySQL’s features for date ranges and other various time/date functions within mySQL that make handling sessions and so much more easier now a days. So here it is, my simple little solution

function unixToMySQL($timestamp){
return date('Y-m-d H:i:s', $timestamp);
}

Unix Timestamp Example: 1283664323
Above Timestamp converted to MySQL DATETIME: 2010-09-05 05:25:23

I use it as a function just out of my own practices to call things from a global file that contain functions used widely through out sites I develop. This function can also be developed upon heavily to do various other conversions but I figured I would give you what I found most people look for specifically. Myself included at one time. The live example above is equivilant to a MySQL DATETIME date using NOW()

Example of usage:

$blah = time();
echo unixToMySQL($blah);

Display Random YouTube Videos on your site or blog with PHP

by Chris — Categories: Coding, PHP — Tags: , , 4 Comments

Well here is another random function from my little repository.. A little while back one of my clients presented me with the idea that they wanted to display a set of videos from there YouTube gallery at random on there home page and various other sections of there site. But only specific videos did they want. So from that I created a little function. That would do just that. I will say though this function is a bit toned down from what I actually gave them as they wanted a small control panel to go with it ran off a mysql database so they could add and remove videos from from randomly chosen videos they provided from there YouTube gallery they also wanted to provide a brief description on there page for each one as well amongst a couple other things with it. Which I may re-tailor that version of the script eventually and release it to the public as I think its a nice idea. Could make for a good 404 error page or like with them a good way to keep the content on there main page changing but also display some of there portfolio of videos at the same time.

Anyway back to the meat of this article I doubt you want to read more than you have to and lets face it, if you’ve seen my other articles here you would know writing isn’t really my forte. That said heres the code and a brief explanation and as always a demo of it working.

function randomTube(){
    $RVideoArray = array('q8SWMAQYQf0', 'q8SWMAQYQf0', 'q8SWMAQYQf0', 'hpxxvOU3vbI');
    $RVideoCount = count($RVideoArray);
    $RVideoSelect = rand(0, $RVideoCount - 1);
    $RVideoNum = trim($RVideoSelect);
    $RVideo = $RVideoArray[$RVideoNum];
    $theTube = '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/'.$RVideo.'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'.$RVideo.'" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>';
    return $theTube;
}

In this version of the script, I have set up an array that you can add/remove you’re choice of YouTube videos from. All you need to do is obtain the YouTube short code for the video or what ever it is they call it specificly, I call it short code cause to me it resembles a familiar look/feel to that of a short URL through something like bit.ly. But thats off topic. With almost any youtube video there is always a URL construct similar to www.youtube.com/watch?v= what follows the v= and in some cases comes before the next & is the actual bit of the URL you are looking for to use with the array $RVideoArray in the function above.

Example of usage for the Random YouTube video function is.

$myRandomVideo = randomTube(); echo $myRandomVideo;

June 27, 2010

Javascript vs PHP

by Chris — Categories: Coding, Javascript, PHP — Tags: , , , 7 Comments

This is a question I often see and get. “Which one should I use, JavaScript or php?” Well in the end it all boils down to what your doing and how your are expecting it to handle. The biggest key differences between JavaScript and PHP is one runs or renders rather while the page is loading. While the other can do stuff to a page while its loading or after it has loaded.

Both languages are very similar in construct or at least they are in my opinion, and you write code almost the same way. Obviously they have different built in functions, and names for the functions, and they differ here and there. Generally you can almost do anything with JavaScript that you can with PHP and vice versa.

Now comes again the question “Which should I use?”. Well I personally like PHP for a wide array of things and will generally use it over JavaScript when possible however with todays technology always trying to push the bar up and tempting to break the barriers of just how far you can push someones browsers abilities I do favor AJAX which is the use of PHP and JavaScript together. I say “when possible” because there are times where it definitely is not wise to use AJAX. But thats only due to security concerns. But worry not, most applications you will build with AJAX if you use it wisely and properly you wont have much to worry about. Which one day I am sure I will write an article or many about that.

If you want your elements to be flashy and less bandwidth consuming I would suggest using JavaScript where and when possible to handle your pages content and how its loaded, then handled there after. If bandwidth isn’t much of an issue for you which with most hosting providers it isn’t (unless your pushing several thousands of gigs of there bandwidth a month, then you should check the fine print in there contracts). Then handle everything via PHP its a bit more static, pages have to load but if used properly its as secure as it gets, and can run pretty fast as well.

If your interested in going the AJAX route which I highly recommend I would suggest using jQuery. As its the most stable and mature of frameworks out there and has a much larger community of developers to help get answers from if you ever get stuck.

Are you recently starting out with php, javascript, ajax, mysql, or really any web related scripting language? If you are might I suggest to you a site that helped even me learn the basics years upon years ago. http://www.tizag.com they don’t cover everything, but they cover more than just the simple basics and can give you a good footing on any given scripting language.

AJAX ready frameworks that you can choose from in no particular order (obtained from Wikipedia):

jQuery
jQuery UI (used with jQuery)
Prototype
Script.aculo.us (used with prototype)
Ext (now known as Sencha)
MooTools
Yahoo! UI Library
Dojo Toolkit

Quick Question I see with these framworks mostly due to people searching for ready made scripts is can you use more than one framework. Well ultimately it depends which you use. I know jQuery (even combined with UI) you can set it up to allow other frameworks as mentioned on the jQuery site in there article/post about the subject Using jQuery with Other Libraries however outside of that I cant really vouch for the other libraries and there support on the subject as I prefer jQuery and use that over the rest when ever possible (unless I am working on a clients site and they have something different from jQuery)

June 23, 2010

PHP create a random string of Alpha/Numeric Characters

by Chris — Categories: Coding, PHP — Tags: , , No Comments

Have a need for a quick random string of any given length but want to limit it to a-z 0-9. Then this would be ideal for you, I really can’t think of any real world use for this. Well no thats wrong, you can use it as a random password generator. Or something to the effect of that.

<?php
function genRandomString($howbig) {
$length = $howbig;
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$string = '';

for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}

return $string;
}
echo "<strong>5 char string:</strong> ". genRandomString('5') ."<br />";
echo "<strong>10 char string:</strong> ".genRandomString('10')."<br />";
echo "<strong>15 char string:</strong> ".genRandomString('15')."<br />";
echo "<strong>20 char string:</strong> ".genRandomString('20')."<br />";
echo "<strong>50 char string:</strong> ".genRandomString('50')."<br />";
?>

Example of use:
5 char string: xe082
10 char string: rbehqgr4s
15 char string: ar6uqm8cuptgyua
20 char string: xjslrj8nz0bcsdzwkl3z
50 char string: ug9q2im3iw986zk1qykhm42bq5sm333elpkquwn2goi6dwsvq

June 22, 2010

PHP truncate/shorten string, variable, text

by Chris — Categories: Coding, PHP — Tags: , , No Comments

Every now and again on my projects I come into a spot where I have limited room to display any given amount of text that is generated and updated dynamically. Example I have a length of text thats 400 some odd characters long. I only have room for 120 characters. “So what do I do?” If your asking yourself that question then I have an answer for you, keep in mind not THE answer as there are better solutions out there that will trim truncate any given string down to the number you want but leaving full words in tact at the end rather then cut them off mid word. This function I will show you here that I made for myself a while back is expandable to do such things however I haven’t ran into the need or desire to expand it as such myself as it works for what I use it for without problem.

<?php function ShortenText($text, $chars) {
// Change to the number of characters you want to display
$chars = $chars;
$text = $text."";
$countchars = strlen($text);

if($countchars > $chars) {
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
}

return $text;
}
$myText = "Welcome to Monkey Tooth Productions.";
echo ShortenText($myText, 20);
?>

Translates to:
Welcome to Monkey…

It automatically appends the “…” to the string so try to remember that if you need 20 max you should set it to 17 however you can change that or remove it even if you like.

Well as with any code I throw up here on the site, if you expand this and improve it let me know. I’d be happy to see what you guys do with it.

PHP get IP Address

by Chris — Categories: Coding, PHP — Tags: , , , , No Comments

I have seen this done a hundred and one ways (figuratively speaking of course). However each way I have seen it there was always the occasion something would come up short, and the IP variable would come up undefined or empty. So it eventually lead me to having to tailor my own solution to obtain either my IP or a users IP depending on what my cause is.

Example: Your IP is: 38.107.191.106

How was this obtained? Through a rather simple process of elimination. Since there are multiple ways to get an IP address, yet not a single one of them works every time dependent on the user side of things. So what I have done is made a little function to try diffrent methods and then return the result to me. See the code below. It’s that simple. Although I am sure some of you are likely able to expand on this in a multitude of ways i’d be happy to see what come up with.

<?php
function getRealIpAddr(){

if(!empty($_SERVER['HTTP_CLIENT_IP'])){$ip=$_SERVER['HTTP_CLIENT_IP'];}

elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];}

else{$ip=$_SERVER['REMOTE_ADDR'];}

return $ip;
}
echo "Example: Your IP is: ".getRealIpAddr();
?>

PHP my domain name

by Chris — Categories: Coding, PHP — Tags: , No Comments

Need to find your domain name for a script? Maybe you want to ensure something thats going to run is being run on your site and your site alone. In concept for example trying to protect your script from XSS attacks, say in a case where your using AJAX to POST/GET JSON requests (but this is only a small example of why you might want to implement something like this).

<?php
$mydomain = $_SERVER['HTTP_HOST'];
$mydomain = str_replace('www.''', $mydomain);

if($mydomain == "your-domain-name.com"){
/*your domain found, script to run*/
}else{
/*your domain NOT found, script to run*/
}
?>

Now some people will most likely argue that you should use

$_SERVER['SERVER_NAME']

instead of

$_SERVER['HTTP_HOST']

And this is plausible as they do pretty much the same exact thing. However the key difference is how one reads off the server versus the other, I would go in to the differences but Chris Shiflett puts it together in a nice summary in his article SERVER_NAME Versus HTTP_HOST and backs it up with various tests and other articles he has found on the subject.

© 2010 Monkey Tooth Productions All rights reserved - Wallow theme by TwoBeers Crew - Powered by WordPress - Have fun!