Php常用的http方法

1 篇文章 0 订阅

分别是下载文件、下载文本、服务器检测的php http方法

<?php
/**
 * Created by PhpStorm.
 * User: yonh
 * Date: 16-11-10
 * Time: 上午9:24
 *
 * version 1.0.2
 */

namespace Niaoyun\UpgradeEngine;


class Net
{
	public function downloadFile($url, $filename) {
		set_time_limit(0);
		$fp = fopen($filename, 'wb');
		$options = array(
			CURLOPT_FILE    => $fp,
			CURLOPT_TIMEOUT =>  3600,
			CURLOPT_URL     => $url,
		);

		$ch = curl_init();
		curl_setopt_array($ch, $options);
		curl_exec($ch);
		fclose($fp);
		curl_close($ch);
	}

	/**
	 *
	 * @param $url
	 *
	 * @return mixed
	 * @throws \Exception
	 */
	function downloadText($url)
	{
		set_time_limit(60);
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);


		$result = curl_exec($ch);

		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		if ($httpCode !== 200 || false === $result) {
			$err = curl_error($ch);
			curl_close($ch);
			throw new \Exception('网络异常:' . $err);
		}

		curl_close($ch);
		return $result;
	}

	/**
	 * 简单实现检测服务器检测
	 * @return bool true 正常
	 */
	public function test($url)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_TIMEOUT, 3);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_exec($ch);

		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		if ($httpCode === 200) {
			return true;
		} else {
			$err = curl_error($ch);
			return $err;
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值