download files outside the document root using PHP - get

I'm trying to download a file using readfile(); in PHP but I'm having trouble, here's my code:
<?php
$getdir = $_GET['dir'];
$getdoctype = $_GET['doctype'];
$getfile = $_GET['filename'];
$dir = "/var/www/uploads/$getdir/$getdoctype/";
$type = mime_content_type( $dir . '/' . $getfile );
$contents = file_get_contents($dir . '/' . $getfile);
if (file_exists($getfile)) {
header('Content-Type: ' . $type);
header('Content-Disposition: attachment;filename=' . $getfile);
readfile($getfile);
}
else{
echo "File Not Found";
}
?>
What am I doing wrong? I want to download the file thats stored in $getfile variable. I want to use all filetypes and all filesizes so thats why I did it like this.
The error I keep getting when I click on the file is: "File Not Found" as per my code. But it does exist.
Please also keep in mind that the website that host these files is SSL enabled

You should try replace this code:
file_exists($getfile) => file_exists($dir . '/' . $getfile)
readfile($getfile); => readfile($dir . '/' . $getfile);
But it's very dangerous use $_GET parameters to load file from filesystem, don't use this code on public website.

Your not pointing to the file correctly.
<?php
$getdir = $_GET['dir'];
$getdoctype = $_GET['doctype'];
$getfile = $_GET['filename'];
$dir = "/var/www/uploads/$getdir/$getdoctype/";
if (file_exists($dir . $getfile)) {
$type = mime_content_type( $dir . $getfile );
header('Content-Type: ' . $type);
header('Content-Disposition: attachment;filename=' . $getfile);
readfile($dir . $getfile);
}
else{
echo "File Not Found";
}
?>

Related

bigbluebutton webhooks checksumError

I want create bigbluebutton webhoock, but "checksum" it's not correct
<?php
$urljoin ="https://server1.example.com/bigbluebutton/api/hooks/create?";
$params ='callbackURL=' .urlencode('http://example.net');
echo $urljoin.$params.'&checksum='.sha1('create'.$params.'S8BFPSCuY6XTghtr3iuNrOJhCKMJEV0W0dkfppjow');
}
please guide me
thanks
Your code is having several issues. Here is the code that you can refer to.
$bbb_url = "https://your_domain/bigbluebutton";
$bbb_secret = "YOUR_BBB_SECRET";
$api_name = "create";
$parameter = "name=Test&meetingID=test01";
$checksum = sha1($api_name . $parameter . $bbb_secret);
$query = $parameter . "&checksum=" . $checksum;
$url = $bbb_url . "/api/" . $api_name . "?" . $query;
header("HTTP/1.1 301 Moved Permanently");
header("Location: $url");
Check the official document for more help about create API call: https://docs.bigbluebutton.org/dev/api.html#create

How to fix if operation is not defined in the WSDL using php nusoap

