SlideShare una empresa de Scribd logo
1 de 13
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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 a PHP code examples

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 a PHP code examples (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
 

Último

Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 

Último (20)

Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 

PHP code examples

  • 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