Removing empty lines with notepad++ causes T_Variable Syntax Error - php

Removing empty lines in Notepad++
As described in the thread above you are able to remove empty lines with notepad++. I did try those methods but I am always receiving weird T_Variable Syntax Errors (mostly in line 1-6). There definitely is no error in those lines and I can not see one anywhere.
It also happens when I manually delete the empty lines in some areas of the code (first 5 lines for example). I am guessing this is an encoding problem but also reencoding in UTF-8, Ascii etc. did not help.
Those lines were added when I used an online editor from a webhoster a couple of months ago (1 empty line between the lines that were there before).
I do not get it, maybe you do (thanks in advance!). The file is at http://lightningsoul.com/index.php
And here is the first block of code:
<?php
include("db/lg_db_login.php");
//require 'fb/facebook.php';
if (isset($_GET['c'])) { $content = $_GET['c']; }
else { $content = ""; }
if (isset($_GET['sc'])) { $subcontent = $_GET['sc']; }
else { $subcontent = ""; }
if (isset($_GET['setlang'])) { $setlang = $_GET['setlang']; }
else { $setlang = "eng"; }
$cat = $_GET['cat'];
// Check if Lightningsoul.de or .com
$findme = '.de';
$posde = strpos($thisurl, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($posde === false) {
$lang = "en";
} else {
$lang = "de";
}
include("db/pageturn_class.php");
$findStr = '/lightningsoulcom';
$isApp = strpos($thisurl, $findStr);
// Beachten Sie die Verwendung von ===. Ein einfacher Vergleich (==) liefert
// nicht das erwartete Ergebnis, da die Position von 'a' die nullte Stelle
// (also das erste Zeichen) ist
/*if ($isApp == false) {
$getStyle = "css/get_style.php";
} else {
$getStyle = "css/get_style_small.php";
} */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The problem was in line 181 where something (notepad++?!) must have changed
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
to
<meta http-equiv="content-type" content="text/html; charset=Windows-1250" />
That produced lots of errors as one would expect. I only found it by removing the head part by part.

Related

PHP mail sending empty mails

I'm similar to php and don't undestand what is the problem.
Sometimes php function send me empty messages like
Vanema nimi
Lapse nimi:
Linn:
Telefoninumber:
Email:
Sünnikuupäev:
Sõnumi tekst:
But it should be filled with values like this
Vanema nimi test
Lapse nimi: test
Linn: test
Telefoninumber: test
Email: test#test
Sünnikuupäev: 21313
Sõnumi tekst:test
Here is my php code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Обратная Связь</title>
</head>
<body>
<?php
if (isset($_POST['parent'])) {$parent = $_POST['parent'];}
if (isset($_POST['child'])) {$child = $_POST['child'];}
if (isset($_POST['contacts'])) {$contacts = $_POST['contacts'];}
if (isset($_POST['email'])) {$email = $_POST['email'];}
if (isset($_POST['bbd'])) {$bbd = $_POST['bbd'];}
if (isset($_POST['city'])) {$city = $_POST['city'];}
if (isset($_POST['mess'])) {$mess = $_POST['mess'];}
$to = "info#test.ee"; /*Укажите ваш адрес электоронной почты*/
$headers = "Content-type: text/plain; text/html; charset=utf-8";
$subject = "Kontakti Info";
$message = "Vanema nimi $parent \n Lapse nimi: $child \nLinn:
$city \nTelefoninumber: $contacts \nEmail: $email \nSünnikuupäev: $bbd \nSõnumi tekst: $mess";
$send = mail ($to, $subject, $message, $headers);
if ($send == 'true')
{
echo "<b>Спасибо за отправку вашего сообщения!<p>";
echo "<a href=index.php>Нажмите,</a> чтобы вернуться на главную страницу";
}
else
{
echo "<p><b>Ошибка. Сообщение не отправлено!";
}
?>
</body>
</html>
<?php
header('Location: https://test.ee/aitah.html ');
?>
Please give me advice what is wrong.
If your script is a form processor only, you could e.g. add if(empty($_POST)) { die('No form data!'); } to the top to prevent it from running, except in response to a form submission.
If you require all fields to be filled in, you will have to check each of them before you process your email. You could cram all of those issets into one monster if(isset(...) statement. However, there's a simpler and more readable way to do it. First, let's set up a couple of variables:
// Your required fields:
$fields = ['parent', 'child', 'contacts', 'email', 'bbd', 'city', 'mess'];
// Your data is collected here:
$data = [];
// Any errors are collected here:
$errors = [];
Then, we loop over the fields and if values exist, add to $data, otherwise we add an error note.
// Loop to check your required fields:
foreach($fields as $field) {
// If value exists, add to $data:
if(!empty($_POST[$field])) {
$data[$field] = $_POST[$field];
}
// Else add error:
else {
$errors[] = 'Missing field: ' . $field;
}
}
if(empty($errors)) {
// No errors, send your email
// You can use "Vanema nimi {$data['parent']}...",
// ... otherwise: extract($data) to use $parent etc.
}
else {
// You could report those errors, or redirect back to the form, or whatever.
}
If there are errors (= missing fields), e-mails won't be sent. As a bonus, you now have a reusable piece of code that you can use for other forms with similar functionality simply by modifying the $fields array. (Wrapping it into a function is a good idea if you do need to reuse it; don't copy-paste code. function x($post, $fields) { ... } for a basic helper function.)
Note that here we are using empty in place of isset. If a blank form is submitted, the fields are set (to empty strings ""). Also note that empty returns true for anything that equals false (ie. "", 0, false, null, []). (If "0" is an expected and acceptable value, be aware of its "emptiness"!) On the other hand, isset returns true for anything not null.
P.S. If your code above is the complete code, and your script simply processes the form data and redirects, then you don't really need the HTML wrapper at all. It will never be displayed.

Russian Characters in URL PHP

I have scoured the internet and I'm either not finding the answer or I'm unable to implement it correctly.
Basically I am trying to implement a website in Russian on PHP. I have already got the website in English and French but bringing a whole new range of characters in has sort of broken the test site. My actual goal is to have the Cyrillic characters in the URL, similar to how Wikipedia are able to do it > https://ru.wikipedia.org/wiki/Компьютер and also still find this in the database to show the correct location information.
In my SQL database I have a range of locations, countries such as France, Germany, Australia etc. I have set it up so that the location page is generated dynamically from those entries using the $data['Name'] variable. Now... in the header.php file I use this to generate the location names from the database for the navigation:
<li class="dropdown">
Места
<ul>
<?php if (is_array($locations)) {
foreach ($locations as $key => $location) {
$name = strtolower(str_ireplace(" ","-", $location['name']));
if ($location['top_location'] == 1)
echo '<li>'.$location['name'].'</li>';
}
}
?>
</ul>
</li>
Where $name is replaced by database entries. If I change one of the database entries to Russian (Australia for example - Австралия) then the location page throws a 404 error as it's actually trying to find location/%D0%90%D0%B2%D1%81%D1%82%D1%80%D0%B0%D0%BB%D0%B8%D1%8F rather than location/Австралия.
My location page has the following code to get information from the database:
<?php
include './inc/utils.php';
if (isset($_GET['id'])) {
$name = str_ireplace("-"," ", $_GET['id']);
$result = get_data("Locations", array("name" => $name))[0];
}
else
$result = null;
if ($result != null) {
$data['Name'] = $result['name'];
$data['Url_Name'] = $_GET['id'];
$data['Image'] = $result['image'];
$data['Slider_Text'] = $result['slider_text'];
$data['Description'] = $result['description'];
$data['Country'] = $result['top_location'] != 0 ? true : false;
$data['Cars_In_Location'] = get_cars_in_location($result['id']);
$img_url = $MASTER['car_img_url'];
$link_url = $MASTER['base_url'].'car/';
$cities_id = explode(",", $result['related']);
foreach ($cities_id as $value) {
$data['Related'][] = get_data("Locations", array("id" => $value))[0];
}
}
else {
$data['Name'] = "";
$data['Url_Name'] = "";
$data['Image'] = "";
$data['Slider_Text'] = "";
$data['Description'] = "";
$data['Country'] = false;
$data['Related'] = "";
$data['Cars_In_Location'] = "";
}
if (empty($data['Name']) == true) {
header('HTTP/1.1 404 Not Found');
header('Location: '.$MASTER['base_url'].'404.php');
}
include 'header.php';
?>
I have tried using urldecode to no avail. I think I am missing something either on the SQL side or in one of the function files.
my header.php file contains both
<meta http-equiv="Content-type" content="text/html; charset=utf-8" /> and
header('Content-Type: text/html; charset=utf-8');
as well as my location page containing
header('Content-Type: text/html; charset=utf-8');
my .htaccess file has
AddDefaultCharset UTF-8
I don't know what else I'm missing.
You can see the page here:
https://redfoxluxurycarhire.com/ru/location/Австралия
I am using print_r($host_url) to correctly print the URL despite what it shows so you can see my issue. I am also able to echo Австралия onto the location pages with no problems or encoding.
Any help would be much appreciated as I'm wracking my brain as how to get this to work!
I would start checking if you have any file-systems encoding problem. Check your scripts are using UTF-8, I believe your MySQL database is OK. You should be able to decode requests with urldecode.

Charset issue from local to remote server

I have a problem of charset.
On localhost everything works fine, but now on remote server I see strange characters replacing others like à or è. I have read it's a charset issue and I think the problem can be my php.ini (I can't edit it).
To solve it I've tried many things:
I've set
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
on html,
ini_set('default_charset', 'UTF-8');
on php,
AddDefaultCharset utf-8
on my .htaccess file,
if I use utf8_encode on strings letters are replaced by ã or similar, if I leave it without doing anything letters are �
There is another way to solve this problem that I have not found yet?
Sorry, I forgot to say it: strings are retrieved from another site by a file_get_contents (I'm using a Yandex API)
Here's some code:
$yandex = 'https://dictionary.yandex.net/api/v1/dicservice.json/lookup?key=my_api_key&lang=it-it&text=attualità';
// get json from this page
$object = json_decode(file_get_contents($yandex));
$syns_array = array();
$type = '';
// if the word exists
if (!empty($object->def) && $object->def != FALSE && $object->def != NULL)
{
$type = $object->def[0]->tr[0]->pos;
$rows = $object->def[0]->tr;
// if there're synonyms
if (!empty($rows) && $rows != FALSE && $rows != NULL)
{
foreach ($rows as $row)
{
array_push($syns_array, $row->text);
// if there're more rows with syns
if (!empty($row->syn) && $row->syn !== FALSE && $row->syn !== NULL)
{
foreach ($row->syn as $syns_obj)
{
array_push($syns_array, $syns_obj->text);
}
}
}
}
}
// I echo my synonyms from the array
foreach($syns_array as $syn) {
echo $syn;
}
I forgot to say I was using mb_strtolower on those strings. Replacing it with strotolower the problem is solved... Sorry

Not sure if strpos() is the right function to use

Am not sure if the strpos() is the right function to use for this
task.
PROBLEM:
if the user input hate or another string in my spam variable
it return the spam filter message which is correct, but if the user
input a spam variable mixed with any string not in the various it
passes for processing.
I want the input to to check from the first string to the last string
and that t doesn't contains any of the spam variable string then
return process, here is my code
<?php
//messgae
error_reporting(E_ALL ^ E_NOTICE);
$msg = array();
$spam = "hate partisan party kill maim murder violence love sex fight beat assasinate thug steal sell bribe protest baricade bullets militia fear ";
$spam_array = explode(" ",$spam);
$check = strpos($spam, $_POST['message']);
if ($check == true) {
//do nothing
$msg['invalid'] = 'Spam filter test didnt allow your message';
} else {
$msg['valid'] = 'process';
}
if(isset($_POST['send'])){
$message= $_POST['message'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Strpos</title>
</head>
<body>
<?php
if (isset($msg)) {
echo '<ul>';
foreach ($msg as $alert) {
echo "<li class='warning'>$alert</li>\n";
}
echo '</ul>';
}?>
<form action="" method="post">
<input name="message" type="text" />
<input name="send" type="submit" value="Submit" id="send" />
</form>
</body>
</html>
You started something there, with the $spam_array.
They you check it know, you check if the exact string of bad words are found in your message.
Also stripos instead of strpos so that it will be case insensitive.
$spam = "hate partisan party kill maim murder violence love sex fight beat assasinate thug steal sell bribe protest baricade bullets militia fear ";
$spam_array = explode(" ",$spam);
$isSpam = isSpam($_POST['message'], $spam_array);
function isSpam($content, $spamList)
{
foreach($spamList as $badWord) {
if(stripos($content, $badWord) !== false) {
return true;
}
}
return false;
}
You need to improve your check with word boundaries or you would have false positives for words like "gloves" (love) and "Essex" (sex). You should also make it case-insensitive.
The following approach (check function) uses a preg_match with word boundary metacharacters when looking for each "spam word" within the message. The i modifier also makes it case-insensitive:
function check($msg, $spam_array) {
foreach ($spam_array as $spam_word) {
if (preg_match("/\b" . $spam_word ."\b/i", $msg)) {
return false;
}
}
return true;
}
function test($msg, $spam_array) {
echo "$msg => ", check($msg, $spam_array) ? 'OK' : 'not OK', PHP_EOL;
}
$spam = "hate partisan party kill maim murder violence love sex fight beat "
. "assasinate thug steal sell bribe protest baricade bullets militia fear";
$spam_array = explode(" ", $spam);
test("I'm known for my cookie munching skills.", $spam_array);
test("I could kill for some cookies right now!", $spam_array);
Output:
I'm known for my cookie munching skills. => OK
I could kill for some cookies right now! => not OK

Debugging a php script

I am using textpad to create php scripts. Now is there anything I can use with textpad, or is there a way to debug with textpad. I am a few of my code echo out and I am still not getting the results I am wanting my page to do. So I am thinking my code needs some debugging. I will post the code below and I am sure many of you will agree it needs debugging too. I know alot of people are probally saying I should not use what I am using but this is what I am being tought to use.
<?php
function dbConnect(){
// Connect to the database
$hostname="localhost";
$database="tblFile";
$mysql_login="*****";
$mysql_password="*****";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
echo "I have successfully made a connection to my database and everything
is working as it should.";
}
}
$aryImages=array("image/jpeg","image/png");
$aryDocs=array("application/msword","application/pdf","video/x-msvideo");
$filename=filenameSafe($_FILES['upload']['name']);
$fileType=$_FILES["upload"]["type"];
if (in_array($_FILES["upload"]["type"],$aryImages)){
createThumb($fileType,$_FILES['upload']['tmp_name'],$filename,100,100);
}
elseif (in_array($_FILES["upload"]["type"],$aryDocs)){
move_uploaded_file($_FILES['upload']['tmp_name'],
"/home/valerie2/public_html/elinkswap/snorris/upload/".$filename);
$aryColumns=array("sessionID"=>$curSess,"fileName"=>$filename,"fileType"=>$fileType,"thumbFileName"=>$thumbFilename,"dateCreated"=>date('Y-m-d H:i:s'));
dbInsert($filename,$aryColumns,$_FILES["upload"]["type"]);
}
else{
echo "File Uploaded";
}
function createThumb($type,$tmpname,$filename,$new_w,$new_h){
$thumbFilename="tmb-".$filename;
echo $type;
echo "<br>".$tmpname;
if (is_numeric(strpos($type,"jpeg"))){
$src_img=imagecreatefromjpeg($tmpname);
}
if (is_numeric(strpos($type,"png"))){
$src_img=imagecreatefrompng($tmpname);
}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y) {
$thumb_w=$new_w;
$thumb_h=$new_h;
}
$dst_img=imagecreatetruecolor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if (is_numeric(strpos($type,"jpeg"))){
imagejpeg($dst_img,"/home/valerie2/public_html/elinkswap/imageupload/upload/".$thumbFilename);
imagejpeg($src_img,"/home/valerie2/public_html/elinkswap/imageupload/upload/".$filename);
}
if (is_numeric(strpos($type,"png"))){
imagepng($dst_img,"/home/valerie2/public_html/elinkswap/imageupload/upload/".$thumbFilename);
imagepng($src_img,"/home/valerie2/public_html/elinkswap/imageupload/upload/".$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
dbInsert($filename,$thumbFilename,$type);
}
function filenameSafe($filename)
{
// Lower case
$filename = strtolower($filename);
// get extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
// Replace spaces with a ’_’
$filename = str_replace(" ", "_", $filename);
// Replace non-alphanumerics (except underscores)
$filename = preg_replace('/\W/', '', $filename);
// append the timestamp
$filename = $filename . time();
// create an md5 hash
$result = md5($filename);
// ensure the string is safe for the db query
$result = mysql_real_escape_string($result);
dbConnect();
$SQL="SELECT fileId FROM tblFile WHERE fileName='".$result.".$ext'";
$rs = mysql_query($SQL);
if (mysql_num_rows($rs) > 0) {
$result = str_replace(".$ext", time(), $result);
$result = "$result.$ext";
}
return $result;
}
function dbInsert($filename,$thumbFilename,$type){
dbConnect();
$SQL="INSERT Into tblFile (fileName,thumbFileName,fileType) values('".$filename."','".$thumbFilename."','".$type."')";
//echo $SQL;
mysql_query($SQL);
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>File Upload</title>
<link href="styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
Select File: <input type="file" name="upload">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>
<input name="Submit" type="submit" value="Upload">
</form>
</html>
I have look up myself to see if there is anyway of debugging in textpad but I am getting nothing.
IMHO the easiest way to debug PHP with a non-PHP-IDE is establishing an external logfile.
In your .htaccess you can specify something like
php_value display_errors 1
php_value error_reporting 2147483647
php_value error_log /var/log/php/php_error.log
Make sure this file is writable for your webserver/php process.
Withing your code you can simply use the method error_log
to log stuff into your file.
I'm afraid you have to switch to a "bigger" IDE to be able to do some serius debugging. You must try Eclipse or NetBeans with Xdebug. If you do a Google search you will find lot of tutorial to setup a debugging environment with eclipse php xdebug or netbeans php xdebug.
If you need something very very simpler, but better than calling everytime an echo or a var_dump, you should try FirePHP with FirePHP extension for Firefox.
just by a simple copy paste in a editor with syntax highlight I saw that all the functions you wrote are in the dbConnect function and this doesn't look normal.
also, if you would indent your code it would be a lot easier to read it, so to spot problems. if your server has error reporting and error display on you should get some messages

Categories