Getting the real URL of files uploaded in Moodle - php

I am trying to get the url to a file that I have uploaded to moodle. I want to access the file via the browser using http. The pathname of the file is hashed in the moodle database. Is there a way of getting the real url of uploaded files in moodle? this is the code I was trying out using the Moodle File API.
<?php
require_once("../config.php");
$course_name=$_GET["course"];
$table_files="files";
$results=$DB->get_records($table_files,array('filename'=>$course_name));
//Get the file details here::::
foreach($results as $obj){
$contextid=$obj->contextid;
$component=$obj->component;
$filearea=$obj->filearea;
$itemid=$obj->itemid;
}
$url=$CFG->wwwroot/pluginfile.php/$contextid/$component/$filearea/$itemid/$course_name;
echo print_r($url);
?>
Will appreciate the help.

This works for Moodle version 2.3
<?php
require_once("../config.php");
$filename = "my_image.jpg";
$table_files = "files";
$results = $DB->get_record($table_files, array('filename' => $filename, 'sortorder' => 1));
$baseurl = "$CFG->wwwroot/pluginfile.php/$results->contextid/$results->component/$results->filearea/$results->itemid/$filename";
echo $baseurl;
The result is the Url to the image "my_image.jpg"

Related

Azure File Storage using PHP

I want to run a single webpage to display files, which are stored in an Azure File Storage. It must be Azure File storage because these files came from a Docker container, which is mounted, to that file storage.
I have a Azure Container Instance witch stores PDF files in an Azure File Storage. Now I run a WebApp (PHP) that shall read all the PDFs.
I’ve installed the Microsoft Azure Storage File PHP SDK but have no clue how to use it. Even the sample.php did not help me coming forward. It would be very helpful if someone could help me a bit a simple sniped.
I see you want to directly display a PDF file from Azure File Storage in a web page. Generally, the best practice is to generate the url with sas token of a file in Azure File Storage.
So I followed the GitHub repo Azure/azure-storage-php to install Azure File Storage SDK for PHP in my sample project, here is my sample code and its dependencies.
The file structure of my sample project is as the figure below.
The content of my composer.json file is as below.
{
"require": {
"microsoft/azure-storage-file": "*"
}
}
My sample PHP file demo.php is as below, that's inspired by the function generateFileDownloadLinkWithSAS of the offical sample azure-storage-php/samples/FileSamples.php.
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\File\FileSharedAccessSignatureHelper;
$accountName = "<your account name>";
$accountKey = "<your account key>";
$shareName = "<your share name>";
$fileName = "<your pdf file name>";
$now = date(DATE_ISO8601);
$date = date_create($now);
date_add($date, date_interval_create_from_date_string("1 hour"));
$expiry = str_replace("+0000", "Z", date_format($date, DATE_ISO8601));
$helper = new FileSharedAccessSignatureHelper($accountName, $accountKey);
$sas = $helper->generateFileServiceSharedAccessSignatureToken(
Resources::RESOURCE_TYPE_FILE,
"$shareName/$fileName",
'r', // Read
$expiry // A valid ISO 8601 format expiry time, such as '2020-01-01T08:30:00Z'
);
$fileUrlWithSAS = "https://$accountName.file.core.windows.net/$shareName/$fileName?$sas";
echo "<h1>Demo to display PDF from Azure File Storage</h1>";
echo "<iframe src='$fileUrlWithSAS' width='800' height='500' allowfullscreen webkitallowfullscreen></iframe>";
?>
The result of my web page is as the figures below in Chrome and Firefox.
The result in Chrome:
The result in Firefox:
Update: The code to list files in a file share, as below.
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\File\FileRestProxy;
$accountName = "<your account name>";
$accountKey = "<your account key>";
$shareName = "<your share name>";
$connectionString = "DefaultEndpointsProtocol=https;AccountName=$accountName;AccountKey=$accountKey";
$fileClient = FileRestProxy::createFileService($connectionString);
$list = $fileClient->listDirectoriesAndFiles($shareName);
function endsWith( $str, $sub ) {
return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}
foreach($list->getFiles() as &$file) {
$fileName = $file->getName();
if(endsWith($fileName, ".pdf")) {
echo $fileName."\n";
}
};
?>

