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);
Related
I'm looping through a directory, trying to find XML files with errors.
$baddies = array();
foreach (glob("fonts/*.svg") as $filename) {
libxml_use_internal_errors(true);
$str = file_get_contents($filename);
$sxe = simplexml_load_string($str);
$errors = libxml_get_errors();
$num_of_errors = 0;
$num_of_errors = sizeof($errors);
if ($num_of_errors > 0){
array_unshift($baddies, $filename);
}
}
However it seems that once the errors are put into this object, they persist there through subsequent iterations of the loop, and files without errors still test positive. $num_of_errors remains high for good files. I have it being reset to zero, and have even tried unseting it after each time through the loop. I suppose libxml_get_errors continues to retain a value once set. How can I reset it?
I think you should use libxml_clear_errors function. As per document here it says, the function keeps the errors stored in buffer.
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.
So I have a problem with a script I'm working on. I have a folder full of JSON files called roster0.json, roster1, etc. etc.
$dir = "responses/";
$files = glob($dir . "roster*");
$failed = array();
$failcnt = 0;
if (isset($files)) {
$data = null;
for ($i = 0; $i < count($files); $i++) {
$data = json_decode(utf8_decode(file_get_contents($files[$i])));
if(isset($data)){
// Process stuff
When I var_dump($files) I get an array with over 100 paths "responses/roster0.json".
When I test $data I get a proper array of data.
However, once the loop goes to the next file, it never loads it, and never processes it.
Here's the crazy part. If I change the start of the for loop, e.g. $i = 20. It will load the 21st file in the directory and parse it and insert it into the db properly!
Ignoring the failcnt stuff at the bottom, here's the current version of the script in it's entirety. http://pastebin.com/yqyKi5Ag
PS - I have full WARNING/ERROR reporting on in PHP and not getting any error messages...HELP! Thanks!
When I was writing the insert string the ID was being duplicated and thus was invalid. Switched to auto-inc and tada. It works. Thanks for the assistance. –
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.
I cannot find a way to get the user's home directory (e.g. /home/jack; whatever ~ in bash points to) in PHP using CGI (suPHP). The $_ENV array is empty, and getenv('HOME') returns nothing.
The reason I want to do this is that in absense of configuration saying otherwise, I want to find variable files used by my application in /home/user/.myappnamehere, as most Linux applications do.
I've built something, but it's not the best; While it works, it assumes a lot about the system (e.g. the presence of /etc/passwd)
$usr = get_current_user();
$passwd = file('/etc/passwd');
$var = false;
foreach ($passwd as $line) {
if (strstr($line, $usr) !== false) {
$parts = explode(':', $line);
$var = realpath($parts[5].'/.report');
break;
}
}
I think you want the result of either:
http://us.php.net/manual/en/function.getmyuid.php or
http://us.php.net/manual/en/function.posix-getuid.php sent to
http://us.php.net/manual/en/function.posix-getpwuid.php
If safemode is disabled, try this one
$homedir = `cd ~ && pwd`;