Skip to content

Commit

Permalink
Added methods for cookie management.
Browse files Browse the repository at this point in the history
  • Loading branch information
muhammetsafak committed Jul 1, 2022
1 parent b181e06 commit 7d20341
Show file tree
Hide file tree
Showing 2 changed files with 146 additions and 24 deletions.
92 changes: 75 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ use \InitPHP\Curl\Curl;

$curl = new Curl();
$curl->setUrl("https://example.com");
$curl->prepare()
->handler();
$curl->handler();

$res = $this->getResponse();

Expand All @@ -40,17 +39,14 @@ This library can be used as HTTP client for your API service. Example:
require_once "vendor/autoload.php";
use \InitPHP\Curl\Curl;

$curl = new Curl();
$curl = Curl::client('PUT', 'http://api.service.example.com/update/1')

$curl->setUrl("http://api.service.example.com/update/1")
->setMethod("PUT") // HTTP Request METHOD
->setVersion("1.1") // HTTP Version
$curl->setVersion("1.1") // HTTP Version
->setHeader("Content-Type", "application/json")
->setBody(json_encode([
'username' => 'admin',
'password' => '12345',
]))
->prepare()
->handler();

if(!empty($curl->getError())){
Expand All @@ -74,6 +70,14 @@ switch ($curl->getResponse('code')) {

## Methods

### `client()`

Creates a new client object.

```php
public static function client(string $method, string $url): \InitPHP\Curl\Curl;
```

### `getResponse()`

Returns the result of the curl operation.
Expand Down Expand Up @@ -284,7 +288,7 @@ public function getError(): null|string
It is the `curl_setopt()` function in this library.

```php
public function setOpt($key, $value): self
public function setOpt(int $key, mixed $value): self
```

### `setOptions()`
Expand All @@ -295,14 +299,6 @@ It is the `curl_setopt_array()` function in this library.
public function setOptions(array $options): self
```

### `prepare()`

cURL prepares the library for initialization.

```php
public function prepare(): self
```

### `handler()`

cURL starts and executes.
Expand All @@ -327,14 +323,76 @@ Returns the number of bytes written on success.
/** @var \InitPHP\Curl\Curl $curl */
$curl = new \InitPHP\Curl\Curl();
$curl->setUrl("http://example.com")
->prepare()
->handler();

if($curl->save(__DIR__ . '/example.html') === FALSE){
echo "The file could not be written.";
}
```

### `setCookie()`

Defines a cookie to be sent with cURL.

```php
public function setCookie(string $name, string|int|float $value): self
```

**Example :**

```php
/** @var \InitPHP\Curl\Curl $curl */
$curl->setCookie('username', 'admin') // $_COOKIE['username']
->setCookie('mail', '[email protected]'); // $_COOKIE['mail']
```

### `setCookies()`

Defines cookies as multiple with an associative array.

```php
public function setCookies(array $cookies): self
```

**Example :**

```php
/** @var \InitPHP\Curl\Curl $curl */
$curl->setCookies([
'username' => 'admin', // $_COOKIE['username']
'mail' => '[email protected]' // $_COOKIE['mail']
]);
```

### `setCookieJarFile()`

It tells the file path where the cookies values to be sent to the server will be kept or kept.

```php
public function setCookieJarFile(string $filePath): self
```

If the specified file exists, cookies are read from the file and sent to the server. `CURLOPT_COOKIEFILE`

If the specified file does not exist, cookies from the server are written to the file. `CURLOPT_COOKIEJAR`

**Example :**

```php
$login = new \InitPHP\Curl\Curl();
$login->setUrl("http://example.com/user/login")
->setField('username', 'admin')
->setField('password', '123456')
->setMethod('POST')
->setCookieJarFile(__DIR__ . '/session.txt')
->handler();

$dashboard = new \InitPHP\Curl\Curl();
$dashboard->setUrl("http://example.com/user/dashboard")
->setCookieJarFile(__DIR__ . '/session.txt')
->handler();
```

## Credits

- [Muhammet ŞAFAK](https://www.muhammetsafak.com.tr) <<[email protected]>>
Expand Down
78 changes: 71 additions & 7 deletions src/Curl.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ class Curl

protected array $fields = [];

protected array $cookies = [];

protected bool $canFollow = false;

protected bool $allowRedirects = false;
Expand Down Expand Up @@ -88,6 +90,33 @@ public function __debugInfo()
];
}

public static function client(string $method, string $url): Curl
{
$client = new self();
$client->setMethod($method)
->setUrl($url);
return $client;
}

public static function get(string $method, string $url, array $headers = [], ?string $body = null, string $version = '1.1'): array
{
$curl = self::client($method, $url)
->setVersion($version);
if(!empty($headers)){
$curl->setHeaders($headers);
}
if(!empty($body)){
$curl->setBody($body);
}
if(!$curl->handler()){
return [
'error' => (!empty($curl->getError()) ? $curl->getError() : 'Something went wrong.'),
'info' => $curl->getInfo()
];
}
return $curl->getResponse();
}

public function setUrl(string $url): self
{
if(\filter_var($url, \FILTER_VALIDATE_URL) === FALSE){
Expand Down Expand Up @@ -212,6 +241,40 @@ public function setUpload(string $name, \CURLFile $file): self
return $this;
}

/**
* @param string $name
* @param string|int|float $value
* @return $this
*/
public function setCookie(string $name, $value): self
{
if(!\is_string($value) && !\is_numeric($value)){
throw new \InvalidArgumentException("Defined '" . $name . "' cookie value can only be string or numeric.");
}
$name = \trim($name);
$value = \trim((string)$value);
$this->cookies[$name] = $value;
return $this;
}

public function setCookies(array $cookies): self
{
foreach ($cookies as $key => $value) {
$this->setCookie((string)$key, $value);
}
return $this;
}

public function setCookieJarFile(string $filePath): self
{
if(!\is_file($filePath)){
$this->addCurlOption(\CURLOPT_COOKIEJAR, $filePath);
}else{
$this->addCurlOption(\CURLOPT_COOKIEFILE, $filePath);
}
return $this;
}

/**
* @param null|string $key
* @return null|mixed
Expand Down Expand Up @@ -274,14 +337,9 @@ public function setOptions(array $options): self
return $this;
}

public function prepare(): self
{
$this->curlOptionsPrepare();
return $this;
}

public function handler(): bool
{
$this->curlOptionsPrepare();
$this->curl = \curl_init();
try {
if(!empty($this->options)){
Expand Down Expand Up @@ -335,7 +393,13 @@ private function curlOptionsPrepare(): void
if(!empty($this->referer)){
$this->addCurlOption(\CURLOPT_REFERER, $this->referer);
}

if(!empty($this->cookies)){
$cookies = [];
foreach ($this->cookies as $key => $value) {
$cookies[$key] = $key . '=' . $value;
}
$this->addCurlOption(\CURLOPT_COOKIE, \implode('; ', $cookies));
}
switch ($this->version) {
case '1.0':
$version = \CURL_HTTP_VERSION_1_0;
Expand Down

0 comments on commit 7d20341

Please sign in to comment.