downloaded file cannot open(damage) codeigniter

i have a file with extension PDF and DOCX, and when i download it from my server, the file cannot opened and the size become 1kb, when in my server folder it has 199kb size. iam using database to store the file path and filename, here is my view to download the file
View
<?php echo $details->FILE_NAME; ?>
and my controller
Admin_Controls.php
function download_proposal($id_pemesanan) {
$this->load->helper('download');
$this->load->model('gedung/gedung_model');
$temp_id = substr($id_pemesanan, 7); //i cut the string because it content prefix string
$data = $this->gedung_model->get_proposal_by_id($temp_id);
$path = file_get_contents($data->PATH.$data->FILE_NAME);
$file_name = $data->FILE_NAME;
force_download($file_name, $data);
}
my model
Gedung_Model.php
public function get_proposal_by_id($id_pemesanan) {
$sql = "SELECT * FROM pemesanan_details WHERE ID_PEMESANAN = $id_pemesanan";
$query = $this->db->query($sql);
$hasil = $query->row();
return $hasil;
}
my problem is just after i download the file, it becomes corrupted and cannot open, like i say the size become 1kb. all works well from user click to download until the download process
Thanks in advice
I would like to check the path . You can use absolute path of the file for testing purpose instead of dynamic generated path .

Downloading uploaded file php

