原文来自http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/ 1.不要使用相对路径 常常会看到: require_once('../../lib/some_class.php'); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录. 因此会检查过多路径.
原文来自http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/
1.不要使用相对路径require_once('../../lib/some_class.php');view sourceprint?
define('ROOT' , '/var/www/project/');
require_once(ROOT . '../../lib/some_class.php');
//rest of the code
我们定义了一个绝对路径, 值被写死了. 我们还可以改进它. 路径 /var/www/project 也可能会改变, 那么我们每次都要改变它吗? 不是的, 我们可以使用__FILE__常量, 如:
用 php + mysql 驱动的在线商城系统,我们的目标为中国的中小企业及个人提供最简洁,最安全,最高效的在线商城解决方案,使用了自建的会员积分折扣功能,不同的会员组有不同的折扣,让您的商店吸引更多的后续客户。 系统自动加分处理功能,自动处理会员等级,免去人工处理的工作量,让您的商店运作起来更方便省事 采用了自建的直接模板技术,免去了模板解析时间,提高了代码利用效率 独立开发的购物车系统,使用最
0
//suppose your script is /var/www/project/index.php
//Then __FILE__ will always have that full path.
define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
require_once(ROOT . '../../lib/some_class.php');
//rest of the coderequire_once('lib/Database.php');
require_once('lib/Mail.php');
require_once('helpers/utitlity_functions.php');function load_class($class_name)
{
//path to the class file
$path = ROOT . '/lib/' . $class_name . '.php');
require_once( $path );
}
load_class('Database');
load_class('Mail');function load_class($class_name)
{
//path to the class file
$path = ROOT . '/lib/' . $class_name . '.php');
if(file_exists($path))
{
require_once( $path );
}
}define('ENVIRONMENT' , 'development');
if(! $db->query( $query )
{
if(ENVIRONMENT == 'development')
{
echo "$query failed";
}
else
{
echo "Database error. Please contact administrator";
}
}define('ENVIRONMENT' , 'production');
if(! $db->query( $query )
{
if(ENVIRONMENT == 'development')
{
echo "$query failed";
}
else
{
echo "Database error. Please contact administrator";
}
}/**
Method to execute a command in the terminal
Uses :
1. system
2. passthru
3. exec
4. shell_exec
*/
function terminal($command)
{
//system
if(function_exists('system'))
{
ob_start();
system($command , $return_var);
$output = ob_get_contents();
ob_end_clean();
}
//passthru
else if(function_exists('passthru'))
{
ob_start();
passthru($command , $return_var);
$output = ob_get_contents();
ob_end_clean();
}
//exec
else if(function_exists('exec'))
{
exec($command , $output , $return_var);
$output = implode("\n" , $output);
}
//shell_exec
else if(function_exists('shell_exec'))
{
$output = shell_exec($command) ;
}
else
{
$output = 'Command execution not possible on this system';
$return_var = 1;
}
return array('output' => $output , 'status' => $return_var);
}
terminal('ls');function add_to_cart($item_id , $qty)
{
$_SESSION['cart']['item_id'] = $qty;
}
add_to_cart( 'IPHONE3' , 2 );function add_to_cart($item_id , $qty)
{
if(!is_array($item_id))
{
$_SESSION['cart']['item_id'] = $qty;
}
else
{
foreach($item_id as $i_id => $qty)
{
$_SESSION['cart']['i_id'] = $qty;
}
}
}
add_to_cart( 'IPHONE3' , 2 );
add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );<?php echo "Hello"; //Now dont close this tag
<?php
class super_class
{
function super_function()
{
//super code
}
}
?>
//super extra character after the closing tag
index.phprequire_once('super_class.php');
//echo an image or pdf , or set the cookies or session data<?php
class super_class
{
function super_function()
{
//super code
}
}
//No closing tagfunction print_header()
{
echo "<div id='header'>Site Log and Login links</div>";
}
function print_footer()
{
echo "<div id='footer'>Site was made by me</div>";
}
print_header();
for($i = 0 ; $i < 100; $i++)
{
echo "I is : $i ';
}
print_footer();function print_header()
{
$o = "<div id='header'>Site Log and Login links</div>";
return $o;
}
function print_footer()
{
$o = "<div id='footer'>Site was made by me</div>";
return $o;
}
echo print_header();
for($i = 0 ; $i < 100; $i++)
{
echo "I is : $i ';
}
echo print_footer();$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'; $xml = "<response> <code>0</code> </response>"; //Send xml data echo $xml;
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
$xml = "<response>
<code>0</code>
</response>";
//Send xml data
header("content-type: text/xml");
echo $xml;JavaScript
header("content-type: application/x-javascript");
echo "var a = 10";
CSS
header("content-type: text/css");
echo "#div id { background:#000; }";//Attempt to connect to database
$c = mysqli_connect($this->host , $this->username, $this->password);
//Check connection validity
if (!$c)
{
die ("Could not connect to the database host: ". mysqli_connect_error());
}
//Set the character set of the connection
if(!mysqli_set_charset ( $c , 'UTF8' ))
{
die('mysqli_set_charset() failed');
}$value = htmlentities($this->value , ENT_QUOTES , CHARSET);
$images = array(
'myself.png' , 'friends.png' , 'colleagues.png'
);
$js_code = '';
foreach($images as $image)
{
$js_code .= "'$image' ,";
}
$js_code = 'var images = [' . $js_code . ']; ';
echo $js_code;
//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];$images = array( 'myself.png' , 'friends.png' , 'colleagues.png' ); $js_code = 'var images = ' . json_encode($images); echo $js_code; //Output is : var images = ["myself.png","friends.png","colleagues.png"]
$contents = "All the content"; $file_path = "/var/www/project/content.txt"; file_put_contents($file_path , $contents);
$contents = "All the content";
$dir = '/var/www/project';
$file_path = $dir . "/content.txt";
if(is_writable($dir))
{
file_put_contents($file_path , $contents);
}
else
{
die("Directory $dir is not writable, or does not exist. Please check");
}
// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);
// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);if($_POST['submit'] == 'Save')
{
//Save the things
}if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )
{
//Save the things
}//Delay for some time
function delay()
{
$sync_delay = get_option('sync_delay');
echo "Delaying for $sync_delay seconds...";
sleep($sync_delay);
echo "Done ";
}//Delay for some time
function delay()
{
static $sync_delay = null;
if($sync_delay == null)
{
$sync_delay = get_option('sync_delay');
}
echo "Delaying for $sync_delay seconds...";
sleep($sync_delay);
echo "Done ";
}$_SESSION['username'] = $username; $username = $_SESSION['username'];
define('APP_ID' , 'abc_corp_ecommerce');
//Function to get a session variable
function session_get($key)
{
$k = APP_ID . '.' . $key;
if(isset($_SESSION[$k]))
{
return $_SESSION[$k];
}
return false;
}
//Function set the session variable
function session_set($key , $value)
{
$k = APP_ID . '.' . $key;
$_SESSION[$k] = $value;
return true;
}function utility_a()
{
//This function does a utility thing like string processing
}
function utility_b()
{
//This function does nother utility thing like database processing
}
function utility_c()
{
//This function is ...
}class Utility
{
public static function utility_a()
{
}
public static function utility_b()
{
}
public static function utility_c()
{
}
}//and call them as $a = Utility::utility_a(); $b = Utility::utility_b();
if($a == true)
{
$a_count++;
}foreach($arr as $c => $v)
{
$arr[$c] = trim($v);
}$amount = intval( $_GET['amount'] ); $rate = (int) $_GET['rate'];
$db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB $cc = $db_records_in_array_format; //2MB more some_function($cc); //Another 2MB ?
$a = get_large_array(); pass_to_function(&$a);
class A
{
function first()
{
$this->a = get_large_array();
$this->pass_to_function();
}
function pass_to_function()
{
//process $this->a
}
}function add_to_cart()
{
$db = new Database();
$db->query("INSERT INTO cart .....");
}
function empty_cart()
{
$db = new Database();
$db->query("DELETE FROM cart .....");
}$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";
$db->query($query); //call to mysqli_query()function insert_record($table_name , $data)
{
foreach($data as $key => $value)
{
//mysqli_real_escape_string
$data[$key] = $db->mres($value);
}
$fields = implode(',' , array_keys($data));
$values = "'" . implode("','" , array_values($data)) . "'";
//Final query
$query = "INSERT INTO {$table}($fields) VALUES($values)";
return $db->query($query);
}
$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);
insert_record('users' , $data);<head> <base href="http://www.domain.com/store/"> </head> <body> @@##@@ </body> </html>
<a href="../home.php">Home</a> <a href="ipad.php">Ipad</a>
<head> <base href="http://www.domain.com/store/"> </head> <body> <a href="home.php">Home</a> <a href="products/ipad.php">Ipad</a> </body> </html>
ini_set('display_errors', 1);
error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);$ php -a
Interactive shell
php > echo strtotime("0000-00-00 00:00:00");
-62170005200
php > echo strtotime('1000-01-30');
-30607739600
php > echo strtotime('2100-01-30');
4104930600set_time_limit(30); //Rest of the code
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号