I am trying to rename a file that I am accepting via http POST. Please see the code:
<?php
$xmlData = fopen('php://input' , 'rb');
while (!feof($xmlData)) { $xmlString .= fread($xmlData, 4096); }
fclose($xmlData);
file_put_contents('temp/message' . date('m-d-y') . '-' . time() . '.xml', $xmlString, FILE_APPEND);
$xml = new SimpleXMLElement($xmlString);
$id = trim($xml->MSG->ID);
$receiver = trim($xml->MSG->RECEIVER);
$message = trim($xml->MSG->MESSAGE);
$sender = trim($xml->MSG->SENDER);
$binary = trim($xml->MSG->BINARY);
$sent = trim($xml->MSG->SENT);
foreach ($xml->{'line-items'}->{'line-item'} as $lineItem) {
array_push($messageTitles, trim($lineItem->title));
}
header('HTTP/1.0 200 OK');
exit();
Now I am at a slight loss at how to rename this?
You don't even need to save the file in order to process the XML tree. So you can process the file and move the file_put_contents(...) at the end.
<?php
$xmlData = fopen('php://input' , 'rb');
while (!feof($xmlData)) { $xmlString .= fread($xmlData, 4096); }
fclose($xmlData);
$xml = new SimpleXMLElement($xmlString);
$id = trim($xml->MSG->ID);
$receiver = trim($xml->MSG->RECEIVER);
$message = trim($xml->MSG->MESSAGE);
$sender = trim($xml->MSG->SENDER);
$binary = trim($xml->MSG->BINARY);
$sent = trim($xml->MSG->SENT);
foreach ($xml->{'line-items'}->{'line-item'} as $lineItem) {
array_push($messageTitles, trim($lineItem->title));
}
file_put_contents("temp/$receiver.xml", $xmlString, FILE_APPEND); // warning: security issue here
header('HTTP/1.0 200 OK');
exit();
Please note that you should enforce security restrictions to prevent the user from naming your file with an arbitrary name.
Related
When I generate an excel sheet from the database it shows an error that "excel file does not match format. Do you want to open it anyway?" and it says to click on ok button to upgrade format of excel file. When I click on ok it works fine... but in mobile its not open.
i want to generate microsoft excel file with no error.
//generating Excel File
$setSql = "SELECT * from demo table";
$setRec = mysqli_query($db, $setSql);
$header_name="DATA LIST IN EXCEL";
$Event= "This is a demo";
date_default_timezone_set("Asia/Kolkata");
$date='Export Date:-'.date("l, jS \of F Y h:i:s A");
$columnHeader = '';
$columnHeader = "Name" . "\t" . "Date" . "\t". "Mode No" . "\t". "Address" . "\t". "eduction"."\t"."Organisation" . "\t". "Paid Status" . "\t";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename= file_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo $header_name ."\t\t\t\t\t\t\t\n". $Event ."\t\t\t". $date ."\n". ucwords($columnHeader) . "\n" . $setData . "\n";
Here you have our code.
Notice
ob_clean before download
This is the tricky point. If you have some content in the output buffer (maybe for an incorrect include file) it is sent with the file. So, you have to clean it before any download command
Added BOM header to CSV file
And, if you plan to open the file with Excel, and the file is UTF8, you have to add BOM header
public function reportAsset($budgetPeriod_id)
{
$timeProcess = round(microtime(true) / 1000);
if ($budgetPeriod_id) {
$budget = \App\Models\Invoicing\BudgetPeriod::select(['description'])->find((int) $budgetPeriod_id);
$client = \App\Models\Structure\Client::select(['description'])->find($this->client_id);
$filename = date('Ymd').'_'.$budget->description . '_' . $client->description . '.csv';
$headers = [
'Content-type' => 'text/csv;charset=UTF-8',
'Content-Disposition' => 'attachment; filename=' . $filename,
'Pragma' => 'no-cache',
'Expires' => '0',
];
$output = fopen($filename, "w");
// JMA: Add BOM header
fputs($output, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
fputcsv($output, [_i('Asset_id'), _i('Asset'), _i('Client Category'), _i('Budget'), _i('Spent'), _i('Available'),_i('Spent') .' %', _i('# Invoices')], ';');
$query = \App\Models\Invoicing\AssetBudget::query();
$query->has('asset')
->has('clientCategory')
->with('asset:PROCESS_ID,Identificador_Processo', 'clientCategory:id,description')
->orderBy('asset_id', 'clientCategory_id', 'clientCategory.id')
->selectRaw('amount as total, asset_id, budgetPeriod_id, clientCategory_id')
->where('budgetPeriod_id', $budgetPeriod_id)
->chunk($this::BUDGET_CHUNK, function ($chunk_query) use ($budgetPeriod_id, $output, $timeProcess) {
foreach ((array) $chunk_query as $report) {
foreach ($report as $rep) {
$row = [];
// JMA: The amount has to be the individual amount per asset
// So. we read asset_invoices where the invoice is in the budget period and category
// TODO: Replace this piece of code with consumedBudgetByRequest function in Invoicing BudgetController
// TODO: Try with calculateBudget but is not the same structure
//$invoices = \App\Library\Invoicing\BudgetCalculator::calculateBudget($rep->budgetPeriod_id, $rep->clientCategory_id, (array)$rep->asset_id);
$invoices=AssetInvoice::whereHas('invoice' , function ($invoice) use ($rep) {
$invoice->where('budgetPeriod_id',$rep->budgetPeriod_id)
->where('clientCategory_id',$rep->clientCategory_id);
}
)
->selectRaw('count(asset_id) as nInvoices, sum(amount) as spent')
->where('asset_id',$rep->asset_id)
->first();
// Log::debug('BudgetController->reportAsset: Invoices found='.$invoices->nInvoices.' spent='.$invoices->spent);
$row['asset_id'] = $rep->asset->PROCESS_ID;
$row['Identificador_Processo'] = $rep->asset->Identificador_Processo;
$row['clientCategory'] = $rep->clientCategory->description;
$row["budget"] = floatval($rep->total);
$row["spent"] = floatval($invoices->spent);
$row["available"] = $row["budget"] - $row["spent"];
if(floatval($rep->total)==0 ){
$row["percentaje"] = '';
}else{
$row["percentaje"] = number_format((float)(floatval($invoices->spent)*100)/ floatval($rep->total), 2, '.', '');
}
$row["nInvoices"] = floatval($invoices->nInvoices);
// Uncomment this line to monitor time consumption
// $row["times"] = $timeProcess - round(microtime(true) / 1000);
fputcsv($output, $row, ';');
}
}
});
fclose($output);
// CHECK THIS: Clean output buffer before sending files (avoid initial whitespaces)
if (ob_get_contents()) {
ob_clean();
}
// Send csv file as response
return response()->download($filename, $filename, $headers)->deleteFileAfterSend(true);
}
I want to connect php with tally and I want to store ledger in tally with php any idea?
I got reference from different site like :
1) http://www.tallysolutions.com/website/html/tallydeveloper/integration-capabilities.php
2)http://stackoverflow.com/questions/15717941/how-to-insert-data-into-tally-using-php
But it doesn't fulfill my requirement.
Thanks in advance
It's may help you
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
$envelope = $doc->appendChild($doc->createElement('ENVELOPE'));
//Header Section
$header = $envelope->appendChild($doc->createElement('HEADER'));
$version = $header->appendChild($doc->createElement('VERSION','6.3'));
$import = $header->appendChild($doc->createElement('TALLYREQUEST','Import'));
$type = $header->appendChild($doc->createElement('TYPE','Data'));
$id = $header->appendChild($doc->createElement('ID','All Masters'));
//End Header Section
//Body Section
$body = $envelope->appendChild($doc->createElement('BODY'));
$desc = $body->appendChild($doc->createElement('DESC'));
$static_var = $desc->appendChild($doc->createElement('STATICVARIABLES'));
$dup_combine = $static_var->appendChild($doc->createElement('IMPORTDUPS','##DUPCOMBINE'));
$data = $body->appendChild($doc->createElement('DATA'));
$tally_msg = $data->appendChild($doc->createElement('TALLYMESSAGE'));
//Ledger Data
foreach($contacts_data as $key => $value){
$ledger = $tally_msg->appendChild($doc->createElement('LEDGER'));
$parent=$ledger->appendChild($doc->createElement('PARENT',($value['contacts_types_id']=='1')?'Sundry Debtors':'Sundry Creditors'));
$name=$ledger->appendChild($doc->createElement('NAME',trim(str_replace( "&"," AND ",$value['name']))));
$address=$ledger->appendChild($doc->createElement('ADDRESS',trim(str_replace( "&"," AND ",$value['address']))));
$state=$ledger->appendChild($doc->createElement('STATENAME',trim(str_replace( "&"," AND ",$value['state_name']))));
$pincode=$ledger->appendChild($doc->createElement('PINCODE',$value['pincode']));
/*$ledger_contact=$ledger->appendChild($doc->createElement('LEDGERCONTACT',trim(str_replace( "&"," AND ",$value['contact_person']))));
$phone=$ledger->appendChild($doc->createElement('LEDGERPHONE',$value['phone']));
$fax=$ledger->appendChild($doc->createElement('LEDGERFAX',$value['fax']));
$mobile_no=$ledger->appendChild($doc->createElement('MOBILENO',$value['mobile_no']));
$sales_tax_no=$ledger->appendChild($doc->createElement('SALESTAXNO','23456789'));
$pan_no=$ledger->appendChild($doc->createElement('PANNO','453456789'));*/
$o['contacts_id'][]=$value['id'];
}
//End Ledger and Body Section
//Write the XML nodes
$fp = fopen(public_path()."/xml/import_tally/ledger.xml","wb");
if(fwrite($fp,$doc->saveXML())){
$o['tally_rslt']= shell_exec("curl -X POST tally_server_ip:port --data #".public_path()."/xml/import_tally/ledger.xml");
$o['modified_result']=strpos(preg_replace('/[0-9]+/', '', $o['tally_rslt']),'exists');
}
fclose($fp);
return $o;
I'm trying to send a json object as a POST command using the following:
$uri = "http://amore-luce.com/product_create";
$product = $observer->getEvent()->getProduct();
$json = Mage::helper('core')->jsonEncode($product);
Mage::log(" Json={$json}", null,'product-updates.txt');
// new HTTP request to some HTTP address
$client = new Zend_Http_Client('http://amore-luce.com/product_create');
// set some parameters
$client->setParameterPost('product', $json);
// POST request
$response = $client->request(Zend_Http_Client::POST);
When I view the $json the data is there and all looks good - however the POST is not sending the json data. I'm capturing it using a simple email form that should send me the response:
<?php
$webhookContent = "";
$ref = "";
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhookContent .= fread($webhook, 4096);
}
fclose($webhook);
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
foreach ($headers as $header => $value) {
$ref .= "$header: $value <br />\n";
}
$post = file_get_contents('php://input');
$to = "address#my-email.com"; //the address the email is being sent to
$subject = "This is the subject"; //the subject of the message
$msg = "This is the message - Webhook content: ".$webhookContent." This is url: ".$ref; //the message of the email
mail($to, $subject, $msg, 'From: PHP Scriptv2 <noreply#domain.com>'); //send the email.
echo ($_SERVER['HTTP_REFERER']."<br>".$_SERVER['REQUEST_URI']);
?>
This page works with other json POST requests I've sent to it. I'm fairly new at sending POST requests so any help would be greatly appreciated.
Try change :
$client->setParameterPost('product', $json);
to :
$client->setHeaders('Content-type','application/json');
$client->setParameterPost('product', $json);
or use:
$client->setRawData($json, 'application/json');
So Update / Answer changing how I did it to these lines of code:
$uri = "http://requestb.in/p6p4syp6";
$product = $observer->getEvent()->getProduct();
$json = Mage::helper('core')->jsonEncode($product);
Mage::log(" Json={$json}", null,'product-updates.txt');
$client = new Zend_Http_Client($uri);
$client->setRawData($json, null)->request('POST');
Changing the SetRawData($json, null) was the bit - using SetRawDate($json, 'application/json') caused it to fail.
Thanks Voodoo417 - I'll also try your suggestion and see if that lets me set the correct type
I need to retrieve a get http request in php and store it in a variable.
I need to execute the following:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
I know this is simple. just not able to get my head around it.
$content = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials');
Within the Open Graph protocol page on Facebook, there is an example within the documentation coded using PHP: http://developers.facebook.com/docs/opengraph/
<?php
$ogurl = "INSERT_YOUR_OG_URL_HERE";
define(FACEBOOK_APP_ID, "YOUR_APP_ID_HERE");
define(FACEBOOK_SECRET, "YOUR_SECRET_KEY_HERE");
$mymessage = "Hello World!";
$access_token_url = "https://graph.facebook.com/oauth/access_token";
$parameters = "grant_type=client_credentials&client_id=" . FACEBOOK_APP_ID ."&client_secret=" . FACEBOOK_SECRET;
$access_token = file_get_contents($access_token_url . "?" . $parameters);
$apprequest_url = "https://graph.facebook.com/feed";
$parameters = "?" . $access_token . "&message=" . urlencode($mymessage) . "&id=" . $ogurl . "&method=post";
$myurl = $apprequest_url . $parameters;
$result = file_get_contents($myurl);
// output the post id
echo "post_id" . $result;
}
?>
The key line in actually making the call being:
$result = file_get_contents($myurl);
There is also a good amount of other information about the resulting object you get back there that would be good to take a look into.
Hope this is helpful.
if ($fp = fopen('https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
// do something with the content here
// ...
} else {
// an error occured when trying to open the specified url
}
You mean something like
$client_id = $_GET['client_id'];
$client_secret = $_GET['client_secret'];
$grant_type = $_GET['grant_type'];
?
Or rather something like
$content = file_get_contents($url);
?
Use the following
$id = $_GET['client_id'];
$type = $_GET['grant_type'];
$secret = $_GET['client_secret'];
Hope this helps you
$httpsock = #socket_create_listen("9090");
if (!$httpsock) {
print "Socket creation failed!\n";
exit;
}
while (1) {
$client = socket_accept($httpsock);
$input = trim(socket_read ($client, 4096));
$input = explode(" ", $input);
$input = $input[1];
$fileinfo = pathinfo($input);
switch ($fileinfo['extension']) {
default:
$mime = "text/html";
}
if ($input == "/") {
$input = "index.html";
}
$input = ".$input";
if (file_exists($input) && is_readable($input)) {
echo "Serving $input\n";
$contents = file_get_contents($input);
$output = "HTTP/1.0 200 OK\r\nServer: APatchyServer\r\nConnection: close\r\nContent-Type: $mime\r\n\r\n$contents";
} else {
//$contents = "The file you requested doesn't exist. Sorry!";
//$output = "HTTP/1.0 404 OBJECT NOT FOUND\r\nServer: BabyHTTP\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n$contents";
function openfile()
{
$filename = "a.pl";
$file = fopen($filename, 'r');
$filesize = filesize($filename);
$buffer = fread($file, $filesize);
$array = array("Output"=>$buffer,"filesize"=>$filesize,"filename"=>$filename);
return $array;
}
$send = openfile();
$file = $send['filename'];
$filesize = $send['filesize'];
$output = 'HTTP/1.0 200 OK\r\n';
$output .= "Content-type: application/octet-stream\r\n";
$output .= 'Content-Disposition: attachment; filename="'.$file.'"\r\n';
$output .= "Content-Length:$filesize\r\n";
$output .= "Accept-Ranges: bytes\r\n";
$output .= "Cache-Control: private\n\n";
$output .= $send['Output'];
$output .= "Content-Transfer-Encoding: binary";
$output .= "Connection: Keep-Alive\r\n";
}
socket_write($client, $output);
socket_close ($client);
}
socket_close ($httpsock);
Hello, I am snikolov i am creating a miniwebserver with php and i would like to know how i can send the client a file to download with his browser such as firefox or internet explore i am sending a file to the user to download via sockets, but the cleint is not getting the filename and the information to download can you please help me here,if i declare the file again i get this error in my server
Fatal error: Cannot redeclare openfile() (previously declared in C:\User
s\fsfdsf\sfdsfsdf\httpd.php:31) in C:\Users\hfghfgh\hfghg\httpd.php on li
ne 29, if its possible, i would like to know if the webserver can show much banwdidth the user request via sockets, perl has the same option as php but its more hardcore than php i dont understand much about perl, i even saw that a miniwebserver can show much the client user pulls from the server would it be possible that you can assist me with this coding, i much aprreciate it thank you guys.
You are not sending the filename to the client, so how should it know which filename to use?
There is a drawback, you can provide the desired filename in the http header, but some browsers ignore that and always suggest the filename based on the last element in URL.
For example http://localhost/download.php?help.me would result in the sugested filename help.me in the file download dialogue.
see: http://en.wikipedia.org/wiki/List_of_HTTP_headers
Everytime you run your while (1) loop you declare openfile function. You can declare function only once. Try to move openfile declaration outside loop.
$httpsock = #socket_create_listen("9090");
if (!$httpsock) {
print "Socket creation failed!\n";
exit;
}
while (1) {
$client = socket_accept($httpsock);
$input = trim(socket_read ($client, 4096));
$input = explode(" ", $input);
$input = $input[1];
$fileinfo = pathinfo($input);
switch ($fileinfo['extension']) {
default:
$mime = "text/html";
}
if ($input == "/") {
$input = "index.html";
}
$input = ".$input";
if (file_exists($input) && is_readable($input)) {
echo "Serving $input\n";
$contents = file_get_contents($input);
$output = "HTTP/1.0 200 OK\r\nServer: APatchyServer\r\nConnection: close\r\nContent-Type: $mime\r\n\r\n$contents";
} else {
//$contents = "The file you requested doesn't exist. Sorry!";
//$output = "HTTP/1.0 404 OBJECT NOT FOUND\r\nServer: BabyHTTP\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n$contents";
$filename = "dada";
$file = fopen($filename, 'r');
$filesize = filesize($filename);
$buffer = fread($file, $filesize);
$send = array("Output"=>$buffer,"filesize"=>$filesize,"filename"=>$filename);
$file = $send['filename'];
$output = 'HTTP/1.0 200 OK\r\n';
$output .= "Content-type: application/octet-stream\r\n";
$output .= "Content-Length: $filesize\r\n";
$output .= 'Content-Disposition: attachment; filename="'.$file.'"\r\n';
$output .= "Accept-Ranges: bytes\r\n";
$output .= "Cache-Control: private\n\n";
$output .= $send['Output'];
$output .= "Pragma: private\n\n";
// $output .= "Content-Transfer-Encoding: binary";
//$output .= "Connection: Keep-Alive\r\n";
}
socket_write($client, $output);
socket_close ($client);
}
socket_close ($httpsock);