SlideShare a Scribd company logo
1 of 13
PHP Code examples
By
PHP resources
PHP resources
Contents
Contents................................................................................................................................................2
Check for valid email address............................................................................................................3
Getting real IP address.......................................................................................................................3
Resize Image......................................................................................................................................4
Import CSV File..................................................................................................................................5
iPhone & iPod Detection....................................................................................................................5
Display source code of any webpage.................................................................................................5
Display Facebook fans count.............................................................................................................5
Download & save a remote image.....................................................................................................5
Send Mail using mail function in PHP................................................................................................6
HTTP Redirection...............................................................................................................................6
Human Readable Random String ......................................................................................................6
Parse JSON Data ................................................................................................................................7
Parse XML Data .................................................................................................................................7
Directory Listing in PHP......................................................................................................................8
Unzip a Zip File...................................................................................................................................9
Crop Image......................................................................................................................................10
Create Zip Files.................................................................................................................................11
Test whether URL exists...................................................................................................................12
For more programming information and code................................................................................13
PHP resources
Check for valid email address
function is_valid_email($email)
{
if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0)
return true;
else
return false;
}
Getting real IP address
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
//to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
PHP resources
Resize Image
Creates a thumbnail from an existing image. $filename is the original filename, while $tmpname is
the actual filesystem name (for example, the temporary filename used in a PHP upload). Returns an
image resource which you can then output to the browser, or save to a file using imagejpg(),
imagepng(), etc.
function resize_image($filename, $tmpname, $xmax, $ymax)
{
$ext = explode(".", $filename);
$ext = $ext[count($ext)-1];
if($ext == "jpg" || $ext == "jpeg")
$im = imagecreatefromjpeg($tmpname);
elseif($ext == "png")
$im = imagecreatefrompng($tmpname);
elseif($ext == "gif")
$im = imagecreatefromgif($tmpname);
$x = imagesx($im);
$y = imagesy($im);
if($x <= $xmax && $y <= $ymax)
return $im;
if($x >= $y) {
$newx = $xmax;
$newy = $newx * $y / $x;
}
else {
$newy = $ymax;
$newx = $x / $y * $newy;
}
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
return $im2;
}
PHP resources
Import CSV File
$handle = fopen("file.csv", 'r');
while(($data = fgetcsv($handle, 1000, ",")) !== false)
{
list($col1, $col2, ...) = $data;
}
fclose($handle);
iPhone & iPod Detection
if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod'))
{
header('Location: http://yoursite.com/iphone');
exit();
}
Display source code of any webpage
<?php
$lines = file('http://google.com/');
foreach ($lines as $line_num => $line)
{
// loop thru each line and prepend line numbers
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "n";
}
Display Facebook fans count
function fb_fan_count($facebook_name)
{
<a href="https://graph.facebook.com/digimantra">https://graph.facebook.com/digimantra</a>
$data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
echo $data->likes;
}
Download & save a remote image
PHP resources
$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image);
Send Mail using mail function in PHP
<?php
$to = "emailaddress@gmail.com";
$subject = "getph[.net";
$body = "Body of your message
$headers = "From: Peterrn";
$headers .= "Reply-To: info@programmershelp.netrn";
$headers .= "Return-Path: info@ programmershelp.net rn";
$headers .= "X-Mailer: PHP5n";
$headers .= 'MIME-Version: 1.0' . "n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
mail($to,$subject,$body,$headers);
?>
HTTP Redirection
<?php
header('Location: http://you_stuff/url.php'); // stick your url here
?>
Human Readable Random String
/**************
*@length - length of random string (must be a multiple of 2)
**************/
function readable_random_string($length = 6){
$conso=array("b","c","d","f","g","h","j","k","l",
"m","n","p","r","s","t","v","w","x","y","z");
$vocal=array("a","e","i","o","u");
$password="";
srand ((double)microtime()*1000000);
$max = $length/2;
for($i=1; $i<=$max; $i++)
{
$password.=$conso[rand(0,19)];
$password.=$vocal[rand(0,4)];
}
return $password;
}
PHP resources
Parse JSON Data
$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php
Parse XML Data
//xml string
$xml_string="<?xml version='1.0'?>
<users>
<user id='398'>
<name>Foo</name>
<email>foo@bar.com</name>
</user>
<user id='867'>
<name>Foobar</name>
<email>foobar@foo.com</name>
</user>
</users>";
//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);
//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email, '<br />';
}
PHP resources
Directory Listing in PHP
<?php
function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db)
{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."n";
}
}
closedir($handle);
}
}
}
/*
To use:
<?php
list_files("images/");
?>
*/
?>
PHP resources
Unzip a Zip File
<?php
function unzip($location,$newLocation){
if(exec("unzip $location",$arr)){
mkdir($newLocation);
for($i = 1;$i< count($arr);$i++){
$file = trim(preg_replace("~inflating: ~","",$arr[$i]));
copy($location.'/'.$file,$newLocation.'/'.$file);
unlink($location.'/'.$file);
}
return TRUE;
}else{
return FALSE;
}
}
?>
//Use the code as following:
<?php
include 'functions.php';
if(unzip('zippedfiles/test.zip','unzipped/myNewZip'))
echo 'Success!';
else
echo 'Error';
?>
PHP resources
Crop Image
<?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 = '200'; // width
$src_h = '200'; // height
$dst_x = '0'; // destination x
$dst_y = '0'; // destination y
$dst_im = imagecreatetruecolor($src_w, $src_h);
$white = imagecolorallocate($dst_im, 255, 255, 255);
imagefill($dst_im, 0, 0, $white);
imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
header("Content-type: image/png");
imagepng($dst_im);
imagedestroy($dst_im);
?>
PHP resources
Create Zip Files
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE :
ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
/***** Example Usage ***/
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
create_zip($files, 'myzipfile.zip', true);
PHP resources
Test whether URL exists
function url_exists($url)
{
$hdrs = @get_headers($url);
return is_array($hdrs) ? preg_match('/^HTTP/d+.d+s+2dds+.*$/',$hdrs[0]) : false;
}
PHP resources
For more programming information and code
PHP resources
Programmers help
Programming site
PHP resources

