This may seem like a weird question, but I am trying to get my website to upload files that users input to a folder on my Nextcloud instance. So, that I may share it with others on my team.
I have not been able to find anything about how to do this. I have created a folder and created a share link for it.
The code that I am trying to use to do this is:
$file = $_FILES['fileToUpload'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('pdf', 'docx', 'doc');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 1000000) {
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "https://files.devplateau.com/nextcloud/index.php/s/jfbavtp4q6UWNlR");
curl_setopt($c, CURLOPT_USERPWD, "username:password");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_PUT, true);
//curl_setopt($c, CURLOPT_INFILESIZE, filesize($file));
$fp = fopen($file, "r");
curl_setopt($c, CURLOPT_INFILE, $fp);
curl_exec($c);
curl_close($c);
fclose($fp);
} else {
echo "Your file is too big!";
}
} else {
echo "There was an error uploading your file!";
}
} else {
echo "You cannot upload files of this type!";
}
When trying this though, I get a few errors. They are:
Warning: fopen() expects parameter 1 to be a valid path, array given...
Warning: curl_setopt(): supplied argument is not a valid File-Handle resource...
Warning: fclose() expects parameter 1 to be resource, boolean given...
I understand what the first warning means. I just do not know how to get the array into something that fopen can use. Then I really do not understand what the other warning means.
Can someone help me get this working or see a better way to get this done?
You have to change the url to: remote.php/dav/files/user/path/to/file
Related
I have a bunch of PDFs that were downloaded using a scraper. This scraper didn't check to see if the file was a JPG or a PDF so by default all of them were downloaded and saved with the '.pdf' extension. So, just to clarify all the files in the batch are .pdf. However, if I try to open them(The files that are not PDF but rather JPGs) via a server or locally I'm hit with an error.
My question. Is there a way with PHP to check and see if this file is a valid PDF? I would like to run all the URLs through a loop to check these files. There are hundreds of them and it would take hours upon hours to check.
Thanks
For local files (PHP 5.3+):
$finfo = finfo_open(FILEINFO_MIME_TYPE);
foreach (glob("path/to/files") as $filename) {
if(finfo_file($finfo, $filename) === 'application/pdf') {
echo "'{$filename}' is a PDF" . PHP_EOL;
} else {
echo "'{$filename}' is not a PDF" . PHP_EOL;
}
}
finfo_close($finfo);
For remote files:
$ch = curl_init();
$url = 'http://path.to/your.pdf';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$results = split("\n", trim(curl_exec($ch)));
foreach($results as $line) {
if (strtok($line, ':') == 'Content-Type') {
$parts = explode(":", $line);
echo trim($parts[1]); // output: application/pdf
}
}
Get MIME type of the file using function: finfo_file()
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, "PATH-TO-YOUR-FILE");
finfo_close($finfo);
echo $mimetype;
}
echo "<pre>";
print_r($mimetype);
echo "</pre>";
Use finfo_file() function
<?php
if (function_exists('finfo_open')) {
$mime = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($mime, "FILE-PATH");
if($mime_type == "application/pdf")
echo "file is pdf";
else
echo "file is not pdf";
finfo_close($mime);
}
Sometimes you gotta check a mime signature of a file and sometimes of a variable. These are how you do both checkings:
$filename = '/path/to/my/file.pdf';
$content = file_get_contents($filename);
$file_is_pdf = function(string $filename) : bool {
return mime_content_type($filename) === 'application/pdf';
};
$var_is_pdf = function(string $content) : bool {
$mime_type_found = (new \finfo(FILEINFO_MIME))->buffer($content);
return $mime_type_found === 'application/pdf; charset=binary';
};
// Checks if a file contains a pdf signature.
var_dump($file_is_pdf($filename));
// Checks if a variable contains a pdf signature.
var_dump($var_is_pdf($content));
I have a file, where I read URLs line by line. The URL are links to images. All the image-links work in the browser. Now I want to download them to my current directory. For the record I need to use a PHP-script.
This is how I get my Images:
for ($j; $j< $count;$j++)
{
// Get Image-URL as String and then do getImage
$image = $arr[$j];
$newname = $j;
getImage($image, $newname);
}
function getImage($image, $newname)
{
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$fp = fopen("$newname.jpg",'w');
fwrite($fp, $rawdata);
fclose($fp);
}
But the problem is, I get all the images, only the last one is viewable. The others I can't open and they only have 1KB.
So what did I do wrong?
Plus I need to also download png-Files later on, so can I then just change the $newname.jpg into $newname.png?
Thanks in advance, I really need an answer fast, been sitting here for hours, trying to figure it out.
Why not use stream_copy_to_stream?
function getImage($image, $newname, $fileType = "jpg")
{
$in = fopen($image, "r");
$out = fopen("$newname.$fileType",'w');
stream_copy_to_stream($in, $out);
fclose($in); fclose($out);
}
You can also play with stream_set_read_buffer
stream_set_read_buffer($in, 4096);
Just tested this with our avatar pics.
$data = [
"https://www.gravatar.com/avatar/42eec337b6404f97aedfb4f39d4991f2?s=32&d=identicon&r=PG&f=1",
"https://www.gravatar.com/avatar/2700a034dcbecff07c55d4fef09d110b?s=32&d=identicon&r=PG&f=1",
];
foreach ($data as $i => $image) getImage($image, $i, "png");
Works perfectly.
Debug: Read the remote headers for more info?
$httpresponseheader
var_dump($http_response_header);
or stream_get_meta_data
var_dump(stream_get_meta_data($in), stream_get_meta_data($out));
I wrote a PHP script which simply gets URL for images and tries to download/save them on server.
My problem here is that sometimes the image is not fully loaded and the codes blow only save images partially. I did some research but couldn't figure out if I can add something to it, so it can check whether it is saving the full image or not.
Images sizes and other properties of images are random so I can't check it with those factors unless there is a way that I can get those info before loading them image.
Thank you all.
if ( $leng >= "5" ) {
define('UPLOAD_DIR', dirname(__FILE__) . '/files/');
$length = 512000;
$handle = fopen($url, 'rb');
$filename = UPLOAD_DIR . substr(strrchr($url, '/'), 1);
$write = fopen($filename, 'w');
while (!feof($handle))
{
$buffer = fread($handle, $length);
fwrite($write, $buffer);
}
fclose($handle);
fclose($write);
}else {Echo "failed";}
I think that using cURL is a better solution than using fopen for url. Check this out:
$file = fopen($filename, 'wb'); //Write it as a binary file - like image
$c = curl_init($url);
curl_setopt($c, CURLOPT_FILE, $file);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); //Allow cURL to follow redirects (but take note that this does not work with safemode enabled)
curl_exec($c);
$httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE); //200 means OK, you may check it later, just for sure
curl_close($c);
fclose($file);
Partially based on Downloading a large file using curl
i have this upload form and i want to resize image when uploaded
its upload form from url i did it from file upload but cant for url upload
can anyone help me?
<?php
if($_POST["sub"]){
$url = trim($_POST["url"]);
if($url){
$file = fopen($url,"rb");
if($file){
$directory = "../images/news/";
$valid_exts = array("jpg","jpeg","gif","png");
$ext = substr(basename($url), strrpos(basename($url), '.'));
$ext = str_replace('.','',$ext);
if(in_array($ext,$valid_exts)){
$rand = rand(0,9999999999);
$filename = $rand.'.'.$ext;
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo ''."";
echo ''.$filename.'';
} else { echo 'Could not establish new file ('.$directory.$filename.') on local server. Be sure to CHMOD your directory to 777.'; }
} else { echo 'Invalid file type. Please try another file.'; }
} else { echo 'Could not locate the file: '.$url.''; }
} else { echo 'Invalid URL entered. Please try again.'; }
}
?>
Use GD or Image Magic library to resize image:
http://php.net/manual/en/imagick.resizeimage.php
http://php.net/manual/en/function.imagecopyresized.php
For saving the file from URL:
If you have allow_url_fopen set to true:
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
Else use cURL:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
This is the same as the answer in this post...
<?php
$source = 'http://www.xxx.com/1.jpg';
$fileBody = date('YmdHis') . rand(1000, 9999);
$extension = pathinfo($source, PATHINFO_EXTENSION);
$fileName = $fileBody . '.' . $extension;
$ch = curl_init($source);
$fp = fopen($path . $fileName, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
clearstatcache();
return $fileName;
This is how I grab image from internet, the image saved successfully and I will return file name for ajax to make immediately thumbnail, but sometimes php return the $fileName when it still processing download, therefore JavaScript reveal empty image on the page, how response after the file indeed been download.
curl_exec returns true on success and false on failure. Use that information.
Also, You can check curl_getinfo to make sure the transfer completed successfully and was not empty. (You get http_code there for example, as well as content_type and size_download).
$downComplete = false;
while(!$downComplete)
{
if(!file_exist($filePath))
{
sleep(1);
}
else
{
$downComplete = true;
break;
}
}
Hi,Above is an idea for check if file is completely downloaded,i think it's useful,
main idea is check saved file all the time until its finished download,then you can
display the img to front end..you can add it after your curl code,i didn't run it
myself,so just an idea..