Is PHP uniqid safe for HTML id attribute?

I would like to use a random attribute id

in HTML:

<?php $id = uniqid(); ?>
<div data-cycle-prev="#<?php echo $id; ?>_slideshow_prev">
    <div id="<?php echo $id; ?>_slideshow_prev"></div>
</div>

      

I am using PHP method uniqid

to create it, but I don't know if it is safe and W3C compliant?

My concern about compliance is the generated HTML that PHP outputs. Not all characters are allowed in the HTML attribute, so I was wondering if it generates uniqid()

only valid characters.

+3


source to share


2 answers


uniqid

returns an id that contains hexadecimal characters (0-9, af). This is explained in the comments manually - http://php.net/manual/en/function.uniqid.php#95001



So yes, it is html attribute safe.

+2


source


Yes, it will save you money if you don't generate the ID twice, which is very inconvenient.

I would do it differently. Perhaps you want to present this in your library.

function getNextInt() {
    static $i = 0;
    $i++;
    return $i;
}

      

And in your template:



<?php $id = getNextInt(); ?>
<div data-cycle-prev="#<?php echo $id; ?>_slideshow_prev">
    <div id="<?php echo $id; ?>_slideshow_prev"></div>
</div>

      

If you are using legacy HTML versions, we must first have the letter as id (statet from @ mb21 in the comments):

<?php $id = 'mycontrol' . getNextInt(); ?>

      

+2


source







All Articles