unsplash-php

repository·master·Indexed 19 days ago

https://github.com/unsplash/unsplash-php

A PHP client for the official Unsplash API that enables developers to integrate photo search, collections, and user data into PHP applications. The library provides classes for managing photos, users, and collections, and includes a Connection class to handle the OAuth2 authorization workflow, token generation, and refreshes.

Tokens
7.9K
Snippets
47
Records
49
Agent score
64%

What's inside unsplash-php

  1. Overview of the Unsplash PHP Wrapper

    master

    The unsplash-php library is a PHP client for the official Unsplash API. It allows developers to interact with Unsplash resources such as photos, collections, and users.

    Important Compliance Note: When using this client, your application must follow the Unsplash API Guidelines. Key requirements include:

    • Hotlinking images: Do not host Unsplash images on your own servers; use the provided URLs.
    • Triggering downloads: Use the appropriate download trigger methods when a user requests a photo to ensure Unsplash photographers receive proper credit/metrics.
  2. Configure the Unsplash HttpClient

    master

    Before using the library, initialize the Unsplash\HttpClient with your credentials. If you are only performing public actions, only the applicationId is required. Note that applicationId is used for the access key due to legacy reasons. Providing utmSource is recommended to avoid notices.

    Unsplash\HttpClient::init([
    	'applicationId' => 'YOUR ACCESS KEY',
    	'secret' => 'YOUR APPLICATION SECRET',
    	'callbackUrl' => 'https://your-application.com/oauth/callback',
    	'utmSource' => 'NAME OF YOUR APPLICATION'
    ]);
  3. Implement the User Authorization workflow

    master

    To access non-public data (e.g., uploading photos or editing user data), you must implement the OAuth flow:

    1. Generate Authorization URL: Direct the user to the Unsplash authorization URL with your desired scopes.
    2. Handle Callback: After authorization, Unsplash redirects to your callbackUrl with an authentication code.
    3. Generate Token: Use the code to generate an access token.

    Refer to /examples/oauth-flow.php for a complete implementation example.

    // 1. Generate Authorization URL
    $scopes = ['public', 'write_user'];
    Unsplash\HttpClient::$connection->getConnectionUrl($scopes);
    
    // 2. Generate Token using the code received from the callback
    Unsplash\HttpClient::$connection->generateToken($code);
  4. Manage Unsplash OAuth2 authentication with Connection

    master

    The Unsplash\Connection class manages the lifecycle of Unsplash API authentication, including generating authorization URLs, validating OAuth2 states, exchanging authorization codes for tokens, and handling token refreshes. It acts as a wrapper around the OAuth2 provider to simplify the user authorization workflow.

    use Unsplash\Connection;
    use Unsplash\OAuth2\Client\Provider\Unsplash;
    
    // Initialize with a provider
    $provider = new Unsplash($clientId, $clientSecret);
    $connection = new Connection($provider);
  5. Initialize the Unsplash HttpClient

    master

    Before making any API requests, you must initialize the HttpClient using the init() method. This method sets up the global Connection object required for all subsequent requests.

    To comply with Unsplash API terms, you must provide a utmSource in your credentials array. If it is missing, a PHP error will be triggered.

    Credentials Array

    Required keys for authentication:

    • applicationId (string): Your Unsplash Application ID.
    • secret (string): Your Application Secret (required for OAuth).
    • callbackUrl (string): The URL to redirect to after OAuth authentication.
    • utmSource (string): The name of your application (required for API terms).

    Access Token Array

    If you already have an access token (e.g., from a previous session), you can pass it to init() to avoid re-authenticating:

    • access_token (string): The identifier.
    • refresh_token (string): Necessary when the access token expires.
    • expires_in (int): The expiration duration.
    use Unsplash\HttpClient;
    
    // Initialize with credentials
    HttpClient::init([
        'applicationId' => 'YOUR_APP_ID',
        'secret'        => 'YOUR_APP_SECRET',
        'callbackUrl'   => 'https://your-app.com/callback',
        'utmSource'     => 'my_awesome_app'
    ]);
    
    // Or initialize with an existing access token
    HttpClient::init([
        'applicationId' => 'YOUR_APP_ID',
        'secret'        => 'YOUR_APP_SECRET',
        'callbackUrl'   => 'https://your-app.com/callback',
        'utmSource'     => 'my_awesome_app'
    ], [
        'access_token'  => 'EXISTING_ACCESS_TOKEN',
        'refresh_token' => 'EXISTING_REFRESH_TOKEN',
        'expires_in'    => 3600
    ]);
  6. Interact with Photos using Unsplash\Photo

    master

    The Unsplash\Photo class provides methods to retrieve photo details, search for random photos, and perform user-specific actions like liking or downloading.

    // Retrieve a list of photos
    Unsplash\Photo::all($page, $per_page, 'popular');
    
    // Find a specific photo
    $photo = Unsplash\Photo::find($id);
    
    // Get the photographer of a photo
    $photographer = $photo->photographer();
    
    // Get random photo with filters
    $filters = ['query' => 'coffee', 'w' => 100, 'h' => 100];
    Unsplash\Photo::random($filters);
    
    // Like a photo (requires 'write_likes' scope)
    $photo->like();
    
    // Unlike a photo (requires 'write_likes' scope)
    $photo->unlike();
    
    // Trigger a download (required by Unsplash API guidelines)
    $photo->download();
    
    // Get photo statistics
    $photo->statistics('days', 7);
  7. Manage Users with Unsplash\User

    master

    The Unsplash\User class allows you to retrieve user information, portfolios, and manage the current authenticated user's profile.

    // Find a user by username
    $user = Unsplash\User::find('username');
    
    // Get user's portfolio link
    $portfolio = Unsplash\User::portfolio('username');
    
    // Get current authenticated user (requires 'read_user' scope)
    $currentUser = Unsplash\User::current();
    
    // Get current user's photos
    $photos = $currentUser->photos($page, $per_page);
    
    // Get current user's collections (requires 'read_collections' scope)
    $collections = $currentUser->collections($page, $per_page);
    
    // Update current user profile (requires 'write_user' scope)
    $currentUser->update(['first_name' => 'Elliot', 'last_name' => 'Alderson']);
    
    // Get user statistics
    $user->statistics('days', 30);
  8. Search for Photos, Collections, or Users

    master

    Use the Unsplash\Search class to perform keyword-based searches. Methods return an ArrayObject which behaves like a standard stdClass.

    // Search Photos
    Unsplash\Search::photos('forest', 1, 10, 'landscape');
    
    // Search Collections
    Unsplash\Search::collections('nature', 1, 10);
    
    // Search Users
    Unsplash\Search::users('photography', 1, 10);
  9. Manage Collections with Unsplash\Collection

    master

    The Unsplash\Collection class allows you to retrieve, create, update, and delete collections. Many methods require you to first instantiate a collection object using find($id).

    // Retrieve all collections
    Unsplash\Collection::all($page, $per_page);
    
    // Find a specific collection and get its photos
    $collection = Unsplash\Collection::find($id);
    $photos = $collection->photos($page, $per_page);
    
    // Create a new collection (requires 'write_collections' scope)
    $collection = Unsplash\Collection::create('My Title', 'My Description');
    
    // Update a collection (requires 'write_collections' scope)
    $collection->update(['private' => true]);
    
    // Add a photo to a collection (requires 'write_collections' scope)
    $collection->add($photo_id);
    
    // Remove a photo from a collection (requires 'write_collections' scope)
    $collection->remove($photo_id);
    
    // Delete a collection (requires 'write_collections' scope)
    $collection->destroy();
  10. Reference: Unsplash Permission Scopes

    master

    The following scopes define the level of access your application requests from a user:

    • public: Access a user's public data
    • read_user: Access a user's private data
    • write_user: Edit and create user data
    • read_photos: Access private information from a user's photos
    • write_photos: Post and edit photos for a user
    • write_likes: Like a photo for a user
    • read_collections: View a user’s private collections
    • write_collections: Create and update a user's collections
  11. Refresh an expired access token

    master

    If you have a stored token that contains a refresh token, you can call refreshToken() to obtain a new access token. This method updates the internal token state of the Connection object.

    Returns the new AccessToken object, or null if no token or refresh token is available.

    $newToken = $connection->refreshToken();