The PHP library contains innumerable useful php code snippets which every developer needs to have in their “toolbox”. These php snippets offer a variety of handy functions which can ultimately end up saving you time. Today, we’ve collected 10 useful and handy php snippets which you may find useful within your coding endeavors. Enjoy !
1. The Real Way to Check Uploaded File Type
<!--?php <br ?-->// Here we specify all the type of files we want to accept $extension = array("application/pdf", "image/jpeg", "image/png", "image/gif"); if(isset($_POST['submit'])){ exec("file -i ".$_FILES['inputName']['tmp_name'], $output); $type = explode(':', (string)$output[0]); } // Here we check our file with our needs if (isset($_FILES['inputName']) && $_FILES['inputName']['error'] == UPLOAD_ERR_OK && $_FILES['inputName']['size'] <= 10000000 && in_array(trim($type[1]), $extension)){ var_dump($_FILES['inputName']['tmp_name']); }else{ die("File Error"); }
2. Add a Custom Message to the WordPress Editing Pane
<!--?php function wpemoticode_text_after_title( $post_type ) { ?--></pre> <div class="after-title-help postbox"> <h3>Using this screen</h3> <div class="inside"> Use this screen to add new articles or edit existing ones. Make sure you click 'Publish' to publish a new article once you've added it, or 'Update' to save any changes.</div> <!-- .inside --></div> <pre> <!-- .postbox --> <!--?php }<br ?-->add_action( 'edit_form_after_title', 'wpemoticode_text_after_title' );
3. Retrieve the Number of Facebook Page Followers
<!--?php $json = file_get_contents('http://api.facebook.com/method/fql.query?format=json&query=select+fan_count+from+page+where+page_id%3D475488679182886'); $decode = json_decode($json); echo $decode[0]--->fan_count; ?>
4. How to Expire a PHP Session After X Minutes
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) { // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage } $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp /* You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation: */ if (!isset($_SESSION['CREATED'])) { $_SESSION['CREATED'] = time(); } else if (time() - $_SESSION['CREATED'] > 1800) { // session started more than 30 minutes ago session_regenerate_id(true); // change session ID for the current session an invalidate old session ID $_SESSION['CREATED'] = time(); // update creation time } //note that session.gc_maxlifetime should be at least equal to the life time of this custom expiration handler (1800 in this example).
5. Change Role Access to Menus and Widgets
<!--?php // get the the role object $role_object = get_role('editor'); // add $cap capability to this role object $role_object--->add_cap('edit_theme_options'); ?>
6. Username Password and Data Validation with PHP
<!--?php function is_valid_username($username){ // accepted username length between 5 and 20 if (preg_match('/^\w{5,20}$/', $username)) return true; else return false; } function is_valid_password($pwd){ // accepted password length between 5 and 20, start with character. if (preg_match("/^[a-zA-Z][0-9a-zA-Z_!$@#^&]{5,20}$/", $pwd)) return true; else return false; } function is_valid_date($date){ //============ date format dd-mm-yyyy if(preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $sdate)) if(checkdate($sdate[2], $sdate[1], $sdate[3])) return true; } ?-->
7. Create Data URI’s
function data_uri($file, $mime) { $contents=file_get_contents($file); $base64=base64_encode($contents); echo "data:$mime;base64,$base64"; }
8. Generate QR Codes with Metadata
<!--?php function qr_code($data, $type = "TXT", $size ='150', $ec='L', $margin='0') { $types = array("URL" =--> "http://", "TEL" => "TEL:", "TXT"=>"", "EMAIL" => "MAILTO:"); if(!in_array($type,array("URL", "TEL", "TXT", "EMAIL"))) { $type = "TXT"; } if (!preg_match('/^'.$types[$type].'/', $data)) { $data = str_replace("\\", "", $types[$type]).$data; } $ch = curl_init(); $data = urlencode($data); curl_setopt($ch, CURLOPT_URL, 'http://chart.apis.google.com/chart'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, 'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $response = curl_exec($ch); curl_close($ch); return $response; } header("Content-type: image/png"); echo qr_code("http://emoticode.net", "URL"); ?>
9. Facebook Comments for WordPress
</pre> <div id="fb-root"></div> <pre> <script type="text/javascript">// <![CDATA[ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=Your App ID Here"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); // ]]></script> <meta content="Your App ID Here" /></pre> <div class="fb-comments" data-href="<?php the_permalink() ?>" data-num-posts="2" data-width="470" data-colorscheme="light" data-mobile="false"></div> <pre> // Get combined FB and WordPress comment count function get_full_comment_count() { global $post; $url = get_permalink($post->ID); $filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url); $json = json_decode($filecontent); $count = $json->$url->comments; $wpCount = get_comments_number(); $realCount = $count + $wpCount; if ($realCount == 0 || !isset($realCount)) { $realCount = 0; } return $realCount; } function the_full_comment_count() { $realCount = get_full_comment_count(); echo $realCount; }
10. Using PHP Mailer to Send HTML Emails with Images
<!--?php require("class.phpmailer.php"); $mail = new PHPMailer();$mail = new PHPMailer(); $mail--->IsSMTP(); $mail->Host = "smtp1.example.com;smtp2.example.com"; $mail->SMTPAuth = true; $mail->Username = 'smtpusername'; $mail->Password = 'smtppassword'; $mail->From="[email protected]"; $mail->FromName="My site's mailer"; $mail->Sender="[email protected]"; $mail->AddReplyTo("[email protected]", "Replies for my site"); $mail->AddAddress("[email protected]"); $mail->Subject = "Test 1"; $mail->IsHTML(true); $mail->AddEmbeddedImage('logo.jpg', 'logoimg', 'logo.jpg'); // attach file logo.jpg, and later link to it using identfier logoimg $mail->Body = "</pre> <h1>Test 1 of PHPMailer html</h1> <pre> This is a test picture: <img alt="" src="\"cid:logoimg\"" /> "; $mail->AltBody="This is text only alternative body."; if(!$mail->Send()) { echo "Error sending: " . $mail->ErrorInfo;; } else { echo "Letter is sent"; } ?>
Share