php PHP片段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php PHP片段相关的知识,希望对你有一定的参考价值。
//Append Non-Breaking Space Between Last Two Words
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;
}
//Change Date from dd/mm/yyyy to yyyy-dd-mm
$date_array = explode("/",$date); // split the array
$var_day = $date_array[0]; //day seqment
$var_month = $date_array[1]; //month segment
$var_year = $date_array[2]; //year segment
$new_date_format = "$var_year-$var_day-$var_month"; // join them together
<?php
$UploadDirectory = 'uploads/'; //Upload Directory, ends with slash & make sure folder exist
$SuccessRedirect = 'success.html'; //Redirect to a URL after success
// replace with your mysql database details
$MySql_username = "xxx"; //mysql username
$MySql_password = "xxx"; //mysql password
$MySql_hostname = "localhost"; //hostname
$MySql_databasename = 'xxx'; //databasename
if (!@file_exists($UploadDirectory)) {
//destination folder does not exist
die("Make sure Upload directory exist!");
}
if($_POST)
{
if(!isset($_POST['mName']) || strlen($_POST['mName'])<1)
{
//required variables are empty
die("Title is empty!");
}
if($_FILES['mFile']['error'])
{
//File upload error encountered
die(upload_errors($_FILES['mFile']['error']));
}
$FileName = strtolower($_FILES['mFile']['name']); //uploaded file name
$FileTitle = mysql_real_escape_string($_POST['mName']); // file title
$ImageExt = substr($FileName, strrpos($FileName, '.')); //file extension
$FileType = $_FILES['mFile']['type']; //file type
$FileSize = $_FILES['mFile']["size"]; //file size
$RandNumber = rand(0, 9999999999); //Random number to make each filename unique.
$uploaded_date = date("Y-m-d H:i:s");
switch(strtolower($FileType))
{
//allowed file types
case 'image/png': //png file
case 'image/gif': //gif file
case 'image/jpeg': //jpeg file
case 'application/pdf': //PDF file
case 'application/msword': //ms word file
case 'application/vnd.ms-excel': //ms excel file
case 'application/x-zip-compressed': //zip file
case 'text/plain': //text file
case 'text/html': //html file
break;
default:
die('Unsupported File!'); //output error
}
//File Title will be used as new File name
$NewFileName = preg_replace(array('/s/', '/.[.]+/', '/[^w_.-]/'), array('_', '.', ''), strtolower($FileTitle));
$NewFileName = $NewFileName.'_'.$RandNumber.$ImageExt;
//Rename and save uploded file to destination folder.
if(move_uploaded_file($_FILES['mFile']["tmp_name"], $UploadDirectory . $NewFileName ))
{
//connect & insert file record in database
/*
$dbconn = mysql_connect($MySql_hostname, $MySql_username, $MySql_password)or die("Unable to connect to MySQL");
mysql_select_db($MySql_databasename,$dbconn);
@mysql_query("INSERT INTO file_records (file_name, file_title, file_size, uploaded_date) VALUES ('$NewFileName', '$FileTitle',$FileSize,'$uploaded_date')");
mysql_close($dbconn);
*/
header('Location: '.$SuccessRedirect); //redirect user after success
}else{
die('error uploading File!');
}
}
//function outputs upload error messages, http://www.php.net/manual/en/features.file-upload.errors.php#90522
function upload_errors($err_code) {
switch ($err_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>
function _make_url_clickable_cb($matches) {
$ret = '';
$url = $matches[2];
if ( empty($url) )
return $matches[0];
// removed trailing [.,;:] from URL
if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
}
function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;
if ( empty($dest) )
return $matches[0];
// removed trailing [,;:] from URL
if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
}
function _make_email_clickable_cb($matches) {
$email = $matches[2] . '@' . $matches[3];
return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
}
function make_clickable($ret) {
$ret = ' ' . $ret;
// in testing, using arrays here was found to be faster
$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
// this one is not in an array because we need it to run last, for cleanup of accidental links within links
$ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
$ret = trim($ret);
return $ret;
}
$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->evaluate("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
echo $url.'<br />';
}
$meta = get_meta_tags('http://www.emoticode.net/');
$keywords = $meta['keywords'];
// Split keywords
$keywords = explode(',', $keywords );
// Trim them
$keywords = array_map( 'trim', $keywords );
// Remove empty values
$keywords = array_filter( $keywords );
print_r( $keywords );
<?
//When sending emails, you might want to be able to find out if your email has been read.
error_reporting(0);
Header("Content-Type: image/jpeg");
//Get IP
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
//Time
$actual_time = time();
$actual_day = date('Y.m.d', $actual_time);
$actual_day_chart = date('d/m/y', $actual_time);
$actual_hour = date('H:i:s', $actual_time);
//GET Browser
$browser = $_SERVER['HTTP_USER_AGENT'];
//LOG
$myFile = "log.txt";
$fh = fopen($myFile, 'a+');
$stringData = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . "\r\n";
fwrite($fh, $stringData);
fclose($fh);
//Generate Image (Es. dimesion is 1x1)
$newimage = ImageCreate(1,1);
$grigio = ImageColorAllocate($newimage,255,255,255);
ImageJPEG($newimage);
ImageDestroy($newimage);
?>
function combine_my_files($array_files, $destination_dir, $dest_file_name){
//Combine js and css files
if(!is_file($destination_dir . $dest_file_name)){ //continue only if file doesn't exist
$content = "";
foreach ($array_files as $file){ //loop through array list
$content .= file_get_contents($file); //read each file
}
//You can use some sort of minifier here
//minify_my_js($content);
$new_file = fopen($destination_dir . $dest_file_name, "w" ); //open file for writing
fwrite($new_file , $content); //write to destination
fclose($new_file);
return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combined file
}else{
//use stored file
return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combine file
}
}
// a complex array
$myvar = array(
'hello',
42,
array(1,'two'),
'apple'
);
// convert to a string
$string = serialize($myvar);
//or if its json
$string = json_encode($myvar);
// generate unique string
echo uniqid();
/* prints
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* prints
4bd67c9472340
To reduce the chances of getting a duplicate, you can pass a prefix,
or the second parameter to increase entropy*/
echo uniqid('foo_');
/* prints
foo_4bd67d6cd8b8f */
/*
* PHP provides useful magic constants for fetching the current line number (__LINE__),
* file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__),
* class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__)
*/
// this is relative to the loaded script's path
// it may cause problems when running scripts from different directories
require_once('config/database.php');
// this is always relative to this file's path
// no matter where it was included from
require_once(dirname(__FILE__) . '/config/database.php');
my_debug("some debug message", __LINE__);
/* prints
Line 4: some debug message
*/
my_debug("another debug message", __LINE__);
/* prints
Line 11: another debug message
*/
function my_debug($msg, $line) {
echo "Line $line: $msg\n";
}
function ordinal($cdnl){
$test_c = abs($cdnl) % 10;
$ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th'
: (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1)
? 'th' : 'st' : 'nd' : 'rd' : 'th'));
return $cdnl.$ext;
}
for($i=1;$i<100;$i++){
echo ordinal($i).'<br>';
}
/*
Result:
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
*/
function get_client_language($availableLanguages, $default='en'){
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langs as $value){
$choice=substr($value,0,2);
if(in_array($choice, $availableLanguages)){
return $choice;
}
}
}
return $default;
}
/*
Data uri’s can be useful for embedding images into HTML/CSS/JS to save on HTTP requests,
at the cost of maintainability.
You can use online tools to create data uri’s, or you can use the simple PHP function
*/
function data_uri($file, $mime) {
$contents=file_get_contents($file);
$base64=base64_encode($contents);
echo "data:$mime;base64,$base64";
}
$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //save the image on your server
<?php
//Instead of
/*
$username=$_POST["username"];
$age=$_POST["age"];
...
Do
*/
$expected=array('username','age','city','street');
foreach($expected as $key){
if(!empty($_POST[$key])){
${key}=$_POST[$key];
}
else{
${key}=NULL;
}
}
?>
<div class="example-class<?php echo ($xyz++%2); ?>">
function getTweets($hash_tag) {
$url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ;
echo "<p>Connecting to <strong>$url</strong> ...</p>";
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
$xml = curl_exec ($ch);
curl_close ($ch);
//If you want to see the response from Twitter, uncomment this next part out:
//echo "<p>Response:</p>";
//echo "<pre>".htmlspecialchars($xml)."</pre>";
$affected = 0;
$twelement = new SimpleXMLElement($xml);
foreach ($twelement->entry as $entry) {
$text = trim($entry->title);
$author = trim($entry->author->name);
$time = strtotime($entry->published);
$id = $entry->id;
echo "<p>Tweet from ".$author.": <strong>".$text."</strong> <em>Posted ".date('n/j/y g:i a',$time)."</em></p>";
}
return true ;
}
getTweets('#cats');
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
$theta = $longitude1 - $longitude2;
$miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$feet = $miles * 5280;
$yards = $feet / 3;
$kilometers = $miles * 1.609344;
$meters = $kilometers * 1000;
return compact('miles','feet','yards','kilometers','meters');
}
function cleanInput($input) {
$search = array(
'@<script[^>]*?>.*?</script>@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments
);
$output = preg_replace($search, '', $input);
return $output;
}
?>
<?php
function sanitize($input) {
if (is_array($input)) {
foreach($input as $var=>$val) {
$output[$var] = sanitize($val);
}
}
else {
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
}
$input = cleanInput($input);
$output = mysql_real_escape_string($input);
}
return $output;
}
// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars){
$email = "
<p>An error ($number) occurred on line
<strong>$line</strong> and in the <strong>file: $file.</strong>
<p> $message </p>";
$email .= "<pre>" . print_r($vars, 1) . "</pre>";
$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Email the error to someone...
error_log($email, 1, 'you@youremail.com', $headers);
// Make sure that you decide how to respond to errors (on the user's side)
// Either echo an error message, or kill the entire project. Up to you...
// The code below ensures that we only "die" if the error was more than
// just a NOTICE.
if ( ($number !== E_NOTICE) && ($number < 2048) ) {
die("There was an error. Please try again later.");
}
}
// We should use our custom function to handle errors.
set_error_handler('nettuts_error_handler');
// Trigger an error... (var doesn't exist)
echo $somevarthatdoesnotexist;
function whois_query($domain) {
// fix the domain name:
$domain = strtolower(trim($domain));
$domain = preg_replace('/^http:\/\//i', '', $domain);
$domain = preg_replace('/^www\./i', '', $domain);
$domain = explode('/', $domain);
$domain = trim($domain[0]);
// split the TLD from domain name
$_domain = explode('.', $domain);
$lst = count($_domain)-1;
$ext = $_domain[$lst];
// You find resources and lists
// like these on wikipedia:
//
// http://de.wikipedia.org/wiki/Whois
//
$servers = array(
"biz" => "whois.neulevel.biz",
"com" => "whois.internic.net",
"us" => "whois.nic.us",
"coop" => "whois.nic.coop",
"info" => "whois.nic.info",
"name" => "whois.nic.name",
"net" => "whois.internic.net",
"gov" => "whois.nic.gov",
"edu" => "whois.internic.net",
"mil" => "rs.internic.net",
"int" => "whois.iana.org",
"ac" => "whois.nic.ac",
"ae" => "whois.uaenic.ae",
"at" => "whois.ripe.net",
"au" => "whois.aunic.net",
"be" => "whois.dns.be",
"bg" => "whois.ripe.net",
"br" => "whois.registro.br",
"bz" => "whois.belizenic.bz",
"ca" => "whois.cira.ca",
"cc" => "whois.nic.cc",
"ch" => "whois.nic.ch",
"cl" => "whois.nic.cl",
"cn" => "whois.cnnic.net.cn",
"cz" => "whois.nic.cz",
"de" => "whois.nic.de",
"fr" => "whois.nic.fr",
"hu" => "whois.nic.hu",
"ie" => "whois.domainregistry.ie",
"il" => "whois.isoc.org.il",
"in" => "whois.ncst.ernet.in",
"ir" => "whois.nic.ir",
"mc" => "whois.ripe.net",
"to" => "whois.tonic.to",
"tv" => "whois.tv",
"ru" => "whois.ripn.net",
"org" => "whois.pir.org",
"aero" => "whois.information.aero",
"nl" => "whois.domain-registry.nl"
);
if (!isset($servers[$ext])){
die('Error: No matching nic server found!');
}
$nic_server = $servers[$ext];
$output = '';
// connect to whois server:
if ($conn = fsockopen ($nic_server, 43)) {
fputs($conn, $domain."\r\n");
while(!feof($conn)) {
$output .= fgets($conn,128);
}
fclose($conn);
}
else { die('Error: Could not connect to ' . $nic_server . '!'); }
return $output;
}
$compressed = gzcompress($string);
echo "Original size: ". strlen($string)."\n";
/* prints
Original size: 800
*/
echo "Compressed size: ". strlen($compressed)."\n";
/* prints
Compressed size: 418
*/
// getting it back
$original = gzuncompress($compressed);
echo "Initial: ".memory_get_usage()." bytes \n";
/* prints
Initial: 361400 bytes
*/
// let's use up some memory
for ($i = 0; $i < 100000; $i++) {
$array []= md5($i);
}
// let's remove half of the array
for ($i = 0; $i < 100000; $i++) {
unset($array[$i]);
}
echo "Final: ".memory_get_usage()." bytes \n";
/* prints
Final: 885912 bytes
*/
echo "Peak: ".memory_get_peak_usage()." bytes \n";
/* prints
Peak: 13687072 bytes
*/
$i = imagecreatefromjpeg("image.jpg");
for ($x=0;$x<imagesx($i);$x++) {
for ($y=0;$y<imagesy($i);$y++) {
$rgb = imagecolorat($i,$x,$y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> & 0xFF;
$b = $rgb & 0xFF;
$rTotal += $r;
$gTotal += $g;
$bTotal += $b;
$total++;
}
}
$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);
$hostname = 'localhost';
$user = 'username';
$pass = 'password';
$database = 'database_name';
$db_connection = new PDO( "mysql:host=" . $hostname . ";dbname=" . $database, $user, $pass );
$results = $db_connection->query( 'SELECT testimonial, author FROM recommendations WHERE 1 ORDER by rand() LIMIT 1' );
foreach ( $results as $row ) {
echo '<p id="quote">' . $row['testimonial'] . '</p>';
echo '<p id="author">–' . $row['author'] . '</p>';
}
// Close the connection
$db_connection = null;
/*
Imagine that you want to capture some benchmark statistics at the end of your script execution,
such as how long it took to run
You just add the code to the very bottom of the script and it runs before it finishes.
However, if you ever call the exit() function, that code will never run.
Also, if there is a fatal error, or if the script is terminated by the user
(by pressing the Stop button in the browser), again it may not run.
*/
$start_time = microtime(true);
register_shutdown_function('my_shutdown');
// do some stuff
// ...
function my_shutdown() {
global $start_time;
echo "execution took: ".
(microtime(true) - $start_time).
" seconds.";
}
print_r(getrusage());
/* prints
Array
(
[ru_oublock] => 0
[ru_inblock] => 0
[ru_msgsnd] => 2
[ru_msgrcv] => 3
[ru_maxrss] => 12692
[ru_ixrss] => 764
[ru_idrss] => 3864
[ru_minflt] => 94
[ru_majflt] => 0
[ru_nsignals] => 1
[ru_nvcsw] => 67
[ru_nivcsw] => 4
[ru_nswap] => 0
[ru_utime.tv_usec] => 0
[ru_utime.tv_sec] => 0
[ru_stime.tv_usec] => 6269
[ru_stime.tv_sec] => 0
)
*/
/* Explanation
ru_oublock: block output operations
ru_inblock: block input operations
ru_msgsnd: messages sent
ru_msgrcv: messages received
ru_maxrss: maximum resident set size
ru_ixrss: integral shared memory size
ru_idrss: integral unshared data size
ru_minflt: page reclaims
ru_majflt: page faults
ru_nsignals: signals received
ru_nvcsw: voluntary context switches
ru_nivcsw: involuntary context switches
ru_nswap: swaps
ru_utime.tv_usec: user time used (microseconds)
ru_utime.tv_sec: user time used (seconds)
ru_stime.tv_usec: system time used (microseconds)
ru_stime.tv_sec: system time used (seconds)
*/
$files = glob('*.php');
print_r($files);
/* output looks like:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/
// get all php files AND txt files
$files = glob('*.{php,txt}', GLOB_BRACE);
function fb_fan_count($facebook_name){
// Example: https://graph.facebook.com/digimantra
$data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
echo $data->likes;
}
if ($_SERVER['HTTPS'] != "on") {
echo "This is not HTTPS";
}else{
echo "This is HTTPS";
}
$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) . "<br>\n";
}
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();
$curl_opt = array(
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $curlopt_useragent,
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
);
curl_setopt_array($ch, $curl_opt);
$content = curl_exec($ch);
if (!is_null($curl_info)) {
$curl_info = curl_getinfo($ch);
}
curl_close($ch);
if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) ) {
$city = $regs[1];
}
if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) ) {
$state = $regs[1];
}
if( $city!='' && $state!='' ){
$location = $city . ', ' . $state;
return $location;
}else{
return $default;
}
}
// Include the TextMagic PHP lib - Not free!
require('textmagic-sms-api-php/TextMagicAPI.php');
// Set the username and password information
$username = 'myusername';
$password = 'mypassword';
// Create a new instance of TM
$router = new TextMagicAPI(array(
'username' => $username,
'password' => $password
));
// Send a text message to '999-123-4567'
$result = $router->send('Wake up!', array(9991234567), true);
// result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )
// código util que tira {_ do começo e } do final de uma string
$response['class'] = trim($badgeClass['class'], '{_}');
以上是关于php PHP片段的主要内容,如果未能解决你的问题,请参考以下文章