How to Check If A Cookie Exists in PHP

Check if a cookie exists in PHP

To check if a cookie exists in PHP, you need to call the isset() function on the $_COOKIE array variable.

For example, suppose you want to check for a cookie named lang. You need to call the isset() function inside an if statement as shown below:

// πŸ‘‡ check if cookie exists
if (isset($_COOKIE["lang"])) {
    print "lang cookie value: " . $_COOKIE["lang"];
} else {
    print "lang cookie doesn't exists";

Keep in mind that a cookie can only be accessed after the page has been reloaded.

This is because cookies are sent as part of the header response when you request a page.

Checking for the cookie existence immediately after setting it with setcookie() will cause PHP to return undefined array key warning:

if (!isset($_COOKIE["lang"])) {
    setcookie("lang", "ja");

// πŸ‘‡ Warning: Undefined array key "lang"
// until next request
print $_COOKIE["lang"];


If you want to check for the cookie without reloading, then you need to call the setcookie() function and set the $_COOKIE value in the next line.

This way, you can use that cookie without a page reload:

if (!isset($_COOKIE["lang"])) {
    setcookie("lang", "ja");
    $_COOKIE["lang"] = "ja";

// πŸ‘‡ prints "ja"
print $_COOKIE["lang"];


By setting the $_COOKIE key-value pair manually, you tricked the code to think that the cookie is set.

But this may also introduce a bug since your code thinks that the user has the cookie in the first place.

As an alternative, you can add a fallback value as a variable instead:

if (!isset($_COOKIE["lang"])) {
    setcookie("lang", "ja");

$fallback_lang = "en";

// πŸ‘‡ if lang not set, prints fallback value
print isset($_COOKIE["lang"]) ? $_COOKIE["lang"] : $fallback_lang;

Using the ternary condition as shown above is considered the right approach because it doesn’t trick the code with a made-up cookie.

Now you’ve learned how to check if a cookie exists in PHP. Good job! πŸ‘

Original article source at:

#php #cookies 

What is GEEK

Buddha Community

How to Check If A Cookie Exists in PHP

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? has always been an industry leader for companies and business owners looking to hire PHP web developer. By choosing to Hire PHP Developer from our company, you can always expect the best results. Our PHP services and solutions are always flexible which means that no matter the nature of your project, you can always count on us for getting the best PHP expertise.

Consult with our experts:

#hire php developer #php developer #php development company #php development services #php development #php

Hire PHP Developer - Best PHP Web Frameworks for Web Development

A framework that can drastically cut down the requirement to write original code to develop the web apps as per your requirement is PHP Framework. PHP frameworks offer code libraries for commonly used functions to reduce the development time.

Want to use PHP Web Frameworks for your web applications?

WebClues Infotech offers a service to hire dedicated PHP developers for all of the below-mentioned frameworks

  • Laravel Developer
  • Codeigniter Developer
  • Yii Developer
  • Zend Developer
  • Cake PHP Developer
  • Core PHP Developer

Not sure which framework to use for your PHP web application?

Contact us

Schedule Interview with PHP Developer


#hire php developer #hire php web developers #hire php developer in 2021 #hire php developers & dedicated php programmers #hire php developers india #hire and outsource freelance php developers

5 Favorite PHP Libraries for File Manipulation and MIME Type Detection

In today's post we will learn about 5 Favorite PHP Libraries for File Manipulation and MIME Type Detection.

What is MIME type detection?

The most simple way to detect the MIME type of any file is to use MIME_Type's static autoDetect() method. It will try to determine the file's type and return it as a string. If an error occurs, a PEAR_Error object is returned. By default, only the plain MIME type will be returned, without any comments or parameters.

Table of contents:

  • CSV - A CSV data manipulation library.
  • Flysystem - Abstraction for local and remote filesystems.
  • Gaufrette - A filesystem abstraction layer.
  • PHP FFmpeg - A wrapper for the FFmpeg video library.
  • UnifiedArchive - A unified reader and writer of compressed archives.

1 - CSV:

A CSV data manipulation library.

Csv is a library to ease parsing, writing and filtering CSV in PHP. The library goal is to be powerful while remaining lightweight, by utilizing PHP native classes whenever possible.


  • Easy to use API
  • Read and Write to CSV documents in a memory efficient and scalable way
  • Support PHP stream filtering capabilities
  • Transform CSV documents into popular format (JSON, XML or HTML)
  • Fully documented
  • Fully unit tested
  • Framework-agnostic

System Requirements

You need the mbstring extension to use Csv and the latest stable version of PHP is recommended.

Please find below the PHP support for Csv version 9.

Min. Library VersionMin. PHP VersionMax. Supported PHP Version
9.0.0PHP 7.0.10PHP 7.1.x
9.1.2PHP 7.0.10PHP 7.2.x
9.2.0PHP 7.0.10PHP 7.4.x
9.6.0PHP 7.2.5PHP 7.4.x
9.6.2PHP 7.2.5PHP 8.0.x
9.7.0PHP 7.3.0PHP 8.0.x
9.7.3PHP 7.3.0PHP 8.1.x
9.8.0PHP 7.4.0PHP 8.1.x


Install Csv using Composer.

composer require league/csv


Warning: If your CSV document was created or is read on a Macintosh computer, add the following lines before using the library to help PHP detect line ending.

if (!ini_get("auto_detect_line_endings")) {
    ini_set("auto_detect_line_endings", '1');


The library has a :

To run the tests, run the following command from the project folder.

composer test

View on Github

2 - Flysystem:

Abstraction for local and remote filesystems.

Flysystem is a file storage library for PHP. It provides one interface to interact with many types of filesystems. When you use Flysystem, you're not only protected from vendor lock-in, you'll also have a consistent experience for which ever storage is right for you.

Getting Started

Officially supported adapters

Third party Adapters

You can always create an adapter yourself.


If you discover any security related issues, please email instead of using the issue tracker.

View on Github

3 - Gaufrette:

A filesystem abstraction layer.

Gaufrette provides a filesystem abstraction layer.

Why use Gaufrette?

Imagine you have to manage a lot of medias in a PHP project. Lets see how to take this situation in your advantage using Gaufrette.

The filesystem abstraction layer permits you to develop your application without the need to know where all those medias will be stored and how.

Another advantage of this is the possibility to update the files location without any impact on the code apart from the definition of your filesystem. In example, if your project grows up very fast and if your server reaches its limits, you can easily move your medias in an Amazon S3 server or any other solution.


Requires :

  • docker-ce
  • docker-compose

Create .env file :

$ make

and configure it as you want.

Build the php docker image :

$ make

Install dependencies :

$ make docker.all-deps

Run tests :

$ make docker.tests

You can also use a different php version, simply set the PHP_VERSION env var to any of these values when calling a make target :

See the docker-compose.yml file for more details.

You'll need to clear the previously installed dependencies when switching from a version to an other, to do so, run :

$ make clear-deps
$ PHP_VERSION=<the_version_you_want_to_use> make build install-deps

Apply Coding Standards

You should check for CS violations by using

$ make php-cs-compare

and fix them with

$ make php-cs-fix


This project does not have any stable release yet but we do not want to break BC now.

View on Github

4 - PHP FFmpeg:

A wrapper for the FFmpeg video library.

An Object-Oriented library to convert video/audio files with FFmpeg / AVConv.


This library requires PHP 8.0 or higher. For older versions of PHP, check out the 0.x-branch.

The recommended way to install PHP-FFMpeg is through Composer.

$ composer require php-ffmpeg/php-ffmpeg

Basic Usage

require 'vendor/autoload.php';

$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
    ->resize(new FFMpeg\Coordinate\Dimension(320, 240))
    ->save(new FFMpeg\Format\Video\X264(), 'export-x264.mp4')
    ->save(new FFMpeg\Format\Video\WMV(), 'export-wmv.wmv')
    ->save(new FFMpeg\Format\Video\WebM(), 'export-webm.webm');


This documentation is an introduction to discover the API. It's recommended to browse the source code as it is self-documented.


FFMpeg\FFMpeg is the main object to use to manipulate medias. To build it, use the static FFMpeg\FFMpeg::create:

$ffmpeg = FFMpeg\FFMpeg::create();

FFMpeg will autodetect ffmpeg and ffprobe binaries. If you want to give binary paths explicitly, you can pass an array as configuration. A Psr\Logger\LoggerInterface can also be passed to log binary executions.

$ffmpeg = FFMpeg\FFMpeg::create(array(
    'ffmpeg.binaries'  => '/opt/local/ffmpeg/bin/ffmpeg',
    'ffprobe.binaries' => '/opt/local/ffmpeg/bin/ffprobe',
    'timeout'          => 3600, // The timeout for the underlying process
    'ffmpeg.threads'   => 12,   // The number of threads that FFMpeg should use
), $logger);

You may pass a temporary_directory key to specify a path for temporary files.

$ffmpeg = FFMpeg\FFMpeg::create(array(
    'temporary_directory' => '/var/ffmpeg-tmp'
), $logger);

Manipulate media

FFMpeg\FFMpeg creates media based on URIs. URIs could be either a pointer to a local filesystem resource, an HTTP resource or any resource supported by FFmpeg.

Note: To list all supported resource type of your FFmpeg build, use the -protocols command:

ffmpeg -protocols

To open a resource, use the FFMpeg\FFMpeg::open method.


Two types of media can be resolved: FFMpeg\Media\Audio and FFMpeg\Media\Video. A third type, FFMpeg\Media\Frame, is available through videos.

View on Github

5 - UnifiedArchive:

A unified reader and writer of compressed archives.

How it works

UnifiedArchive uses "drivers", which can be one of types:

  1. PHP Extensions
  2. Utilities + bridge
  3. Pure PHP

By default, UA goes top-down to select first available driver for passed archive. So, PHP Extension driver will be used (if available), then Utilities + bridge driver (if available), and then Pure PHP driver.

There is at least one driver in all three types, which handles zip format, so this format can be fully supported in any OS/PHP configuration:

  1. zip / phar PHP extensions
  2. Utility + bridge SevenZip / AlchemyZippy
  3. Pure NelexaZip

tar format (with compressed variants) supported by:

  1. phar PHP extension
  2. Utility + bridge SevenZip / AlchemyZippy
  3. Pure TarByPear

So, there is always one driver that supports popular formats, and you should not remember how to work with this concrete driver (zip/phar/SevenZip/AlchemyZippy/NelexaZip), interface for them is uniform.

Quick start

Installation and configuration

Install library

composer require wapmorgan/unified-archive
#Check supported formats with installed drivers
./vendor/bin/cam system:formats
#Check supported functions for zip format
./vendor/bin/cam system:format zip

Install new driver

#Read installation instructions from
./vendor/bin/cam system:drivers
#install missing drivers, for example pear/archive_tar
composer require pear/archive_tar
#check out driver functions
./vendor/bin/cam system:formats TarByPear

#if needed, install extensions, cli tools and php libraries
#to enable support of other formats


use \wapmorgan\UnifiedArchive\UnifiedArchive;

$output_dir = '/var/www/extracted';

# Extraction
$archive = UnifiedArchive::open(''); // archive.rar, archive.tar.bz2

if (disk_free_space($output_dir) < $archive->getOriginalSize()) {
    throw new \RuntimeException('No needed space available. Need ' . ($archive->getOriginalSize() - disk_free_space($output_dir)) . ' byte(s) more');

$extracted = $archive->extract($output_dir);
echo 'Number of extracted files' . $extracted.PHP_EOL;

# Archiving
    '' => '/default/path/to/',
    '' => '/folder/with/content/',
], '');

View on Github

Thank you for following this article.

Related videos:

How to Open ZIP Files With PHP

#php #file #type #detection 

Mariya James

Mariya James


Top PHP web development company| PHP development services India

ValueCoders is a leading PHP app development company that focuses on building robust, secure & scalable web applications for start-ups, enterprises, and entrepreneurs.

We have 16+ years of experience and have delivered custom PHP web development solutions to 2500+ global clients catering industry verticals, including healthcare, adtech, eLearning, data analysis, Fintech, eCommerce, etc

Are you planning to outsource PHP development services? Or want to hire an offshore PHP development team?

#hire php developer #hire a php developer in india #hire dedicated php programmers #hire php coders #php developer in india #php developers for hire

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers?

Hire Dedicated PHP Developer, who can convert your idea to reality, within the stipulated time frame. expertise & experience as the top PHP development company put us above our competitors, in many ways. We have some of the top PHP developers in the industry, which can create anything you can imagine, that too, at the most competitive prices.

Consult with our experts:-

#hire dedicated php developer #php developers #php development company #php development services #php development #php developer