0

I am with a code where the user connects using his username and password and what I would like to do is that once he is logged in, he will see an alert message where it says:

"Welcome + username +"

I have tried to do it in this way but it is not possible:

<?php  if (isset($_SESSION['username'])) : ?>
    <script> alert ("Welcome" . <?php echo $_SESSION['username']; ?>)</script>

The alert appears but not with the message I want but with 'undefined'

However, if I don’t put an alert but only a message with the corresponding username, it appears correct:

    <?php  if (isset($_SESSION['username'])) : ?>
    <p>Welcome <strong><?php echo $_SESSION['username']; ?></strong></p>

Could you help me?

Thank you

galep
  • 80
  • 7
  • `alert('Welcome ');` – NoLifeKing Aug 01 '18 at 08:56
  • 1
    When debugging, don't skip from PHP to rendered output in the browser. Look at the JavaScript source code you are generating. Think about what it means. – Quentin Aug 01 '18 at 08:56
  • 1
    @NoLifeKing — Danger! You are failing to escape special characters which risks breaking the JS and XSS. – Quentin Aug 01 '18 at 08:56
  • @Quentin I know. I just made it lazy, to be more like OP had it. (Which is a bad call) – NoLifeKing Aug 01 '18 at 08:57
  • It should probably be like `alert('Welcome ');` – NoLifeKing Aug 01 '18 at 09:00
  • 1
    **Never** forget the charset param in the htmlentities function @NoLifeKing ... " encoding An optional argument defining the encoding used when converting characters. If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1. " Also incorrect charset encoding might cause encoding bypasses – Raymond Nijland Aug 01 '18 at 09:02
  • Thank you everyone! Now it works as I wanted to. – galep Aug 01 '18 at 09:03
  • @RaymondNijland I was not aware of that parameter actually. :) – NoLifeKing Aug 01 '18 at 09:03
  • "I was not aware of that parameter actually." @NoLifeKing Really it's a must know for PHP security – Raymond Nijland Aug 01 '18 at 09:05
  • @RaymondNijland Thanks for the info! – NoLifeKing Aug 01 '18 at 09:06

1 Answers1

1

You are using PHP concatenation operator inside your JavaScript, you should directly write the username string in the welcome string:

<script> alert("Welcome <?php echo $_SESSION['username']; ?>")</script>

To concatenate strings in JavaScript you should use +, but this is not useful in your case.
Also note that this won't be secured and you should sanitize the username to prevent XSS attacks.

AymDev
  • 6,626
  • 4
  • 29
  • 52