PHP's setrawcookie in TypeScript

How to use

Install via yarn add locutus and import: import { setrawcookie } from 'locutus/php/network/setrawcookie'.

Or with CommonJS: const { setrawcookie } = require('locutus/php/network/setrawcookie')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1setrawcookie('author_name', 'Kevin van Zonneveld')true

Notes

  • This function requires access to the window global and is Browser-only

Here's what our current TypeScript equivalent to PHP's setrawcookie looks like.

type CookieExpires = string | number | Date | null | undefined

export function setrawcookie(
name: string,
value: string,
expires?: CookieExpires,
path?: string | null,
domain?: string | null,
secure?: boolean,
): boolean {
// discuss at: https://locutus.io/php/setrawcookie/
// original by: Brett Zamir (https://brett-zamir.me)
// original by: setcookie
// improved by: Kevin van Zonneveld (https://kvz.io)
// input by: Michael
// note 1: This function requires access to the `window` global and is Browser-only
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// example 1: setrawcookie('author_name', 'Kevin van Zonneveld')
// returns 1: true

if (typeof window === 'undefined') {
return true
}

let normalizedExpires = expires

if (typeof normalizedExpires === 'string' && /^\d+$/.test(normalizedExpires)) {
normalizedExpires = parseInt(normalizedExpires, 10)
}

if (normalizedExpires instanceof Date) {
normalizedExpires = normalizedExpires.toUTCString()
} else if (typeof normalizedExpires === 'number') {
normalizedExpires = new Date(normalizedExpires * 1e3).toUTCString()
}

const parts = [name + '=' + value]
if (normalizedExpires) {
parts.push('expires=' + normalizedExpires)
}
if (path) {
parts.push('path=' + path)
}
if (domain) {
parts.push('domain=' + domain)
}

if (secure) {
parts.push('secure')
}

window.document.cookie = parts.join(';')

return true
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP network functions


Star