未加星标

20 Useful PHP Snippets for Beginner Web Developers

字体大小 | |
[开发(php) 所属分类 开发(php) | 发布者 店小二05 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Check out these20 usefulphp snippets for beginner web developers. These PHP snippets are perfect for all web developers, especially beginnerssince these codes can ease the development process and are easy to understand without any extensive PHP knowledge.

In this article, you will find code snippets for various functions such as associative array syntax, calendar function, check if a file exists, append a number to a name, change graphics based on season, adjust server time, and more.

You can even learn how to use PHP to convert HEX to RGB, create data URI’s, detect location by IP, crop image, validate email addresses, find all links to a page, get file size, find file extension, randomize background image,and more!

Adjust Server Time

This is a useful PHP snippet that allows you to adjust the server time. This is a simple code that can be used by beginner web developers.

$today = date('Y-m-d-G'); $today = strftime("%Y-%m-%d-%H", strtotime("$today -5 hour")); Append Non-Breaking Space Between Last Two Words

Here is a great code line that you can use to append non-breaking space between last two words. This PHP snippet is perfect for beginnerweb developers.

<?php
function word_wrapper($text,$minWords = 3) {
$return = $text;
$arr = explode(' ',$text);
if(count($arr) >= $minWords) {
$arr[count($arr) - 2].= ' '.$arr[count($arr) - 1];
array_pop($arr);
$return = implode(' ',$arr);
}
return $return;
}
?> Associative Array Syntax

Here is a PHP snippet of an associative array syntax. You have 3 variations that you can use: simple, array of associative arrays, and looping.

$carParts = array(
'Tires'=>100,
'Window'=>1042,
'DoorHandle'=>917
); Automatic Mailto Links

Use this PHP snippet to create automatic Mailto links. This can be used by all designers, beginners to advanced. Check out the code lines and see if you can use them in your projects!

$string = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})','<a href="mailto:\\1">\\1</a>', $text);
echo $string; Basic SimplePie Usage

Check out this small part of basic SimplePie usage PHP snippet that is perfect for beginner web developers. Take a look at this PHP snippet and use it in your current or upcoming projects.

<?php
require_once('inc/simplepie.inc');
$feed = new SimplePie();
$feed->set_feed_url(array(
'http://search.twitter.com/search.atom?q=movie'
));
$feed->enable_cache(true);
$feed->set_cache_location('cache');
$feed->set_cache_duration(15); Calendar Function

Here you have a part of a PHP code snippet that you can use to create calendars. In the code page, you have a preview of the result. Enjoy!

<?php
function build_calendar($month,$year,$dateArray) {
// Create array containing abbreviations of days of week.
$daysOfWeek = array('S','M','T','W','T','F','S');
// What is the first day of the month in question?
$firstDayOfMonth = mktime(0,0,0,$month,1,$year);
// How many days does this month contain?
$numberDays = date('t',$firstDayOfMonth); Change Graphics Based on Season

This is a small part of the PHP snippet thatshows you how to change graphics based on seasons. You have the complete code lines to fully create this result.

<?php
function current_season() {
// Locate the icons
$icons = array(
"spring" => "images/spring.png",
"summer" => "images/summer.png",
"autumn" => "images/autumn.png",
"winter" => "images/winter.png"
);
// What is today's date - number
$day = date("z"); Check if File Exists / Append Number to Name

This is a very useful PHP snippet that all beginnerweb developers can use. When using this code lines, if the name doesn’t exist, you will receive a file name with _number.

function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
$counter = 0;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
return $newname;
} Convert HEX to RGB

Take a look at this PHP snippet and see if you can use it for your projects. This code is great to converts HEX to array RGB values. Enjoy!

function hex2rgb( $colour ) {
if ( $colour[0] == '#' ) {
$colour = substr( $colour, 1 );
}
if ( strlen( $colour ) == 6 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
} elseif ( strlen( $colour ) == 3 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
} else {
return false;
}
$r = hexdec( $r );
$g = hexdec( $g );
$b = hexdec( $b );
return array( 'red' => $r, 'green' => $g, 'blue' => $b );
} Create Data URI’s

These can be useful for embedding images into HTML/CSS/JS to save on HTTP requests, at the cost of maintainability. More information. There are online tools to do it, but if you want your own very simple utility, here’s some PHP to do it:

function data_uri($file, $mime) {
$contents=file_get_contents($file);
$base64=base64_encode($contents);
echo "data:$mime;base64,$base64";
} Crop Image

Here is a preview of the PHP snippet that lets you crop any image. These code lines can be used by all designers, beginners to experienced.

<?php
$filename= "test.jpg";
list($w, $h, $type, $attr) = getimagesize($filename);
$src_im = imagecreatefromjpeg($filename);
$src_x = '0'; // begin x
$src_y = '0'; // begin y
$src_w = '100'; // width
$src_h = '100'; // height
$dst_x = '0'; // destination x
$dst_y = '0'; // destination y Detect Location by IP

This PHP code snippet was written by Chris Coyier. Here you have a part of the full code that allows you to detect location by using the IP information.

function detect_city($ip) {
$default = 'UNKNOWN';
if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
$ip = '8.8.8.8';
$curlopt_useragent = 'Mozilla/5.0 (windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
$url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
$ch = curl_init(); Email Address Validation

Here you have a very useful PHP code that lets you validate any email address. This comes in handy when needed to verify a given email address.

$email = [email protected]';
$validation = filter_var($email, FILTER_VALIDATE_EMAIL);
if ( $validation ) $output = 'proper email address';
else $output = 'wrong email address';
echo $output; Find All Links on a Page

Take a look at this PHP snippet and see if you can use it in your current or upcoming projects. These code lines let you identify all the links from a page.

$html = file_get_contents('http://www.example.com');
$dom = new DOMDocument();
@$dom->loadHTML($html);
// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath-&gt

本文开发(php)相关术语:php代码审计工具 php开发工程师 移动开发者大会 移动互联网开发 web开发工程师 软件开发流程 软件开发工程师

主题: PHPHTMLWindowsCSSWordFirefox
分页:12
转载请注明
本文标题:20 Useful PHP Snippets for Beginner Web Developers
本站链接:http://www.codesec.net/view/532204.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(php) | 评论(0) | 阅读(99)