Download files directly to my server - http

Is there a way to download files directly to my web host? Let's say I want to download a video file from a site and upload it in to my website again. Instead of downloading it to my PC and uploading, Is there a way to do that easily?
Thank you!

I'm using this script now :)
`
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'downloads/';
$url = $_POST['url'];
$name = $_POST['name'];
$ext = $_POST['extention'];
$newfname = $destination_folder . $name . '.' . $ext;
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
echo 'File saved as '. $newfname
?>`

Related

mPDF failed to open stream: operation failed

mPDF stopping working for me, pdfs generated from php are now blank, when I turn on debug I get the following error message.
Error detected. PDF file generation aborted: file_get_contents(https://www.myurl.com/pdf.php): failed to open stream: operation failed
When I go directly to the php page it appears fine.
Here is the code I'm using, I changed permissions to 777 on the file and the folder and it still doesn't work yet if I change the url to an external one it works perfectly. So I'm guessing something on my server is blocking it.
require __DIR__ . '/vendor/autoload.php';
$invoice_id = $_GET['invoice_id'];
$url="https://www.myurl.com/pdf.php";
if (ini_get('allow_url_fopen')) {
$html = file_get_contents($url);
} else {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , 1 );
$html = curl_exec($ch);
curl_close($ch);
}
try
{
$mpdf = new \Mpdf\Mpdf();
$mpdf->debug = true;
$mpdf->SetDisplayMode('fullwidth');
$mpdf->CSSselectMedia='mpdf'; // assuming you used this in the document header
$mpdf->setBasePath($url);
$mpdf->WriteHTML($html);
$mpdf->Output('invoice'.$invoice_id.'.pdf','D');
} catch (\Mpdf\MpdfException $e) { // Note: safer fully qualified exception
echo $e->getMessage();
}

How to download a ZIP file into the wp-plugins folder programmatically?

I am creating a WordPress plugin which should download a ZIP file from a remote location and place it into the wp-plugins folder.
So I created a method which downloads the file using Curl (this works fine) and should then place the file into the wp-plugins folder. I am using the WP_Filesystem in order to make sure I have the rights to place a file on the server. This is what I have until now:
public function download_plugin($url, $path)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
global $wp_filesystem;
if(defined('FS_CHMOD_FILE'))
{
$chmod = FS_CHMOD_FILE;
}
else
{
$chmod = 0755;
}
if (empty($wp_filesystem))
{
require_once (ABSPATH . '/wp-admin/includes/file.php');
WP_Filesystem();
}
if(!$wp_filesystem->put_contents(
$path,
$data,
$chmod
))
else
{
return new \WP_Error('writing_error', 'Error when writing file');
}
}
When I run the method no file is being created on the server. The $path variable however has the right path and the $data variable does contain the ZIP file as a string. The WordPress method put_contents however does nothing. It returns null even when I change the method's parameter to something that should definitely work like $wp_filesystem->put_contents(WP_PLUGIN_DIR.'example.txt','Some text',FS_CHMOD_FILE));.
Is there anything I am doing wrong? It's really difficult to debug since I don't get any errors and put_contents always returns null.

PHPExecel file is empty when send as in attachment

An excel file is created using phpexcel which is saved in the folder with all the data. The same file cannot be send as an attachment in the mail. I would also like to upload the excel in the form in order to make changes.
Please advice. Here is the code.
<?php
//include PHPExcel library
require_once "Classes/PHPExcel.php";
require_once "Classes/PHPExcel/IOFactory.php";
if (!empty($_POST['submit'])) {
//give a filename
$dtime = date('Y-m-d H-i-s');
$dtimeFile = date('Y-m-d-H-i-s');
date_default_timezone_set('Asia/Singapore');
$filename = 'myexcel'.$dtimeFile.'.xls';
$path = __DIR__;
//set headers to download file
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='.$filename);
// create new PHPExcel object
$objTpl = new PHPExcel;
// set default font
$objTpl->getDefaultStyle()->getFont()->setName('Calibri');
// set default font size
$objTpl->getDefaultStyle()->getFont()->setSize(8);
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, "Excel5");
// writer already created the first sheet for us, let's get it
$objSheet = $objTpl->getActiveSheet();
// rename the sheet
$objSheet->setTitle('My Personal Details');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A1:C1')->getFont()->setBold(true)->setSize(12);
$objSheet->getStyle('A2:C2')->getFont()->setSize(12);
// write header
$objSheet->getCell('A1')->setValue('Name');
$objSheet->getCell('B1')->setValue('Email');
$objSheet->getCell('C1')->setValue('Location');
// we could get this data from database, but for simplicty, let's just write it
$objSheet->getCell('A2')->setValue(stripslashes($_POST['name']));
$objSheet->getCell('B2')->setValue(stripslashes($_POST['email']));
$objSheet->getCell('C2')->setValue(stripslashes($_POST['location']));
// // autosize the columns
// $objSheet->getColumnDimension('A')->setAutoSize(true);
// $objSheet->getColumnDimension('B')->setAutoSize(true);
// $objSheet->getColumnDimension('C')->setAutoSize(true);
// $objSheet->getColumnDimension('D')->setAutoSize(true);
$objWriter->save('php://output');
$to = "cloudinnovates#hotmail.com";
$subject = $filename;
$from = "shabs0#hotmail.com";
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"1a2a3a\"";
$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"
."--1a2a3a\r\n";
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
."Attached is the file number \"".$filename."\"\r\n\r\n"
."--1a2a3a\r\n";
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$message .= "Content-Type: application/vnd.ms-excel; name=\"".$filename."\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
."\r\n"
.chunk_split(base64_encode($content))
."--1a2a3a--";
// Send email
//
$success = mail($to, $subject, $message, $headers);
if (!$success) {
echo "Mail to ".$to." failed .";
} else {
echo "Success : Mail was send to ".$to;
}
}
//*************** upload file ***************//
if (!empty($_POST['btn-upload'])) {
$file = 'file';
$Reader = PHPExcel_IOFactory::createReaderForFile($file);
$Reader->setReadDataOnly(true);// set this, to not read all excel properties, just data
$objXLS = $Reader->load($file);
$value = $objXLS->getSheet(0)->getCell('A1')->getValue();
$objXLS->disconnectWorksheets();
unset($objXLS);
}
?>
I'm not familiar with PHP Excel and have not worked with PHP for a long time, but something stands out to me in your code.
You initialize a variable for the file name
$filename = 'myexcel'.$dtimeFile.'.xls';
and attempt to read the content of the file like this
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
But you don't appear to actually save your Excel sheet to that file. Rather, you seem to write it to the output stream of the current PHP page.
$objWriter->save('php://output');
Setting the content-disposition header
header('Content-Disposition: attachment;filename='.$filename);
tells the browser opening this PHP page what to do with the data returned by the PHP page, but does not save the file to your local server, so that it can be attached to an email on that server.
You will need to save the Excel file to a location on your local server before it is attached to the email.

Symfony2 PHPWord response

I am trying to generate a docx document on Symfony2, using the PHPWord bundle.
In my controller, I succeed in returning a docx file, but it is empty, I think it comes from my faulty response format.
public function indexAction($id)
{
$PHPWord = new PHPWord();
$section = $PHPWord->addSection();
$section->addText(htmlspecialchars(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
));
// Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
return new Response($objWriter->save('helloWorld.docx'), 200, array('Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'));
}
Try this class
<?php
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Settings;
use Symfony\Component\HttpFoundation\Response;
class WordResponse extends Response
{
/**
* WordResponse constructor.
* #param string $name The name of the word file
* #param PhpWord $word
*/
public function __construct($name, &$word)
{
parent::__construct();
// Set default zip library.
if( !class_exists('ZipArchive')){
Settings::setZipClass(Settings::PCLZIP);
}
$writer = IOFactory::createWriter($word, 'Word2007');
//Set headers.
$this->headers->set("Content-Disposition", 'attachment; filename="' . $name . '"');
$this->headers->set("Content-Type", 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$this->headers->set("Content-Transfer-Encoding", 'binary');
$this->headers->set("Cache-Control", 'must-revalidate, post-check=0, pre-check=0');
$this->headers->set("Expires", '0');
$this->sendHeaders();
$writer->save('php://output');
}
}
Then in your controller do:
return new WordResponse($phpWord, "filename.docx");
Thanks a lot for your answer.
I achieve using the 2nd method, which is in my opinion the best.
I just have to return a response, otherwise the file was generated, but stuck in the web directory.
Using this response, everything was fine and a download prompt appeared, with the "full" file.
Here's my code :
$PHPWord = new PHPWord();
$section = $PHPWord->addSection();
$section->addText(htmlspecialchars(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
));
// Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$filename="MyAwesomeFile.docx";
$objWriter->save($filename, 'Word2007', true);
$path = $this->get('kernel')->getRootDir(). "/../web/" . $filename;
$content = file_get_contents($path);
$response = new Response();
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);
$response->setContent($content);
return $response;
PHPWord->save() returns a true value so that would be why your file is not being downloaded. With your return new Response() you are setting the content of your response to true (the result of your save call) which is why your response is empty.
You have 2 (and probably more that I haven't thought of) options to generate and download this file..
1. Save your file to a temp folder and server from there
$filename = sprintf(
'%s%sDoc-Storage%s%s.%s',
sys_get_temp_dir(),
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR,
uniqid(),
'docx'
);
$objWriter->save($filename);
$response = new BinaryFileResponse($filename);
For more info on the BinaryFileResponse see the docs.
2. Ignore Symfony and serve directly via the PHPWord action
$objWriter->save($filename, 'Word2007', true);
exit();
The ->save method provides all of the actions to download the generated file internally (see the code) so all you need to do is set the format and the third parameter to true and it will handle all of the headers for you. Granted it won't be returning a Symfony response but you will be exiting out before you get to that exception.

Client for Google API PHP Client and nested requires?

I'm trying to implement Google analytics api in a wordpress dashboard plugin.
Following the simplest implementation for using the Google API for PHP for the first time, its not working right away at practically the first step.
According to the tutorial README.md, my app, placed ajacent to the library folder, should load the library like so:
require_once 'Google/Client.php';
require_once 'Google/Service/Books.php';
$client = new Google_Client();
Now, the structure of the library within my app (plugin) is:
myapp.php
/Google
/Google/Client.php
/Google/otherfolders/otherfiles.php
and my app attempts to load the library per the require_once above. But of course the Client.php has many require_once calls itself such as:
require_once 'Google/Auth/AssertionCredentials.php';
Which seem to ignore its position -- already within /Google.
So I'm getting errors:
PHP Warning: require_once(Google/Auth/AssertionCredentials.php) [<a href='function.require-once'>function.require-once</a>]: failed to open stream: No such file or directory in <wpengine host path removed>/wp-content/plugins/mmstats/Google/Client.php on line 18
and
PHP Fatal error: require_once() [<a href='function.require'>function.require</a>]: Failed opening required 'Google/Auth/AssertionCredentials.php' (include_path='.:/usr/share/php:/usr/share/pear') in <wpengine host path removed>/wp-content/plugins/mmstats/Google/Client.php on line 18
This PHP is listed as "Beta" but surely I'm doing something wrong rather than this being a problem with Client.php
Any help appreciated!
The Google Director needs to be in the same directory as your file. If its not your going to have to edit all the required_once's yourself. Here is some working code for use with the Google Analytics API.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
You can find a tutorial for this code at Google Oauth2 PHP, there is a little test app at the bottom where you can see it working.

Resources