I'm new to yii framework and we have a project in school about uploading and downloading files and I kind of need some assistance...
I followed this link as a sample exactly as it is and it really does upload to the uploads folder in yii but now I'm trying to download it using this code in my view:
$id= $_GET['id'];
$media = Document::model()->findByPk($id);
$path = Yii::app()->basePath . '/../uploads';
$name = $media->doc_file;
Yii::app()->request->sendFile($name, file_get_contents($path."/".$name));
but when it downloads, it wont open because the file format is not supported... any idea how I can
I did a little modification on your code. Pass the id through the url on the view and that will hit the download action inside your controller. You should be good to go with this
public function actionDownload($id)
{
$media = Document::model()->findByPk($id);
$path = Yii::app()->request->baseURL . '/uploads';
$file = $path . '/'.$media->doc_file;
if (file_exists($file)) {
return Yii::app()->getRequest()->sendFile($name, #file_get_contents($path));
}else{
//throw an error here
}
}

PHP Foreach and jQuery

I am working on a piece of code that I am wanting to "spice" up with jQuery but I can't think of a way to actually make it work. I am sure its simple, I just need a little advice to get me going.
I am wanting to create a piece of code that makes an Ajax request out to start a big loop that will download files and then upload them to an S3 bucket of mine. The place where I am stuck is I am wanting to send back a request back to the browser everytime a file is uploaded and output a string of text to the screen upon completion.
I don't have any of the frontend code working... just trying to get my head wrapped around the logic first... any ideas?
PHP Backend Code:
<?php
public function photos($city) {
if(isset($city))
$this->city_name = "{$city}";
// grab data array from Dropbox folder
$postcard_assets = $this->conn->getPostcardDirContent("{$this->city_name}", "Photos", TRUE);
$data = array();
foreach($postcard_assets['contents'] as $asset) {
//only grab contents in root folder... do not traverse into sub folders && make sure the folder is not empty
if(!$asset['is_dir'] && $asset['bytes'] > 0) {
// get information on file
$file = pathinfo($asset['path']);
// download file from Dropbox
$original_file = $this->conn->downloadFile(str_replace(" ", "%20", $asset['path']));
// create file name
$file_name = $this->cleanFileName($file['basename']);
// write photo to TMP_DIR ("/tmp/photos/") for manipulation
$fh = fopen(self::TMP_DIR . $file_name, 'w');
fwrite($fh, $original_file);
fclose($fh);
// Resize photo
$this->resize_photo($file_name);
// hash file name
$raw_file = sha1($file_name);
// create S3 hashed name
$s3_file_name = "1_{$raw_file}.{$file['extension']}";
// Upload manipulated file to S3
$this->s3->putObject($s3_file_name, file_get_contents(self::TMP_DIR . $file_name), $this->photo_s3_bucket, 'public-read');
// check to see if file exists in S3 bucket
$s3_check = $this->s3->getObjectInfo($s3_file_name, $this->photo_s3_bucket);
// if the file uploaded successully to S3, load into DB
if($s3_check['content-length'] > 0) {
$data['src'] = $s3_file_name;
$data['width'] = $this->width;
$data['height'] = $this->height;
Photo::create_postcard_photo($data, "{$this->city_name}");
// Now that the photo has been uploaded to S3 and saved in the DB, remove local file for cleanup
unlink(self::TMP_DIR . $file_name);
echo "{$file_name} uploaded to S3 and resized!<br />";
}
}
}
// after loop is complete, kill script or nasty PHP header warnings will appear
exit();
}
?>
The main problem is that with PHP, the output is buffered so it won't return a line at a time. You can try and force the flush but it's not always reliable.
You could add an entry to the DB for each file that is exchanged and create a seperate API to get the details of what has completed.
Generally, Jquery will wait till the request has finished before it allows you to manipulate data from a HTTP request.

PHP Transfer File on server to Rackspace Cloud Files

I am trying to script some code that will search a specified folder on the server for the latest file with a specific file extension (in my case .zip) and transfer that file to Rackspace's Cloud Files. The code below is as far i got and i keep getting the error:
Fatal error: Uncaught exception 'IOException' with message 'Could not open file for reading: Resource id #8' in /home/test/public_html/cloudapi/cloudfiles.php:1952 Stack trace: #0 /home/test/public_html/final.php(60): CF_Object->load_from_filename(Resource id #8) #1 {main} thrown in /home/test/public_html/cloudapi/cloudfiles.php on line 1952
The code that i'm using below was originally done for uploading content via an html upload form & i'm trying to adapt the same code to use a local server file instead of an uploaded file. You will see commented code with was previously for an upload script to show you how the upload script had worked.
<?php
// include the Cloud API.
require('cloudapi/cloudfiles.php');
// START - Script to find recent file with the extension .zip in current folder
$show = 2; // Leave as 0 for all
$dir = ''; // Leave as blank for current
if($dir) chdir($dir);
$files = glob( '*.zip');
usort( $files, 'filemtime_compare' );
function filemtime_compare( $a, $b )
{
return filemtime( $b ) - filemtime( $a );
}
$i = 0;
foreach ( $files as $file )
{
++$i;
if ( $i == $show ) break;
$value = $file; //Variable $value contains the filename of the recent file to be used in Cloud Files API
}
// END - Script to find recent file with the extension .zip in current folder
// START - Rackspace API code to upload content to cloud files container
// Rackspace Connection Details;
$username = "randomusername"; // put username here
$key = "234887347r93289f28h3ru283h2fuh23093402398"; // api key
// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
//Set the Container you want to use
$container = $conn->get_container('Backups');
//Temp store the file
//$localfile = $_FILES['uploadfile']['tmp_name'];
//$filename = $_FILES['uploadfile']['name'];
$localfile = fopen($value, "r");
$filename = $value;
//Uploading to Rackspace Cloud
$object = $container->create_object($filename);
$object->load_from_filename($localfile);
echo "Your file has been uploaded";
// END - Rackspace API code to upload content to cloud files container
?>
I know this is an old thread. But for the benefit of people who may land at this page while searching for a solution...
The problem with your code is:
The following statement opens the file for reading
$localfile = fopen($value, "r");
However when you place the load_from_filename call, the routine again tries to open the same file and fails because you already have it open in $localfile.
So comment out the previous command and you should be able to run the script successfully.
Error's being thrown in because content type not defined from read file.

Categories