PHP Download 2 path - php

I have script PHP download 2 path,
And i try in localhost this code work, but i try in my server error not work
This Error
Parse error: syntax error, unexpected '[' in C:\xampp\htdocs\pm_mobile_indosat\link.php on line 10
Full Code
<?php
include "conection.php";
$id = $_GET['id'];
$data = mysql_fetch_array(mysql_query("SELECT * FROM task WHERE id = '$id'"));
$paths = [
"Attachment/".$data['task_id']."/",
"D:/ALL BACKUP GOES HERE/Attachment_kt_fri_jpg_dll/".$data['task_id']."/"
];
foreach ($paths as $path) {
if (file_exists($path . $data['attachment_file'])) {
header("Content-Disposition: attachment; filename=" . $data['attachment_file']);
print file_get_contents($path . $data['attachment_file']);
exit;
}
}
echo "File not found";
exit;
?>
This Error in
$paths = [
"Attachment/".$data['task_id']."/",
"D:/ALL BACKUP GOES HERE/Attachment_kt_fri_jpg_dll/".$data['task_id']."/" ];
Because i have script if disk C full, then files in disk C cut to Disk D.
So i want this script work in my Server.

The script is using the short form of the array declaration introduced in PHP 5.4.
With PHP 5.4 you can declare an array like this:
$arr = []; // for 5.3 you'd use $arr = array();
if your code works on one server but throws this error on another, you have a version of PHP less than 5.4 on the failing server.
Either: upgrade the server to PHP 5.4 or later; or edit the code to use the older form of the array declaration.
NB - there may be other incompatibilities between the code and earlier versions of PHP. Upgrading your server is the way to go.

Related

Warning: Creating default object from empty value in

I have a script which tests the connection speed. When I moved it to another server I got the following warning:
Warning: Creating default object from empty value in /home/speed/public_html/common.php on line 26
Here is an excerpt from my code:
## Read through the config file and assign items to the global $config variable
function ReadConfig($config_file) {
global $config;
$lines = file($config_file);
foreach ($lines as $line_num => $line) {
$line = rtrim(preg_replace("/#.*/","",$line));
if(preg_match("/\[.*\]/", $line, $parts)) {
$section = $parts[0];
$section = preg_replace("/[\[\]]/","",$section);
} elseif (preg_match("/=/",$line)) {
list($var,$value) = split('=',$line);
$var = preg_replace('/ $/','',$var);
$value = preg_replace('/^ +/','',$value);
$config->{$section}->{$var} = $value; # here
}
}
}
I am currently running PHP 5.5, the other server runs a newer version of PHP.
Prefix line 26 with this check:
if (!isset($config->{$section}))
$config->{$section} = new Stdclass;
and it should work without generating warning
#Sjon provides the answer to get rid of the warning, I will just explain why you see the warning now.
Since you moved your code to another server, there is most probably another php ini file and thus, different settings. On your "old" server, you had the errors and warnings most likely switched off so you did not see them, on the "new" server they are switched on by default.
Instead of displaying errors you can log them so you do not see them while browsing:
display_errors(false);
// you definitely wanna log any occurring
log_errors(true);

A reliable way to output multiple JavaScript files in one PHP script? (Avoiding unexpected token ILLEGAL)

