简体   繁体   English

php如何从url下载文件并保存到服务器

[英]php how download file from url and save it on server

my link (URL) is different!!!我的链接 (URL) 不同!!! and does not work with usual method I think because site load with js or aspx you can test my link (URL) in your browser and see download starting but cant work in php并且不适用于通常的方法我认为因为网站加载 js 或 aspx 你可以在你的浏览器中测试我的链接(URL)并看到下载开始但不能在 php 中工作

I have tested all methods (fetch, curl, file, get, put), but it does not work.我已经测试了所有方法(fetch、curl、file、get、put),但它不起作用。 I have a similar URL here: 'http://www.tsetmc.com/tsev2/data/ClientTypeAll.aspx?h=0&r=0'我这里有一个类似的 URL:'http://www.tsetmc.com/tsev2/data/ClientTypeAll.aspx?h=0&r=0'

I can open it in the browser and download a csv file I need to do this in php and save the csv file on server我可以在浏览器中打开它并下载一个 csv 文件我需要在 php 中执行此操作并将 csv 文件保存在服务器上

Here is what I have tried so far:到目前为止,这是我尝试过的:

<?php

$file = fopen('http://www.tsetmc.com/tsev2/data/ClientTypeAll.aspx?h=0&r=0');
$file = file_get_contents('http://www.tsetmc.com/tsev2/data/ClientTypeAll.aspx?h=0&r=0');
file_put_contents('ClientTypeAll.csv', $file);

?>

I do not want Contents !!!我不要内容!!! I want a csv file form my link if you test my link in your browser download start in your pc如果你在浏览器中测试我的链接,我想要一个 csv 文件从你的电脑开始下载

I run this code with a remote PDF file.我使用远程 PDF 文件运行此代码。

<?php
$url = 'https://example.com/file.pdf';
$dir_name = 'storage-x'; // saVe the directory name

if (!file_exists($dir_name)) {
    mkdir($dir_name, 0777, true);
}
$path = $dir_name.'/'.rand().'.pdf';
$file = file_get_contents($url);
file_put_contents($path, $file);

?>

Please follow the below step.请按照以下步骤操作。

  • Get file form URL.获取文件表格 URL。
  • Set directory and check file exit condition and update directory access permission.设置目录并检查文件退出条件并更新目录访问权限。
  • Set new file path, name, and directory.设置新的文件路径、名称和目录。
  • Save the file.保存文件。

Please check the below example which works for me.请检查以下对我有用的示例。

<?php
     $file = file_get_contents('https://example.com/file.pdf');
     
     $dirName = 'storage-pdf';

     if (!file_exists($dirName)) {
         mkdir($dirName, 0777, true);
     }

     $newFilePath = $dirName.'/'.rand().'.pdf';
     
     file_put_contents($newFilePath, $file);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM