PHP code example of iviphp / http
1. Go to this page and download the library: Download iviphp/http library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
iviphp / http example snippets
declare(strict_types=1);
use Ivi\Http\Request;
$request = new Request(
method: 'POST',
uri: '/users?page=2',
headers: [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer secret-token',
],
query: [
'page' => 2,
],
rawBody: '{"name":"Gaspard"}'
);
declare(strict_types=1);
use Ivi\Http\Request;
$request = Request::fromGlobals();
$request = Request::fromGlobals(
server: [
'REQUEST_METHOD' => 'POST',
'REQUEST_URI' => '/products',
'CONTENT_TYPE' => 'application/json',
],
query: [],
post: [],
cookies: [],
files: [],
rawBody: '{"name":"Keyboard"}'
);
$method = $request->method();
$uri = $request->uri();
$path = $request->path();
$queryString = $request->queryString();
if ($request->isMethod('POST')) {
// Handle the POST request.
}
$contentType = $request->header('Content-Type');
$values = $request->headerValues('Accept');
$exists = $request->hasHeader('Authorization');
$headers = $request->headers();
$request->header('content-type');
$request->header('Content-Type');
$request->header('CONTENT-TYPE');
$contentType = $request->contentType();
if ($request->isJson()) {
// The request uses application/json or a +json media type.
}
$token = $request->bearerToken();
$page = $request->query('page', 1);
$filters = $request->query('filters');
$category = $request->query(
'filters.category'
);
if ($request->hasQuery('page')) {
// The query key exists.
}
$allQueryParameters = $request->queryParameters();
$body = $request->parsedBody();
$name = $request->bodyParameter('name');
$email = $request->bodyParameter(
'user.email',
'[email protected] '
);
$data = $request->json();
$name = $request->json('name');
$email = $request->json(
'user.email',
null
);
if ($request->isJson()) {
$data = $request->json();
}
$input = $request->allInput();
$name = $request->input('name');
$page = $request->input('page', 1);
if ($request->hasInput('email')) {
// The input key exists.
}
$sessionId = $request->cookie('session_id');
if ($request->hasCookie('preferences')) {
// The cookie exists.
}
$cookies = $request->cookies();
$remoteAddress = $request->server('REMOTE_ADDR');
$server = $request->serverParameters();
$isSecure = $request->isSecure();
$request = $request->withAttribute(
'user_id',
42
);
$userId = $request->attribute('user_id');
if ($request->hasAttribute('user_id')) {
// The attribute exists.
}
$request = $request->withoutAttribute('user_id');
$updated = $request
->withMethod('PUT')
->withUri('/users/42')
->withHeader('Accept', 'application/json');
use Ivi\Http\UploadedFile;
$file = $request->file('avatar');
if ($file instanceof UploadedFile) {
// Handle the uploaded file.
}
if ($request->hasFile('avatar')) {
$file = $request->file('avatar');
}
$files = $request->file('documents');
use Ivi\Http\UploadedFile;
$file = UploadedFile::fromArray([
'tmp_name' => '/tmp/php-upload',
'name' => 'photo.jpg',
'type' => 'image/jpeg',
'size' => 245760,
'error' => UPLOAD_ERR_OK,
]);
$file = UploadedFile::fromPath(
__DIR__ . '/fixtures/photo.jpg'
);
if (!$file->isValid()) {
throw new RuntimeException(
$file->errorMessage()
);
}
$originalName = $file->clientFilename();
$safeName = $file->safeClientFilename();
$safeName = $file->safeClientFilename(
'uploaded-file'
);
$extension = $file->clientExtension();
$clientType = $file->clientMediaType();
$detectedType = $file->mediaType();
$file->assertMediaType([
'image/jpeg',
'image/png',
'image/webp',
]);
$file->assertMediaType([
'image/*',
]);
$size = $file->size();
$declaredSize = $file->declaredSize();
$file->assertMaximumSize(
5 * 1024 * 1024
);
$checksum = $file->checksum();
$checksum = $file->checksum('sha512');
$stream = $file->openStream();
try {
while (!feof($stream)) {
$chunk = fread($stream, 8192);
if ($chunk === false) {
throw new RuntimeException(
'Unable to read uploaded file.'
);
}
// Process the chunk.
}
} finally {
fclose($stream);
}
$destination = __DIR__
. '/storage/uploads/'
. $file->safeClientFilename();
$file->moveTo($destination);
$file->moveTo(
destination: $destination,
overwrite: true
);
$file->moveTo(
destination: $destination,
permissions: 0640
);
$file->hasMoved();
$file->movedPath();
$file->path();
$file->compressTo(
__DIR__ . '/storage/uploads/data.json.gz'
);
$file->compressTo(
destination: __DIR__ . '/storage/uploads/data.json.gz',
level: 6
);
$file->compressTo(
destination: __DIR__ . '/storage/uploads/data.json.gz',
level: 6,
overwrite: true
);
$file = $request->file('document');
if (!$file instanceof UploadedFile) {
throw new RuntimeException(
'A document upload is 10 * 1024 * 1024
);
$file->assertMediaType([
'application/pdf',
]);
$storageName = bin2hex(
random_bytes(16)
) . '.pdf';
$file->moveTo(
__DIR__ . '/storage/documents/' . $storageName,
permissions: 0640
);
use Ivi\Http\Headers;
$headers = new Headers([
'Content-Type' => 'application/json',
'X-Request-Id' => 'request-123',
]);
$contentType = $headers->get('Content-Type');
$values = $headers->getAll('Set-Cookie');
$exists = $headers->has('X-Request-Id');
$headers->set(
'Cache-Control',
'no-store'
);
$headers->add(
'Set-Cookie',
'theme=dark; Path=/'
);
$headers->remove('X-Request-Id');
$all = $headers->all();
$flattened = $headers->flatten();
$updated = $headers->with(
'Content-Type',
'text/plain'
);
$withoutCache = $updated->without(
'Cache-Control'
);
declare(strict_types=1);
use Ivi\Http\Response;
$response = new Response(
body: 'Hello',
statusCode: 200,
headers: [
'Content-Type' => 'text/plain; charset=UTF-8',
]
);
$response = Response::text(
'Hello from IviPHP'
);
$response = Response::text(
'Resource created',
201
);
$response = Response::html(
'<h1>Welcome</h1>'
);
$response = Response::json([
'success' => true,
'data' => [
'id' => 42,
'name' => 'Product',
],
]);
$response = Response::json(
[
'message' => 'Product created.',
],
201
);
$response = Response::redirect(
'/dashboard'
);
$response = Response::redirect(
'/new-location',
301
);
$response = Response::redirect(
'/maintenance',
307
);
$response = Response::noContent();
$response = Response::empty(204);
$status = $response->statusCode();
$reason = $response->reasonPhrase();
$body = $response->body();
$length = $response->bodyLength();
$contentType = $response->contentType();
$headers = $response->headers();
$response->isInformational();
$response->isSuccessful();
$response->isRedirect();
$response->isClientError();
$response->isServerError();
$response->isError();
$response->isEmpty();
$updated = $response
->withStatus(201)
->withHeader('X-Request-Id', 'request-123')
->withAddedHeader('Set-Cookie', 'theme=dark; Path=/')
->withContentLength();
$updated = $response->withBody(
'Updated response'
);
$updated = $response->withoutHeader(
'X-Internal-Header'
);
$response
->withContentLength()
->send();
$response->send(
sendBody: false
);
use Ivi\Http\Exceptions\HttpException;
throw new HttpException(
statusCode: 400,
message: 'The request is invalid.'
);
throw HttpException::badRequest();
throw HttpException::unauthorized(
challenge: 'Bearer'
);
throw HttpException::forbidden();
throw HttpException::notFound();
throw HttpException::conflict();
throw HttpException::contentTooLarge();
throw HttpException::unsupportedMediaType();
throw HttpException::unprocessable();
throw HttpException::internalServerError();
throw HttpException::methodNotAllowed([
'GET',
'POST',
]);
throw HttpException::tooManyRequests(
retryAfter: 60
);
throw HttpException::serviceUnavailable(
retryAfter: 120
);
$exception = HttpException::methodNotAllowed([
'GET',
'POST',
]);
$allow = $exception->header('Allow');
throw HttpException::notFound(
message: 'The product was not found.',
context: [
'product_id' => 42,
'request_id' => 'request-123',
]
);
$context = $exception->context();
try {
throw HttpException::notFound();
} catch (HttpException $exception) {
$response = Response::json(
[
'error' => [
'status' => $exception->statusCode(),
'message' => $exception->getMessage(),
],
],
$exception->statusCode(),
$exception->headers()
);
}
$headers->has($name);
$headers->get($name, $default);
$headers->getAll($name);
$headers->set($name, $value);
$headers->add($name, $value);
$headers->remove($name);
$headers->all();
$headers->flatten();
$headers->clear();
$headers->with($name, $value);
$headers->without($name);
Request::fromGlobals();
$request->method();
$request->isMethod($method);
$request->uri();
$request->path();
$request->queryString();
$request->headers();
$request->hasHeader($name);
$request->header($name, $default);
$request->headerValues($name);
$request->contentType();
$request->isJson();
$request->contentLength();
$request->bearerToken();
$request->queryParameters();
$request->query($key, $default);
$request->hasQuery($key);
$request->parsedBody();
$request->bodyParameter($key, $default);
$request->rawBody();
$request->json($key, $default);
$request->allInput();
$request->input($key, $default);
$request->hasInput($key);
$request->cookies();
$request->cookie($name, $default);
$request->hasCookie($name);
$request->uploadedFiles();
$request->file($key);
$request->hasFile($key);
$request->serverParameters();
$request->server($key, $default);
$request->isSecure();
$request->attributes();
$request->attribute($name, $default);
$request->hasAttribute($name);
$request->withMethod($method);
$request->withUri($uri);
$request->withHeader($name, $value);
$request->withoutHeader($name);
$request->withParsedBody($body);
$request->withAttribute($name, $value);
$request->withoutAttribute($name);
UploadedFile::fromArray($file);
UploadedFile::fromPath($path);
$file->temporaryPath();
$file->path();
$file->movedPath();
$file->clientFilename();
$file->safeClientFilename($fallback);
$file->clientExtension();
$file->clientMediaType();
$file->mediaType();
$file->size();
$file->declaredSize();
$file->error();
$file->errorMessage();
$file->isHttpUpload();
$file->isValid();
$file->hasMoved();
$file->openStream();
$file->checksum($algorithm);
$file->assertMaximumSize($maximumBytes);
$file->assertMediaType($allowedMediaTypes);
$file->moveTo($destination, $overwrite, $permissions);
$file->compressTo($destination, $level, $overwrite);
Response::text($body, $statusCode, $headers);
Response::html($body, $statusCode, $headers);
Response::json($data, $statusCode, $headers);
Response::redirect($location, $statusCode, $headers);
Response::empty($statusCode, $headers);
Response::noContent($headers);
$response->statusCode();
$response->reasonPhrase();
$response->body();
$response->bodyLength();
$response->isEmpty();
$response->allowsBody();
$response->headers();
$response->hasHeader($name);
$response->header($name, $default);
$response->headerValues($name);
$response->contentType();
$response->isInformational();
$response->isSuccessful();
$response->isRedirect();
$response->isClientError();
$response->isServerError();
$response->isError();
$response->withStatus($statusCode);
$response->withBody($body);
$response->withHeader($name, $value);
$response->withAddedHeader($name, $value);
$response->withoutHeader($name);
$response->withContentLength();
$response->send($sendBody);
HttpException::badRequest();
HttpException::unauthorized();
HttpException::forbidden();
HttpException::notFound();
HttpException::methodNotAllowed($allowedMethods);
HttpException::conflict();
HttpException::contentTooLarge();
HttpException::unsupportedMediaType();
HttpException::unprocessable();
HttpException::tooManyRequests();
HttpException::internalServerError();
HttpException::serviceUnavailable();
$exception->statusCode();
$exception->headers();
$exception->header($name, $default);
$exception->context();
$exception->isClientError();
$exception->isServerError();