I'm using PHP to create a JavaScript document. It does do two things:
Read a directory containing some HTML files that I use as templates and then output an object containing key: value pairs that represent the filename: content, which will end up similar to this:
var HTML = {
"blogpost.html": '<div>{post}</div>',
"comment.html" : '<div class="comment">{comment}</div>'
};
Which allows me to use HTML["template.html"] to append templated data that I receive from AJAX requests.
Read a directory containing JavaScript files and output the content of those straight into the document.
Locally it's working fine, but I've been getting this error when I try it once uploaded:
Uncaught SyntaxError: Unexpected token ILLEGAL
I've tried wrapping the output I get from each of the HTML and JS files in things like:
preg_replace('/\s{2,}/', '', $output);
addslashes($output);
mysql_real_escape_string($output);
And a combination of those, but still the same error.
How can I reliably output the HTML and JavaScript I'm trying to place in the output?
Here's the current entire PHP script I am using (which works locally but not online weirdly):
header("Content-type: application/x-javascript");
// Write HTML templates.
$dir = dir($_SERVER['DOCUMENT_ROOT'] . '/view/html/');
$files = array();
while($file = $dir->read())
{
if(strpos($file, ".html"))
{
$key = substr($file, 0, strpos($file, ".html"));
array_push($files, '"' . $key . '": \'' . compress(file_get_contents($dir->path . $file)) . "'");
}
}
echo 'var HTML = {' . implode(",", $files) . '};';
// Output other JavaScript files.
$js = array();
array_push($js, file_get_contents("plugin/jquery.js"));
array_push($js, file_get_contents("plugin/imagesloaded.js"));
array_push($js, file_get_contents("plugin/masonry.js"));
array_push($js, file_get_contents("base/master.js"));
array_push($js, file_get_contents("plugin/ga.js"));
echo implode("", $js);
// Compress a JavaScript file.
function compress($str)
{
return addslashes(preg_replace('/\s{2,}/', '', $str));
}
You can use json_encode() for any PHP -> JS conversion:
while ($file = $dir->read()) {
if(strpos($file, ".html")) {
$key = substr($file, 0, strpos($file, ".html"));
$files[$key] = compress(file_get_contents($dir->path . $file));
}
}
echo 'var HTML = ' . json_encode($files) .';';
That's a parser error, so the problem happens before your code is even run.
I recommend checking the PHP versions of the two runtimes you're using. It would be ideal to develop and test with the same runtime that you plan to deploy to.
This happened to me before as well.
I'm assuming you copied part of the code you posted on a website like Github, or maybe your editor has stuffed up.
Invisible characters have been known to lurk in such documents.
A fix to this error is type the line of code with the error, the line above it, and the line underneath it in a fully plain-text editor like Notepad (Windows) or TextEdit (Mac). After typing it in, use Ctrl-A or Cmd-A (select all), then copy it and replace the code in your normal code editor.
Should fix the error.
I've worked out how to solve the problem in my current situation.
Background:
My local machine is running PHP Version 5.3.5
My host is running PHP Version 5.2.17
The problem was occurring at the end of each of the loaded HTML documents, where there wasn't a space or tab on the last line of the document, e.g.
<div>
content
</div> <-- at the beginning of this line
Solution:
I changed the preg_replace() statement that was working with the output of each file so that it would also match newlines, which seems to have fixed it.
return preg_replace('/\s{2,}/', '', $str); // Old
return preg_replace('/\s{2,}|\n/', '', $str); // New

run php script and return data as a string

