php通过网页图片地址将图片保存到本地

返回图片保存路径可选择根据需要保存到数据库

public function savePhoto($url){

    set_time_limit(0);//抓取不受时间限制
    $url=str_replace('&','&',$url);
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; SeaPort/1.2; Windows NT 5.1; SV1; InfoPath.2)");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);

    $values = curl_exec($curl);
    curl_close($curl);

    $fileName = time().rand(5,10).'.jpg';
    $savePath = "/uploads/category/".date('Ymd',time()).'/';
    $path = ROOT_PATH.'public'.$savePath;

    if(!is_dir($path)){
        mkdir($path,'0755',true);
    }
    $fp2 = fopen($path.$fileName,'wb');

    fputs($fp2, $values);
    fclose($fp2);
    return $savePath.$fileName;
}
以下是一个简单的HTML和PHP代码,可以将本地的图片上传到bcrab服务器: ```html <!DOCTYPE html> <html> <head> <title>上传图片到bcrab服务器</title> </head> <body> <h2>上传图片到bcrab服务器</h2> <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">选择图片:</label> <input type="file" name="file" id="file"><br><br> <input type="submit" name="submit" value="上传"> </form> </body> </html> ``` ```php <?php if(isset($_POST["submit"])) { $target_dir = "uploads/"; // 上传文件保存的目录 $target_file = $target_dir . basename($_FILES["file"]["name"]); // 上传的文件路径 $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); // 文件类型 // 检查文件是否为图片格式 if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png" && $imageFileType != "gif") { echo "只允许上传 JPG, JPEG, PNG 和 GIF 格式的图片!"; } // 将文件上传到 bcrab 服务器 $ch = curl_init(); $data = array('file' => new CURLFILE(realpath($target_file))); curl_setopt($ch, CURLOPT_URL, "http://bcrab.com/upload.php"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close ($ch); // 输出上传结果 echo $result; } ?> ``` 注意:上面的代码只是一个简单的示例,需要根据实际情况进行修改和优化。同时,也需要确保 bcrab 服务器支持通过 PHP 的 CURL 扩展上传文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值