Search code examples
phpimagettftext

imagettftext \\n line break puzzle PART 2


I previously asked why \n in a string was not returning a line break.

This was because the string needed to be in Double Quotes. (Thanks @Juhana !)

Now I am using GET so I can change the text string in the URL

$text = $_GET["msg"];

And the URL:

http://www.mywebsite.co.uk/image.php?msg=Something\nElse

Results in outputted text "Something\\nElse"
But what I want is a line break like this:
"Something
Else"

How come the text still has those two backslashes?
Am I wrong to think that because the "msg" is in Double Quotes it should create a line break?

thanks

EDIT full PHP code

<?php
// Set the content-type

header('Content-Type: image/png');

// Create the image
$im = imagecreatetruecolor(400, 100); //image big enough to display two lines

// Create some colors
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw

//$text = 'Testing\ntesting'; using SINGLE quotes like this results \\n
//$text = "Testing\ntesting"; using DOUBLE quotes like this results in line break

$text = $_GET["msg"];

// Replace path by your own font path
$font = 'arial.ttf';


// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

Solution

  • I think magic_quotes are ON on configuration. Thats why adds slash automatic when there special character like \ (backslash).

    if(get_magic_quotes_gpc())
        $text = stripslashes($_GET['msg']);
    else 
        $text = $_GET['msg'];
    

    But if you going to use these in live application, you need more validation for avoid security issues. If you sending text with special characters or html tags better use POST method or at least hash code and revese. Your url:

    http://url.com/image.php?msg=<?php echo base64_encode('your text\n test');>
    

    And in image.php

    $text = isset($_GET['msg']) ? $_GET['msg'] : 'default text';
    $text = base64_decode($_GET['msg']);