PHP: codecomments inside functions prevents it work - php

$query = $connect->prepare("SELECT firstname, lastname FROM users WHERE id = '$id'");
$query->execute();
$row = $query->fetch();
// $full_name = $row["firstname"] . " ".$row["lastname"];
$full_name = $row["firstname"] . " ".substr($row["lastname"], 0, 1).".";
return $full_name;
If i remove the line that is a comment ( // ), it will return $full_name, if its there then it wont work. I also tried commenting with #, but it still wont work(wont return anything) as soon as there is a codecomment
weird issue

The only thing I can think if it's really the code: check the newline character settings in your editor or try to open it in another editor. Maybe the php parser see it in one line.
But I dont think so.

It has never happend to me.. very strange.
Try to add some text after // or put everything between this another kind of comment a code
/* the code */

Your comment shouldn't have any effect on the execution.
Have you tried turning on all the error handling? What are the contents for var_dump($row); ?

Try to detect strange invisible characters. On linux I do it with "cat -e file.php".
For all the strange-syntax-errors-because-of-one-line-in-file I try it.
Another way to test it. Remove all the lines between your $row =... and $full_name =... and then redo your commented line (no paste, re-type it).

This should be basic debugging (as well as a literal sanity check), however I'll post it as an answer; First of all turn all errors on, then:
echo 'before: ' . $full_name;
// $full_name = $row["firstname"] . " ".$row["lastname"];
echo 'after' . $full_name;
I do realise this is insane! A comment is a comment and will never have any effect on your output.
Both echos should trigger a warning since there is no $full_name variable defined yet; However, if both are printed you'll know (as we all know) the problem isn't the comment itself... (At this point, my guess is that $full_name = " "; because $query->fetch(); returned false...)
Now if none of those echos executed: Are you sure you're calling the exact same function? Didn't you misspelled it or something and happen to have errors off??

Related

Sanitize input yields a blank safe string

I have a database built and working for my music collection. I have built an entry page that only I have access to. Obviously when I have a title or artist with an apostrophe the entry fails. I've been reading and I found this syntax on a page on this site. However when I try to execute it the 'safe' stringer comes out blank.
This is the part of the code that doesn't work. I'm sure it's something stupid I've done. If anyone can point out the error of my ways I'd greatly appreciate it.
$artist=$_POST['artist'];
echo $artist . "<br>";
$safeartist = mysqli_real_escape_string($artist);
echo $safeartist . "<br>";
$title=$_POST['title'];
$safetitle = mysql_real_escape_string($title);
echo $safetitle . "<br>";
It does in fact have the data in the 'echo artist' command but does not for the second echo.
If you are trying to print the string in the DOM it might be that you are looking for htmlentities
http://www.php.net/htmlentities
mysql_* is deprecated PDO is often a more reasonable choice http://php.net/PDO

php URL encoding error

I have the following line in my code
$lib = simplexml_load_file("http://www.goodreads.com/book/title.xml?key=MYAPIKEY&title=" . $current_book,null,true);
when this is sent, it is sent like this
http://www.goodreads.com/book/title.xml?key=MYAPIKEY&title=Dashing%2BThrough%2Bthe%2BSnow%2BMary%2BHiggins%2BClark%0A
When this happens, the book is not found and an error is returned . . .
However, if i type into my browser
http://www.goodreads.com/book/title.xml?key=MYAPIKEY&title=Dashing+Through+the+Snow+Mary+Higgins+Clark
Then i get a valid XML response, and i can use this to complete my code.
So, how do i send this without the + getting changed to %2B ?
And what is the %0A at the end of the URL?
Your url seems to be encoded twice.
Since you are not encoding at all in the code you show (by the way that would be the proper place to do that) it must have happened before.
The error is not in this code but somewhere before that.
You could correct it like this:
$lib = simplexml_load_file("http://www.goodreads.com/book/title.xml?key=MYAPIKEY&title=" . trim(urldecode($current_book)),null,true);
However that is only a workaround for an existing error, you should fix the prior encoding.
Also the character you mention is a newline character, thats the reason for trim

New Line Character in PHP script on Remote Server not working

I am having trouble with "\n" character not working. I realized that it wasn't work while testing output of variables using a simple echo statement. I have tried approaching the new line character a few different ways to see if it was just me, but nothing I have tried is working. Here is an example of some attempts I have made:
<?php
// Establish Connection to Taskaro DB
require "../_connections/connection_taskDB.php";
// Start Session
session_start();
// Create Session Variables
$_SESSION['userID'];
$_SESSION['companyID'];
$_SESSION['usernameDB'];
// Convert Session Variables to page variables
$userID = $_SESSION['userID'];
$currentUser = $_SESSION['usernameDB'];
$editType = $_REQUEST['editType'];
$projectID = $_REQUEST['projectID'];
// Testing if new line character is working
echo "hello, Mr. New Line!\n\r";
echo "This line should be below 'hello, Mr. New Line!'";
// Testing variable and session connection
echo "SESSION VARIABLES:"."\\n\n"."userID = {$userID}";
echo "userID = {$userID}"."/n";
echo "currentUser = {$currentUser}"."\r";
echo "companyID = {$companyID}\n\r";
echo "\nPOST VARIABLES:\n";
echo "editType = {$editType}\n";
echo "projectID = {$projectID}\n";
?>
I read up on some other overflow questions that had similar problems and none of them fixed my problem. The project is on a remote server (GoDaddy) in which php has been installed. The document has the correct file extension (.php). I am coding in dreamweaver and uploading my script for testing. From the code you can see I've tried "\n","\n\r","\r". I've also tested in both Firefox and Google Chrome.
I also tried to concatenate the "\n" character, and took a shot in the dark and even tried using the forward slash rather than the backslash (I knew it wouldn't work, but I'm getting pretty frustrated at this point). I bet it's something simple but I don't see what else is could be. Thanks in advanced.
If you view the source of the page, you will see all of those values output on separate lines.
If you are viewing the file in the browser, you need to use line breaks (<br />) if you want your text to show up on different lines. HTML ignores newlines in regards to presentation.
echo "hello, Mr. New Line!\n";
echo "This line should be below 'hello, Mr. New Line!'";
When viewing source, the above two text strings will be on separate lines. When viewed in the browser they will appear to be on the same line.
echo "hello, Mr. New Line!\n<br />";
echo "This line should be below 'hello, Mr. New Line!'";
When viewing source, the above two text strings will be on separate lines because of the \n. When viewed in the browser they will also be on separate lines because of the HTML break <br />.
Use the PHP_EOL constant instead of \n and call it a day.
Also, it's \r\n, not the other way around.
If you are expecting the browser to render new line characters as new lines in HTML, that won't happen. You need to use the <br> tag.

PHP $_POST username sanitation - how that this is not ok

I've googled and searched SO and everything, but I can't come to an answer.
Why is the PHP code below letting plus sign through:
$aValid = array('-', '_', '.');
if (ctype_alnum(str_replace($aValid, '', $_POST['Rusername']))){
(If user types 1234+ it goes on like it vas valid????).
I, normally, found a bypass, but is it really necessary;
$aValid = array('-', '_', '.');
if (ctype_alnum(str_replace($aValid, '', (htmlentities ( trim ( $_POST['Rusername'] ) , ENT_NOQUOTES ))))){
echo "+ ok";
}else{
echo "+ not ok";
}
I would like to use this kind of validation and just add special chars to $aValid when needed.
Before inserting to MySQL I would do mysql_real_escape_string or prepared statements.
Any ideas why the + sign is ok for first piece of code. In my opinion it really should't be.
Latest update - I needed few hours of low-level debugging HTTP headers to figure iz out that my A side changed the Content-Type so that the + sign became space before it got to PHP if clause (alowed in my whitelist)...
What an - I hope it will never happen to you - experience :)
Reminder to myself: jQuery should be mentioned if it was such a major player in this validation process...
What you should do is inspect each stage of the process, rather than slamming them all into a single line:
$name = $_POST['Rusername'];
var_dump($name);
$name = str_replace($aValid, '', $name);
var_dump($name);
etc... Basic debugging. If you've got multiple stages in a statement, then check each individual stage. ctype may be working perfectly fine, but the str_replace is failing you somehow.
Any ideas why the + sign is ok for first piece of code. In my opinion it really should't be.
It's not ok... the first piece of code return false..
If you want to remove the + sign you have to add it into the $aValid variable

redirecting using urlencode problem

Am trying to pass the value hrough the URL but when i retrieve it it appears like this ' , urlencode(15.99),'
the value is correct but i have tried different things but still unable to just send the value without the urlencode or added syntax
the line of code am trying to send the value is
redirect_to("$the_file_is?subj=' . urlencode($the_price_is)' ");
This should do what you're looking for, assuming I understood it correctly:
redirect_to($the_file_is . '?subj=' . urlencode($the_price_is));
Surely just change to...
redirect_to($the_file_is."?subj=" . urlencode($the_price_is));
Almost there - just a little bit of quote confusion :)
redirect_to("$the_file_is?subj=" . urlencode($the_price_is));
It's worth noting that you can reference variables in double quotes so:
echo "hello $name"; will work, but echo "$actioned"; might need to be echo "{$action}ed"; echo $action.'ed'; depending.

Categories