I am currently working on a project that uses web service PHP Nusoap. I implement it at first in the local computer and it is already working perfectly fine, it can insert already in the database.Since, we are also deploying our project in the production server (Linux RHEL 4) so we also need to include the web service. In implementing this in the production server, we got this error :
Operation '' is not defined in the WSDL for this service Here is the
full details :
<?xml version="1.0" encoding="utf-8"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode xsi:type="xsd:string">SOAP-ENV:Client</faultcode>
<faultactor xsi:type="xsd:string"></faultactor>
<faultstring xsi:type="xsd:string">Operation &apos;&apos; is not defined in the WSDL for this service
</faultstring>
<detail xsi:type="xsd:string"></detail>
</SOAP-ENV:Fault>
HERE IS THE CODE :
client.php
<?php
require_once('lib/nusoap.php');
$data = json_decode(file_get_contents("php://input"), true);
$file_name = $data['file_name'];
$location = $data['location'];
$client = new nusoap_client('http://servername:port/WebService/server.php?wsdl', true);
if ($SERVER['REQUEST_METHOD'] == 'POST') {
$err = $client->getError();
if ($err) {
echo "<h2> Constructor error </h2><pre>" . $err. "</pre>" ;
echo "<h2> Debug </h2><pre>" . htmlspecialchars($client->getdebug(), ENT_QUOTES) . "</pre>" ;
exit();
}
$datas = array (
'file_name' => $file_name,
'location' => $location
);
$result = $client->call('InsertData', $datas);
if ($client->fault) {
echo "<h2> Fault (Expect - The request contains an invalid SOAP Body)</h2> <pre>" ;
print_r ($result);
echo "</pre>";
} else {
$err = $client->getError ();
if ($err) {
echo "<h2> Error </h2><pre>" . $err. "</pre>";
} else {
print_r ($result);
}
}
} else if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "Method is not POST " ;
}
?>
server.php
<?php
require_once('lib.nusoap');
$server = new soap_server();
$server->configureWSDL('Database Sample Insertion', 'urn:Insert');
$server->soap_defenconding = 'UTF-8' ;
$server->register('InsertData',
array (
'file_name' => 'xsd:file_name',
'location' => 'xsd:location'
),
array ('return' => 'xsd:string'),
'urn:Insert',
'urn:Insertwsdl#InsertDate',
'rpc',
'literal'
);
function InsertData ($file_name, $location) {
$db_host = 'localhost';
$db_username = 'username';
$db_password = '' ;
$db_name = 'sample' ;
$conn = new mysqli ($db_host, $db_username, $db_password, $db_name);
if ($conn->connect_error) {
trigger_error('Database connection failed : ' .$conn->connect_error , E_USER_ERROR);
}
$sql = "INSERT INTO transaction (`filename`, `location`) VALUES ('$file_name', '$location')";
$query = $conn->query($sql);
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '' ;
$server->service($HTTP_RAW_POST_DATA);
?>
what does this problem means and how can we solve this? Or how to setup the web service PHP Nusoap in the production server? Any ideas/suggestions is appreciated. Thanks
I'v had the same problem when PHP/Apache version changed at my server. Im my case the problem was located inside nusoap library function: parse_http_headers()
There is a function used to get all HTTP headers getallheaders() and it seems not getting all headers as it should. There were no Content-Type which is required for nusoap to parse request (ex. text/xml).
Fortunately nusoap checks if function getallheaders() exists and if not it uses $_SERVER array to parse headers.
Finally the one thing I had to do was to change one line of code inside nusoap.php file to disable this function:
if (function_exists('getallheaders')){ ...
to this one:
if (0 && function_exists('getallheaders')){ ...
Hope this help others!

Collaborating of two threads

I have created a Perl script with the two threads:
1) Create .cfg files
2) Read those .cfg files
I want to accomplish that while one thread is busy making files, side by side my second thread would read those files.
Bu I am facing a problem at that moment when my second thread is created it will only read that files which are created at that moment. Can anyone give idea about accomplishing this task.
The Create threads and Reading files functions are mentioned below:
sub CreateThreads() {
$threads[0] = threads->create( \&CreateCFG );
sleep 3;
$threads[1] = threads->create( \&ReadCFG );
}
sub ReadCFG() {
my $id = threads->tid();
opendir( DIR, $filedir ) or die $!;
while ( my $files = readdir(DIR) ) {
if ( $files eq "." || $files eq ".." ) {
next;
}
else {
my $filepath = $filedir . "/" . $files;
if ( $files =~ m/$probename/ ) {
my #file = split( "&", $files );
if ( $file[3] !~~ #reportrobots ) {
push( #reportrobots, $file[3] );
my $raddr =
"/" . $file[1] . "/" . $file[2] . "/" . $file[3];
&ProbeReport( \$userdata_file, \$filepath, \$raddr );
}
}
}
}
}
I think your problem here will be that you're not rereading the directory.
opendir( DIR, $filedir ) or die $!;
while ( my $files = readdir(DIR) ) {
Because it's not obvious, what's actually happening is the first time you call readdir it reads the directory, and subsequent calls just iterate that list.
That's to prevent strange things happening if - for example - I'm creating a file in that directory within my loop.
So in effect - your second thread only ever looks at that directory once. It's functionally similar to:
my #files = readdir(DIR);
foreach my $file ( #files ) {
I would suggest that what you need is the rewinddir function. Or perhaps use a Thread::Queue or other mechanism to pass through files in need of processing.

prevent direct access to PDF link for guest users

I have a joomla site. And have some pdf files into the root of the website.
Is there a way to protect the DIRECT ACCESS to the pdf's for the GUESTS(public) users.. and allow for REGISTERED users?
I tried with htaccess(deny) but registered users can't view the pdf directly too..
Searched but didn't find nothing about this.. PLEASE can somebody help.
Thank you
You must use document management plug-in if you wont want to write your own php codes.SO, DOCman is a powerful document management solution for Joomla. You can check it from following link.
http://extensions.joomla.org/extensions/directory-a-documentation/downloads/10958
Create a file called download.php
Add the following code to download.php file enclose with php tag
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
if (file_exists(dirname(__FILE__) . '/defines.php')) {
include_once dirname(__FILE__) . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', dirname(__FILE__));
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
// Mark afterLoad in the profiler.
JDEBUG ? $_PROFILER->mark('afterLoad') : null;
// Instantiate the application.
$app = JFactory::getApplication('site');
// Initialise the application.
$app->initialise();
$user = JFactory::getUser();
$getfile = JRequest::getVar('file',null,'get','string');
if($getfile){
if($user->get('id') == 0){
die('permission denied');
}
$link = "/files/".$getfile.".pdf"; // Locate the pdf file
$file = JPATH_SITE.$link;
header("Content-Type: application/octet-stream");
$filename = $getfile.'.pdf';
header("Content-Disposition: attachment; filename=".urlencode($filename));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
}
$app->close();
URL example :- www.example.com/download.php?file=filename
And make sure you have change the $link variable as you need.
In .htacess file you have to add the following code
deny from all
And it should be located under the invoice folder where the pdf files is located.
If you use deny from all then file do not have download access for the particular directory where the htacess file is located.
To allow download access for registered user the below controller has to be called instead of direct file path url.
URL example :- www.example.com/index.php?option=com_temp&task=temp.downloadmypdf&file=filename
public function downloadmypdf(){
$user = JFactory::getUser();
$getfile = JRequest::getVar('file');
if($user->get('id') == 0){
die('permission denied');
}
$link = "/invoice/".$getfile.".pdf";
$file = JPATH_SITE.$link;
header("Content-Type: application/octet-stream");
$filename = $getfile.'.pdf';
header("Content-Disposition: attachment; filename=".urlencode($filename));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
JFactory::getApplication()->close();
}
Credits goes to Ashlin rejo.

Webforms in excel instead of e-mail

A client of mine asked me if i can find a solution for this problem.
His website (still a WIP) http://welkommagazine.nl/luuk/ has a form. The form obviously uses a sendmail script to send the form to e-mail. From thereon he manually copy/pastes all the submissions to excel.
What he wants is that the forms online automaticcaly are added to an excel document to save him a lot of work.
Now i am not a programmer, but a designer.. I think this can be done, but i have absolutely no clue how. I googled alot for it and the only thing i found was a dreamweaverplugin.
Is there a way to do this, if so, how?
Not a programmer's response, but...
I think an easy solution is to use Google docs. You can set-up a Google Spreadsheet and associate a form to it. Whenever a user fills the form , his data is added to the spreadsheet.
Your client may download that anytime.
There are some other providers on the market, some free, some not. E.g: wufoo.com
Found the answer myself. I wrote a PHP code snippet which actually stores the fields comma seperated in a CSV file and sends an email to a desired adress with the filled in fields.
if(isset($_POST['Submit'])){
$pakket = $_POST['pakket'];
$extragidsen = $_POST['extragidsen'];
$naambedrijf = $_POST['naambedrijf'];
$err = '';
if(trim($pakket)==''){
$err .= '-Please enter a name';
}
if(empty($extragidsen)){
$err .= '-Please enter an email address';
}
if(strlen($naambedrijf)==0){
$err .= '-Please enter a comment';
}
if($err!=''){
echo $err;
}
else{
$filename = 'file.csv';
$somecontent = $pakket . ',' . $extragidsen . ',' . $naambedrijf . "\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
//--------------------------Set these paramaters--------------------------
// Subject of email sent to you.
$subject = 'Inschrijving welkom';
// Your email address. This is where the form information will be sent.
$emailadd = 'luuk#luukratief.com';
// Where to redirect after form is processed.
$url = 'http://www.google.com';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
foreach ($_POST as $key => $value)
{
if ($req == '1')
{
if ($value == '')
{echo "$key is empty";die;}
}
$j = strlen($key);
if ($j >= 20)
{echo "Name of form element $key cannot be longer than 20 characters";die;}
$j = 20 - $j;
for ($i = 1; $i ';
fclose($handle);
} else {
echo "The file $filename is not writable";
}
}
}
Maybe the code aint that clean as it can be, but eh it works.
Feel free to clean up the code if you want to :)
I guessed I would answer this myself for the community...
BTW u need to set "write" rights to "file.csv"
cheers

Resources