PHP Snippets
Sep
05
Email Validation
Here is a nice little php function that will validate email addresses which is ideal for forms / registration on your website. The function provides an optional parameter to check the email against MX records for the domain in the email address.
<?php
function is_valid_email($email, $test_mx = false)
{
if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
if($test_mx)
{
list($username, $domain) = split("@", $email);
return getmxrr($domain, $mxrecords);
}
else
return true;
else
return false;
}
?>
- Source: Web Developer +
Aug
26
Extract Numbers from Text
Simple yet effective snippet of PHP code to extract numbers from a bit of text. This could be used for several things like extracting data amounts for example the below parses the width of a screenshot that was embedded in free form text by a client.
Invoke Function
$mytext = "The screen is 900px wide.". $mytext = extract_number($mytext);
Function Declaration
<?php
function extract_number($string) {
return ereg_replace("[^0-9]", "", $string);
}
?>
Aug
24
Sending Hebrew Mail to Outlook
A few weeks ago I had a client that needed a PHP contact form, no problem right. Wrong, the thing is he wanted to receive mails in Hebrew. I set it all up and worked fine in Thunderbird, Gmail, etc… , but would not display the Hebrew in MS Outlook. After hours of testing and searching I finally found a solution. The issue was the message headers, setting just the charset and mime type did not work, the content-language also needed to be set. Below is the snippet.
<?php // Your Email Address $ax_mailTo = 'you@tld.com'; // Contact Form Title $ax_mailSubject = '[Contact Form]' . $_POST['subject']; // IMPORTANT The base encoded subject, this prevents the title printing gibberish. $subject = "=?UTF-8?B?".base64_encode($ax_mailSubject)."?="; // Name from Contact Form $name = $_POST['contactName']; // Message from Contact Form $message = $_POST['message']; // The email contents. $body = ' Name: ' . $name . ' Email: ' . $email . ' Comments: ' . $message . ' '; // The message headers $headers = "From: $ax_mailTo" . "\r\n"; $headers .= "Reply-To: $ax_mailTo" . "\r\n"; $headers .= "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-language: he" . "\r\n"; $headers .= "Content-type: text/plain; charset=UTF-8"; // Send the mail mail($ax_mailTo, $subject, $body, $headers); ?>
Aug
20
Simple DailyPic / Picture of the Day
Below is a quick and simple way to achieve a Picture of the Day / DailyPic script without database access for your website. You can just about put this anywhere in your web site.
Usage
Modify the following variables to fit your Website. For your images you must name them according to date format 2011-08-19.jpg and place them in the folders expected by image_url, image_dir, etc.
<?php
$date = date("Y-m-d");
// URL to Images.
$image_url = "http://yourwebsite/DailyPic/photos/";
// Path to Images
$image_dir = "/path/to/your/site/htdocs/DailyPic/photos/";
// Default if no image is available for Today
$default = "http://yourwebsite/DailyPic/photos/default.jpg";
// Image Extension for Your Pics
$ext = ".jpg";
$photo = "$image_dir/$date" . $ext . "";
if (file_exists ($photo)){
echo '
<div class="potd">
<img src="'.$image_url.'/'.$date.$ext.'" border="0">
</div>
';
} else {
echo '
<div class="potd">
<img src="'.$default.'" border="0">
</div>
';
}
?>
Aug
16
Send Text Messages via PHP
Sending text messages with PHP is pretty much identical to sending an email using the built-in PHP function mail(). Instead of using an email address, however, you must use a combination of the phone number you are sending to as well as the hostname for the carrier.
Send Text Msg with PHP Mail Function
Note the use of 5558675309@txt.att.net as where the email address would usually be. For a list of all carriers’ host names and more info, visit the snippet source below.
<?php
mail("5558675309@txt.att.net", "", "Your packaged has arrived!", "From: FirstName LastName <emailaddy@somedomain.com>\r\n");
?>
- Source: DavidWalsh.name
Aug
16
Read a CSV File
If you ever need to read a CSV file for your web site, you may use the following PHP snippet to do so. This will cycle each line of the CSV file and echo each column’s data.
<?php
$importFile = "/path/to/file.csv";
$filedelim = "|";
if (($fhandle = fopen($importFile, "r")) !== FALSE) {
while (($coldata = fgetcsv($fhandle, 0, $filedelim, "\"")) !== FALSE) {
echo $coldata[0]; // first column's data
echo $coldata[1]; // second column's data, etc
}
}
?>
Aug
16
Country List Generator
The following PHP snippet will generate a dropdown or an unordered list of countries to use in a form or display in your web page. This is great for use in a registration or contact form on your web site.
Usage
$action = Type of Output (dropdown or list)
$selectedid = Selected option value (not needed)
<?php
function countrylist($action = 'dropdown', $selectedid = null) {
$country_list = array(
"Afghanistan", "Albania", "Algeria", "Andorra",
"Angola", "Antigua and Barbuda", "Argentina",
"Armenia", "Australia", "Austria", "Azerbaijan",
"Bahamas", "Bahrain", "Bangladesh", "Barbados",
"Belarus", "Belgium", "Belize", "Benin",
"Bhutan", "Bolivia", "Bosnia and Herzegovina",
"Botswana", "Brazil", "Brunei", "Bulgaria",
"Burkina Faso", "Burundi", "Cambodia", "Cameroon",
"Canada", "Cape Verde", "Central African Republic",
"Chad", "Chile", "China", "Colombi", "Comoros",
"Congo (Brazzaville)", "Congo", "Costa Rica",
"Cote d'Ivoire", "Croatia", "Cuba", "Cyprus",
"Czech Republic", "Denmark", "Djibouti", "Dominica",
"Dominican Republic", "East Timor (Timor Timur)",
"Ecuador", "Egypt", "El Salvador", "Equatorial Guinea",
"Eritrea", "Estonia", "Ethiopia", "Fiji", "Finland",
"France", "Gabon", "Gambia, The", "Georgia", "Germany",
"Ghana", "Greece", "Grenada", "Guatemala", "Guinea",
"Guinea-Bissau", "Guyana", "Haiti", "Honduras",
"Hungary", "Iceland", "India", "Indonesia", "Iran",
"Iraq", "Ireland", "Israel", "Italy", "Jamaica",
"Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati",
"Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan",
"Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya",
"Liechtenstein", "Lithuania", "Luxembourg", "Macedonia",
"Madagascar", "Malawi", "Malaysia", "Maldives", "Mali",
"Malta", "Marshall Islands", "Mauritania", "Mauritius",
"Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia",
"Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru",
"Nepa", "Netherlands", "New Zealand", "Nicaragua",
"Niger", "Nigeria", "Norway", "Oman", "Pakistan",
"Palau", "Panama", "Papua New Guinea", "Paraguay",
"Peru", "Philippines", "Poland", "Portugal", "Qatar",
"Romania", "Russia", "Rwanda", "Saint Kitts and Nevis",
"Saint Lucia", "Saint Vincent", "Samoa", "San Marino",
"Sao Tome and Principe", "Saudi Arabia", "Senegal",
"Serbia and Montenegro", "Seychelles", "Sierra Leone",
"Singapore", "Slovakia", "Slovenia", "Solomon Islands",
"Somalia", "South Africa", "Spain", "Sri Lanka", "Sudan",
"Suriname", "Swaziland", "Sweden", "Switzerland",
"Syria", "Taiwan", "Tajikistan", "Tanzania",
"Thailand", "Togo", "Tonga", "Trinidad and Tobago",
"Tunisia", "Turkey", "Turkmenistan", "Tuvalu",
"Uganda", "Ukraine", "United Arab Emirates", "United Kingdom",
"United States", "Uruguay", "Uzbekistan", "Vanuatu",
"Vatican City", "Venezuela", "Vietnam", "Yemen",
"Zambia", "Zimbabwe"
);
if ($action == 'dropdown') {
foreach ($country_list as $country) {
echo "<option value=\"".$country."\"";
if (!empty($selectedid)) {
if ($selectedid == $country) {
echo " selected=\"selected\"";
}
}
echo ">".$country."</option>\n";
}
}
elseif ($action == 'list') {
foreach ($country_list as $country) {
echo "<li>".$country."</li>\n";
}
}
}
?>
Example 1
<select name="country">
<?php countrylist('dropdown','Albania') ?>
</select>
Output
<select>
<option value=”Afghanistan”>Afghanistan</option>
<option value=”Albania” selected=”selected”>Albania</option>
<option value=”Algeria”>Algeria</option>
<option……………..
</select>
Example 2
<ul>
<?php countrylist('list') ?>
</ul>
Output
<ul>
<li>Afghanistan</li>
<li>Albania</li>
<li>Algeria</li>
<li……………..
</ul>
- Source: phpSnips