More Related Content

What's hot

What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16Ricardo Signes
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Intro to php
Intro to phpIntro to php
Intro to phpSp Singh
 
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoIntroduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoMasahiro Nagano
 
Cli the other SAPI confoo11
Cli the other SAPI confoo11Cli the other SAPI confoo11
Cli the other SAPI confoo11Combell NV
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2Hugo Hamon
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
Generated Power: PHP 5.5 Generators
Generated Power: PHP 5.5 GeneratorsGenerated Power: PHP 5.5 Generators
Generated Power: PHP 5.5 GeneratorsMark Baker
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0Elena Kolevska
 
Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Andrew Shitov
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappersPositive Hack Days
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in OptimizationDavid Golden
 

What's hot (20)

What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16
 
Neatly folding-a-tree
Neatly folding-a-treeNeatly folding-a-tree
Neatly folding-a-tree
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
dotCloud and go
dotCloud and godotCloud and go
dotCloud and go
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 
Intro to PHP
Intro to PHPIntro to PHP
Intro to PHP
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoIntroduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
 
Cli the other SAPI confoo11
Cli the other SAPI confoo11Cli the other SAPI confoo11
Cli the other SAPI confoo11
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Inc
IncInc
Inc
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Generated Power: PHP 5.5 Generators
Generated Power: PHP 5.5 GeneratorsGenerated Power: PHP 5.5 Generators
Generated Power: PHP 5.5 Generators
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0
 
Redis for your boss
Redis for your bossRedis for your boss
Redis for your boss
 
Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 

Viewers also liked

Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?Carl Sack
 
Invisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundariesInvisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundariesCarl Sack
 
WebGIS is Fun and So Can You
WebGIS is Fun and So Can YouWebGIS is Fun and So Can You
WebGIS is Fun and So Can YouCarl Sack
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrapZunair Sagitarioux
 
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Cedric Spillebeen
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to BootstrapRon Reiter
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Viewers also liked (13)

PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
Jquery examples
Jquery examplesJquery examples
Jquery examples
 
Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?
 
Invisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundariesInvisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundaries
 
WebGIS is Fun and So Can You
WebGIS is Fun and So Can YouWebGIS is Fun and So Can You
WebGIS is Fun and So Can You
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrap
 
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
 