My php script needs to load contents from another file and then replace certain commands. Using the following code works on static pages:
$pageName = 'pages/' . $_REQUEST['url'] . '.php';
$pageContents = file_get_contents($pageName);
$IDCODE = $_SESSION['IDCODE'];
$sql = "SELECT * FROM members WHERE IDCODE = '$IDCODE'";
$qry = mysql_query($sql);
$OK = $qry ? true : false;
$arr = mysql_fetch_array($qry);
foreach ($arr AS $key => $val) {
$pageContents = str_replace('{' . $key . '}', $val, $pageContents);
}
however, what if the file to be processed was dynamic? IE it populates some text from the mysql database.
Will file_get_contents run the file or just read whats in it as a string?
If you run the link to the file via a webserver, it will be processed. If you link it directly, you will get the exact contents of the file.
Rather messy code.
$pageName = 'pages/' . $_REQUEST['url'] . '.php';
$pageContents = file_get_contents($pageName);
local file inclusion vulnerability here.
$OK = $qry ? true : false;
Why? Anywere you use the value of $OK you could equally use $qry. And you never use $OK again in the code shown.
There's no error checking, no comments in the code.
what if the file to be processed was dynamic?
WTF? Do you mean you want to re-process the output as PHP? Then you could 'eval($pageContents);' but beware of code injection vulnerabilities.
Or you want to apply your script to the output of a PHP scrpt? Then just pass the URL as the argument to file_get_contents() e.g.
file_get_contents('http://localhost/path/'
. basename($_REQUEST['url'] . '.php');
But really the invocation should be controlled better than this. Both are messy solutions - a templating solution should be just that. Go have a long hard look at (e.g.) smarty

CSV file generation error

I'm working on a project for a client - a wordpress plugin that creates and maintains a database of organization members. I'll note that this plugin creates a new table within the wordpress database (instead of dealing with the data as custom_post_type meta data). I've made a lot of modifications to much of the plugin, but I'm having an issue with a feature (that I've left unchanged).
One half of this feature does a csv import and insert, and that works great. The other half of this sequence is a feature to download the contents of this table as a csv. This part works fine on my local system, but fails when running from the server. I've poured over each portion of this script and everything seems to make sense. I'm, frankly, at a loss as to why it's failing.
The php file that contains the logic is simply linked to. The file:
<?php
// initiate wordpress
include('../../../wp-blog-header.php');
// phpinfo();
function fputcsv4($fh, $arr) {
$csv = "";
while (list($key, $val) = each($arr)) {
$val = str_replace('"', '""', $val);
$csv .= '"'.$val.'",';
}
$csv = substr($csv, 0, -1);
$csv .= "\n";
if (!#fwrite($fh, $csv))
return FALSE;
}
//get member info and column data
$table_name = $wpdb->prefix . "member_db";
$year = date ('Y');
$members = $wpdb->get_results("SELECT * FROM ".$table_name, ARRAY_A);
$columns = $wpdb->get_results("SHOW COLUMNS FROM ".$table_name, ARRAY_A);
// echo 'SQL: '.$sql.', RESULT: '.$result.'<br>';
//output headers
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"members.csv\"");
//open output stream
$output = fopen("php://output",'w');
//output column headings
$data[0] = "ID";
$i = 1;
foreach ($columns as $column){
//DIAG: echo '<pre>'; print_r($column); echo '</pre>';
$field_name = '';
$words = explode("_", $column['Field']);
foreach ($words as $word) $field_name .= $word.' ';
if ( $column['Field'] != 'id' && $column['Field'] != 'date_updated' ) {
$data[$i] = ucwords($field_name);
$i++;
}
}
$data[$i] = "Date Updated";
fputcsv4($output, $data);
//output data
foreach ($members as $member){
// echo '<pre>'; print_r($member); echo '</pre>';
$data[0] = $member['id'];
$i = 1;
foreach ($columns as $column){
//DIAG: echo '<pre>'; print_r($column); echo '</pre>';
if ( $column['Field'] != 'id' && $column['Field'] != 'date_updated' ) {
$data[$i] = $member[$column['Field']];
$i++;
}
}
$data[$i] = $member['date_updated'];
//echo '<pre>'; print_r($data); echo '</pre>';
fputcsv4($output, $data);
}
fclose($output);
?>
So, obviously, a routine wherein a query is run, $output is established with fopen, each row is then formatted as comma delimited and fwrited, and finally the file is fclosed where it gets pushed to a local system.
The error that I'm getting (from the server) is
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.
But it clearly is getting found, its just failing. If I enable phpinfo() (PHP Version 5.2.17) at the top of the file, I definitely get a response - notably Cannot modify header information (I'm pretty sure because phpinfo() has already generated a header). All the expected data does get printed to the bottom of the page (after all the phpinfo diagnostics), however, so that much at least is working correctly.
I am guessing there is something preventing the fopen, fwrite, or fclose functions from working properly (a server setting?), but I don't have enough experience with this to identify exactly what the problem is.
I'll note again that this works exactly as expected in my test environment (localhost/XAMPP, netbeans).
Any thoughts would be most appreciated.
update
Ok - spent some more time with this today. I've tried each of the suggested fixes, including #Rudu's writeCSVLine fix and #Fernando Costa's file_put_contents() recommendation. The fact is, they all work locally. Either just echoing or the fopen,fwrite,fclose routine, doesn't matter, works great.
What does seem to be a problem is the inclusion of the wp-blog-header.php at the start of the file and then the additional header() calls. (The path is definitely correct on the server, btw.)
If I comment out the include, I get a csv file downloaded with some errors planted in it (because $wpdb doesn't exist. And if comment out the headers, I get all my data printed to the page.
So... any ideas what could be going on here?
Some obvious conflict of the wordpress environment and the proper creation of a file.
Learning a lot, but no closer to an answer... Thinking I may need to just avoid the wordpress stuff and do a manual sql query.
Ok so I'm wondering why you've taken this approach. Nothing wrong with php://output but all it does is allow you to write to the output buffer the same way as print and echo... if you're having trouble with it, just use print or echo :) Any optimizations you could have got from using fwrite on the stream then gets lost by you string-building the $csv variable and then writing that in one go to the output stream (Not that optimizations are particularly necessary). All that in mind my solution (in keeping with your original design) would be this:
function escapeCSVcell($val) {
return str_replace('"','""',$val);
//What about new lines in values? Perhaps not relevant to your
// data but they'll mess up your output ;)
}
function writeCSVLine($arr) {
$first=true;
foreach ($arr as $v) {
if (!$first) {echo ",";}
$first=false;
echo "\"".escapeCSVcell($v)."\"";
}
echo "\n"; // May want to use \r\n depending on consuming script
}
Now use writeCSVLine in place of fputcsv4.
Ran into this same issue. Stumbled upon this thread which does the same thing but hooks into the 'plugins_loaded' action and exports the CSV then. https://wordpress.stackexchange.com/questions/3480/how-can-i-force-a-file-download-in-the-wordpress-backend
Exporting the CSV early eliminates the risk of the headers already being modified before you get to them.

Getting an errno 2 when running a PHP script

Hope you help me... I've been at this for the past 2 days and have to admit that I'm stumped.
The OS I'm on is Ubuntu 9.10 Karmic.
I successfully installed and tested Mapserver. For my class project, I have a php script that I am using to create a layer see below....
The error I get when run the script on a cmd line prompt:
Warning: [MapServer Error]: msProcessProjection(): no system list, errno: 2
in /var/www/mapserverdocs/ms4w/apps/world/mapscripts/staticwms.php on line 16
Warning: Failed to open map file static.map in /var/www/mapserverdocs/ms4w/apps/world/mapscripts/staticwms.php on line 16
Fatal error: Call to a member function owsdispatch() on a non-object in /var/www/mapserverdocs/ms4w/apps/world/mapscripts/staticwms.php on line 18
PHP SCRIPT:
<?php
if (!extension_loaded("MapScript")) dl("php_mapscript");
$request = ms_newowsrequestobj();
foreach ($_GET as $k=>$v) {
$request->setParameter($k, $v);
}
$request->setParameter("VeRsIoN","1.0.0");
ms_ioinstallstdouttobuffer();
$oMap = ms_newMapobj("static.map");
$oMap->owsdispatch($request);
$contenttype = ms_iostripstdoutbuffercontenttype();
if ($contenttype == 'image/png') {
header('Content-type: image/png');
ms_iogetStdoutBufferBytes();
} else {
$buffer = ms_iogetstdoutbufferstring();
echo $buffer;
}
ms_ioresethandlers();
?>
I made the directory and files world wide rwx just to make sure it was not a permissions issue
Any help would be greatly appreciated!!
Thanks
Chris
As meagar said, the issue is probably that this line:
$oMap = ms_newMapobj("static.map");
is unable to find "static.map". The current working directory of PHP is very often not what you'd expect it to be. Try making the path be relative to the current script. If static.map is in the same directory as static.map, try this code:
$mapPath = dirname(__FILE__).'/static.map';
$oMap = ms_newMapobj($mapPath);
$oMap->owsdispatch($request);
if static.map is at, let's say, /var/www/mapserverdocs/ms4w/apps/world/mapfiles/static.map, then try:
$mapPath = dirname(__FILE__).'/../static.map';
$oMap = ms_newMapobj($mapPath);
$oMap->owsdispatch($request);
Notice the */../*static.map. dirname(__FILE__) will return the name of the directory of the PHP file you place that code in.

Categories