欢迎光临 - 我的站长站,本站所有资源仅供学习与参考,禁止用于商业用途或从事违法行为!

php教程

PHP常用函数大全

php教程 我的站长站 2020-09-05 共109人阅读

PHP随机图片API本地图片版,页面直接输出图片

<?php
$img_array = glob('images/*.{gif,jpg,png,jpeg,webp,bmp}', GLOB_BRACE);
if(count($img_array) == 0) die('没找到图片文件。请先上传一些图片到 '.dirname(__FILE__).'/images/ 文件夹');
header('Content-Type: image/png');
echo(file_get_contents($img_array[array_rand($img_array)]));
?>

将图片保存到images目录下,自动读取images图片并输出。

PHP随机图片API远程图片版,页面直接输出图片

<?php
$imgku=file('pic.txt');
showImg($imgku[array_rand($imgku)]);
/*
* php 页面直接输出图片
*/
function showImg($img){
$img = trim($img);
$info = getimagesize($img);
$imgExt = image_type_to_extension($info[2], false); //获取文件后缀
$fun = "imagecreatefrom{$imgExt}";
$imgInfo = $fun($img);         //1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename )
//$mime = $info['mime'];
$mime = image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型
header('Content-Type:'.$mime);
$quality = 100;
if($imgExt == 'png') $quality = 9;   //输出质量,JPEG格式(0-100),PNG格式(0-9)
$getImgInfo = "image{$imgExt}";
$getImgInfo($imgInfo, null, $quality); //2.将图像输出到浏览器或文件。如: imagepng ( resource $image )
imagedestroy($imgInfo);
}
?>

需安装GD库及exif扩展,php.ini中开启allow_url_fopen函数,读取同目录下pic.txt文件中的图片网址,每行一个图片地址。

Cookie限制时间再次提交

if(isset($_COOKIE['submission_time'])) {
$submissionTime =   $_COOKIE['submission_time'];
$currentTime    =   time();
$timePassed     =   ($currentTime - $submissionTime ) / 60 * 60;
if($timePassed < 24 ) {
echo "<div class='alert alert-warning'>You can record the sales after 24 hours! Please wait..</div>";
die();
}
}else {
$cookieName     =   'submission_time';
$cokkieValue    =   time(); 
setcookie($cookieName, $cokkieValue, time() + (+60*60*24*30 ), "/");
}

判断字符串是否含有某分割符,若包含分割符,分割后输出全部分割后的值

if(strpos($qcont,',') === false){
echo "不包含,分割字段";
}else{
echo "包含,分割字段,下面进行切割并输出";
$qcontArr = explode(",", $qcont);
$qcontcount = count($qcontArr);
for ($i = 0; $i < $qcontcount; $i++) {
if ($qcontArr[$i] == "") {
continue;  
}
echo $qcontArr[$i];
}
}

对错误的详情进行格式化输出,记入log文件。

function slog($logs){
$toppath="log.htm";
$Ts=fopen($toppath,"a+");
fputs($Ts,$logs."rn");
fclose($Ts);
}

使用file_get_contents() 发送GET、post请求

1、【GET请求】

$data = array( 'name'=>'zhezhao','age'=>'23');
$query = http_build_query($data); 
$url = 'http://localhost/get.php';//这里一定要写完整的服务页面地址,否则php程序不会运行 
$result = file_get_contents($url.'?'.$query);

2、【POST请求】