Bootstrap ppt
Bootstrap pptBootstrap ppt
Bootstrap ppt
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to Bootstrap
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar to PHP Code Snippets for Common Tasks

Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with PerlDave Cross
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 WorldFabien Potencier
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop NotesPamela Fox
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?Radek Benkel
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Service intergration
Service intergration Service intergration
Service intergration 재민 장
 
Does your configuration code smell?
Does your configuration code smell?Does your configuration code smell?
Does your configuration code smell?Tushar Sharma
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPMariano Iglesias
 

Similar to PHP Code Snippets for Common Tasks (20)

PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
Php hacku
Php hackuPhp hacku
Php hacku
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
08 php-files
08 php-files08 php-files
08 php-files
 
Php introduction
Php introductionPhp introduction
Php introduction
 
php part 2
php part 2php part 2
php part 2
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Service intergration
Service intergration Service intergration
Service intergration
 
Does your configuration code smell?
Does your configuration code smell?Does your configuration code smell?
Does your configuration code smell?
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 

Recently uploaded

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

PHP Code Snippets for Common Tasks

  • 1. PHP Code examples By PHP resources PHP resources
  • 2. Contents Contents................................................................................................................................................2 Check for valid email address............................................................................................................3 Getting real IP address.......................................................................................................................3 Resize Image......................................................................................................................................4 Import CSV File..................................................................................................................................5 iPhone & iPod Detection....................................................................................................................5 Display source code of any webpage.................................................................................................5 Display Facebook fans count.............................................................................................................5 Download & save a remote image.....................................................................................................5 Send Mail using mail function in PHP................................................................................................6 HTTP Redirection...............................................................................................................................6 Human Readable Random String ......................................................................................................6 Parse JSON Data ................................................................................................................................7 Parse XML Data .................................................................................................................................7 Directory Listing in PHP......................................................................................................................8 Unzip a Zip File...................................................................................................................................9 Crop Image......................................................................................................................................10 Create Zip Files.................................................................................................................................11 Test whether URL exists...................................................................................................................12 For more programming information and code................................................................................13 PHP resources
  • 3. Check for valid email address function is_valid_email($email) { if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0) return true; else return false; } Getting real IP address function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } PHP resources
  • 4. Resize Image Creates a thumbnail from an existing image. $filename is the original filename, while $tmpname is the actual filesystem name (for example, the temporary filename used in a PHP upload). Returns an image resource which you can then output to the browser, or save to a file using imagejpg(), imagepng(), etc. function resize_image($filename, $tmpname, $xmax, $ymax) { $ext = explode(".", $filename); $ext = $ext[count($ext)-1]; if($ext == "jpg" || $ext == "jpeg") $im = imagecreatefromjpeg($tmpname); elseif($ext == "png") $im = imagecreatefrompng($tmpname); elseif($ext == "gif") $im = imagecreatefromgif($tmpname); $x = imagesx($im); $y = imagesy($im); if($x <= $xmax && $y <= $ymax) return $im; if($x >= $y) { $newx = $xmax; $newy = $newx * $y / $x; } else { $newy = $ymax; $newx = $x / $y * $newy; } $im2 = imagecreatetruecolor($newx, $newy); imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y); return $im2; } PHP resources
  • 5. Import CSV File $handle = fopen("file.csv", 'r'); while(($data = fgetcsv($handle, 1000, ",")) !== false) { list($col1, $col2, ...) = $data; } fclose($handle); iPhone & iPod Detection if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod')) { header('Location: http://yoursite.com/iphone'); exit(); } Display source code of any webpage <?php $lines = file('http://google.com/'); foreach ($lines as $line_num => $line) { // loop thru each line and prepend line numbers echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "n"; } Display Facebook fans count function fb_fan_count($facebook_name) { <a href="https://graph.facebook.com/digimantra">https://graph.facebook.com/digimantra</a> $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name)); echo $data->likes; } Download & save a remote image PHP resources
  • 6. $image = file_get_contents('http://www.url.com/image.jpg'); file_put_contents('/images/image.jpg', $image); Send Mail using mail function in PHP <?php $to = "emailaddress@gmail.com"; $subject = "getph[.net"; $body = "Body of your message $headers = "From: Peterrn"; $headers .= "Reply-To: info@programmershelp.netrn"; $headers .= "Return-Path: info@ programmershelp.net rn"; $headers .= "X-Mailer: PHP5n"; $headers .= 'MIME-Version: 1.0' . "n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn"; mail($to,$subject,$body,$headers); ?> HTTP Redirection <?php header('Location: http://you_stuff/url.php'); // stick your url here ?> Human Readable Random String /************** *@length - length of random string (must be a multiple of 2) **************/ function readable_random_string($length = 6){ $conso=array("b","c","d","f","g","h","j","k","l", "m","n","p","r","s","t","v","w","x","y","z"); $vocal=array("a","e","i","o","u"); $password=""; srand ((double)microtime()*1000000); $max = $length/2; for($i=1; $i<=$max; $i++) { $password.=$conso[rand(0,19)]; $password.=$vocal[rand(0,4)]; } return $password; } PHP resources
  • 7. Parse JSON Data $json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} '; $obj=json_decode($json_string); echo $obj->name; //prints foo echo $obj->interest[1]; //prints php Parse XML Data //xml string $xml_string="<?xml version='1.0'?> <users> <user id='398'> <name>Foo</name> <email>foo@bar.com</name> </user> <user id='867'> <name>Foobar</name> <email>foobar@foo.com</name> </user> </users>"; //load the xml string using simplexml $xml = simplexml_load_string($xml_string); //loop through the each node of user foreach ($xml->user as $user) { //access attribute echo $user['id'], ' '; //subnodes are accessed by -> operator echo $user->name, ' '; echo $user->email, '<br />'; } PHP resources
  • 8. Directory Listing in PHP <?php function list_files($dir) { if(is_dir($dir)) { if($handle = opendir($dir)) { while(($file = readdir($handle)) !== false) { if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db) { echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."n"; } } closedir($handle); } } } /* To use: <?php list_files("images/"); ?> */ ?> PHP resources
  • 9. Unzip a Zip File <?php function unzip($location,$newLocation){ if(exec("unzip $location",$arr)){ mkdir($newLocation); for($i = 1;$i< count($arr);$i++){ $file = trim(preg_replace("~inflating: ~","",$arr[$i])); copy($location.'/'.$file,$newLocation.'/'.$file); unlink($location.'/'.$file); } return TRUE; }else{ return FALSE; } } ?> //Use the code as following: <?php include 'functions.php'; if(unzip('zippedfiles/test.zip','unzipped/myNewZip')) echo 'Success!'; else echo 'Error'; ?> PHP resources
  • 10. Crop Image <?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 = '200'; // width $src_h = '200'; // height $dst_x = '0'; // destination x $dst_y = '0'; // destination y $dst_im = imagecreatetruecolor($src_w, $src_h); $white = imagecolorallocate($dst_im, 255, 255, 255); imagefill($dst_im, 0, 0, $white); imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h); header("Content-type: image/png"); imagepng($dst_im); imagedestroy($dst_im); ?> PHP resources
  • 11. Create Zip Files function create_zip($files = array(),$destination = '',$overwrite = false) { //if the zip file already exists and overwrite is false, return false if(file_exists($destination) && !$overwrite) { return false; } //vars $valid_files = array(); //if files were passed in... if(is_array($files)) { //cycle through each file foreach($files as $file) { //make sure the file exists if(file_exists($file)) { $valid_files[] = $file; } } } //if we have good files... if(count($valid_files)) { //create the archive $zip = new ZipArchive(); if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { return false; } //add the files foreach($valid_files as $file) { $zip->addFile($file,$file); } //debug //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status; //close the zip -- done! $zip->close(); //check to make sure the file exists return file_exists($destination); } else { return false; } } /***** Example Usage ***/ $files=array('file1.jpg', 'file2.jpg', 'file3.gif'); create_zip($files, 'myzipfile.zip', true); PHP resources
  • 12. Test whether URL exists function url_exists($url) { $hdrs = @get_headers($url); return is_array($hdrs) ? preg_match('/^HTTP/d+.d+s+2dds+.*$/',$hdrs[0]) : false; } PHP resources
  • 13. For more programming information and code PHP resources Programmers help Programming site PHP resources