$data = array('user'=>'jiaxiaozi','passwd'=>'123456');
$requestBody = http_build_query($data);
$context = stream_context_create(['http' => ['method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencodedrn"."Content-Length: " . mb_strlen($requestBody), 'content' => $requestBody]]);
$response = file_get_contents('http://server.test.net/login', false, $context);

php获取当天是几号、周几

echo date('y').'</br>';    //当前年份
echo date('m').'</br>';    //当前月份
echo date('d').'</br>';    //当前日
echo date('s').'</br>';    //当前秒
echo date('w').'</br>';    //当前周几

打印结果显示为:

20
07
24
50
5

PHP给第三方接口POST或GET方式传输数据并得到返回值

function Post($url, $post = null)
{
$context = array();
if (is_array($post))
{
ksort($post);
$context['http'] = array
(   
'timeout'=>60,
'method' => 'POST',
'content' => http_build_query($post, '', '&'),
);
}
return file_get_contents($url, false, stream_context_create($context));
}
$data = array
(
'name' => 'test',
'email' => 'test@gmail.com',
'submit' => 'submit',
);
echo Post('http://www.baidu.com', $data);

同一页面24小时之内之只能执行一次

define('TIME_OUT', 86400); //定义重复操作最短的允许时间,单位秒
@session_start();
$time = time();
if( isset($_SESSION['time']) ){
if( $time - $_SESSION['time'] <= TIME_OUT ){
echo '<script type=text/javascript>alert("在24小时内只能执行一次!");</script>';
exit();
}
}
$_SESSION['time'] = $time;
echo "正常执行!";

PHP连接远程MSSQL函数:

已在如上环境安装后测试通过!

function mssql_user($username){
$host="远程服务器IP,MSSQL端口";
$dbname="数据库名称";
$user="数据库用户名";
$pass="数据库密码";
try {
$dbh = new PDO("sqlsrv:Server=$host;Database=$dbname", $user, $pass);
} catch(PDOException $e) {
echo $e->getMessage();
exit;
}
$stmt = $dbh->prepare("SELECT XXX FROM XXX WHERE XXX = ".$username);
$stmt->execute();
while ($row = $stmt->fetch()) {
echo $row[0];//多个查询结果输出
//return $row[0]; 单一的结果可以直接用return
}
unset($dbh); unset($stmt);
}

php时间戳和日期相互转换

获取当前日期时间的时间戳

echo time();

获取当前日期时间

echo date("Y/m/d H:i:s");

日期转换为时间戳

echo strtotime(date("Y/m/d"));

时间戳转换为日期

echo date('Y-m-d',time());

打印明天此时的时间戳

echo strtotime("+1 day");

当前时间:

echo date("Y-m-d H:i:s",time()) ;

指定时间:

echo date("Y-m-d H:i:s",strtotime("+1 day")) ;

下个星期此时的时间戳

echo strtotime("+1 week");

指定下星期几的PHP时间戳

echo strtotime("next Thursday");

指定下星期几的时间:

echo date("Y-m-d H:i:s",strtotime("next Thursday"));

指定上星期几的时间戳

echo strtotime("last Thursday");

指定本年的最后一个星期几的时间:

echo date("Y-m-d H:i:s",strtotime("last Thursday"));

截取指定两个字符之间的字符串

方法一

function cut($begin,$end,$str){
$b = mb_strpos($str,$begin) + mb_strlen($begin);
$e = mb_strpos($str,$end) - $b;
return mb_substr($str,$b,$e);
}

方法二

function get_between($input, $start, $end) {
$substr = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1));
return $substr;
}

方法一当截取的是值为串的时候,会出现截取不到的情况用方法二尝试。

方法三:preg_match_all函数

preg_match_all('/<Epoch>(.*)</Epoch>/', $result, $matches); 
//print_r($matches);
$resultapp = $matches[1][1];

方法一及方法二在截取长段字符串时,碰到过无法截取到的情况,用方法三解决。

调用SOHU API获取IP地址

//通过API获取IP地址
function getIP(){
$str = file_get_contents('https://pv.sohu.com/cityjson?ie=utf-8');
$ip = cut('cip": "','", "cid',$str);
if($ip){
return $ip;
}
}

注:需配合上面 截取指定两个字符之间的字符串 函数一起使用

获取访问客户端的IP地址

function get_client_ip(){
static $realip;
if (isset($_SERVER)){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
$realip = $_SERVER["HTTP_CLIENT_IP"];
} else {
$realip = $_SERVER["REMOTE_ADDR"];
}
} else {
if (getenv("HTTP_X_FORWARDED_FOR")){
$realip = getenv("HTTP_X_FORWARDED_FOR");
} else if (getenv("HTTP_CLIENT_IP")) {
$realip = getenv("HTTP_CLIENT_IP");
} else {
$realip = getenv("REMOTE_ADDR");
}
}
return $realip;
}


标签 PHP函数
相关推荐
  • PHP函数
  • PHP数组转换为JSON格式数据

    PHP数组转换为JSON格式数据,这里介绍下PHP json_encode函数,他可以轻松完成转换。json_encode函数PHP json_encode() 用于对变量进行 JSON 编码,该函数如果执行成功返回 JSON 数据,否则返回 FALSE 。json_encode语法string json_encode ( $value [, $opt...

    php教程 97 3年前
  • 利用get_headers函数判断链接是否有效或失效

    PHP判断链接是否有效或失效的方法代码,get_headers() 是PHP系统级函数,他返回一个包含有服务器响应一个 HTTP 请求所发送的标头的数组。如果失败则返回 FALSE 并发出一条 E_WARNING 级别的错误信息(可用来判断远程文件是否存在)。函数定义array get_he...

    php教程 115 3年前
  • 利用explode() 函数分隔字符

    explode()函数本函数为 implode() 的反函数,使用一个字符串分割另一个字符串,返回一个数组。语法:codearray explode( string separator, string string [, int limit] )参数说明:separator 分割标志 string 需要分割的字符串 limit 可选...

    php教程 74 3年前
  • PHP Array函数教程

    PHP Array函数,主要功能:创建索引数组。PHP Array语法索引数组的语法:array(value1,value2,value3,etc.);关联数组的语法array(key=>value,key=>value,key=>value,etc.);定义和用法array() 函数用于创建数组。在 PHP 中,有三种类型的数组:索引数组 - 带有...

    php教程 57 3年前
  • json_encode函数中文乱码解决方法

    在用到json_encode函数对数据进行json格式转换时,中文会乱码,这里需要用到JSON_UNESCAPED_UNICODE对中文不编码处理。实战案列<?php $arr = array(&#39;11px&#39; => &#39;我的站长站&#39;, &#39;taobao&#39; => &#39;淘宝网&#39;); echo json_enc...

    php教程 49 3年前