Lecture Notes Of Class 3: Making API Requests in PHP

Rashmi Mishra
0

Lecture Notes Of Class 3: Making API Requests in PHP

Objective: Learn how to make requests to external APIs using PHP.


Introduction to APIs

An API (Application Programming Interface) allows two software systems to communicate with each other. For example, a weather application can fetch weather data from a weather service API. PHP can be used to interact with APIs to send requests and handle responses.


Why Use APIs?

1.  Access External Data: APIs provide access to external data, such as weather reports, currency exchange rates, or user details.

2.  Integrate Services: You can integrate third-party services like payment gateways or social media platforms.

3.  Dynamic Applications: APIs enable building dynamic applications that fetch live data.


Making API Requests in PHP

There are two common methods for making API requests in PHP:

1.  Using file_get_contents()

2.  Using cURL


1. Using file_get_contents()

The file_get_contents() function can make simple HTTP GET requests.

Syntax:

php

Copy code

file_get_contents(string $url): string|false

  • $url: The URL of the API endpoint you want to request.
  • Returns: The response data as a string or false on failure.

Example: Fetching Data Using file_get_contents()

Let’s fetch data from a sample API.

Code Example:

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/posts/1";

 

// Fetch data from the API

$response = file_get_contents($url);

 

// Check if the response is not false

if ($response !== false) {

    // Convert JSON response to an associative array

    $data = json_decode($response, true);

   

    // Display the fetched data

    echo "Title: " . $data['title'] . "<br>";

    echo "Body: " . $data['body'] . "<br>";

} else {

    echo "Failed to fetch data from the API.";

}

?>

Output:

makefile

Copy code

Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit 

Body: quia et suscipit suscipit recusandae consequuntur expedita et cum...


2. Using cURL for More Complex API Requests

The cURL library in PHP is more powerful and can handle complex requests like POST, PUT, DELETE, and adding headers.

Steps to Use cURL:

1.  Initialize cURL: Use curl_init() to start a cURL session.

2.  Set Options: Use curl_setopt() to configure request options like the URL, method, headers, etc.

3.  Execute Request: Use curl_exec() to execute the request and get the response.

4.  Close cURL: Use curl_close() to close the session.


Example: Fetching Data Using cURL

Code Example:

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/posts/1";

 

// Initialize cURL session

$ch = curl_init();

 

// Set cURL options

curl_setopt($ch, CURLOPT_URL, $url);             // Set API URL

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as a string

 

// Execute the request

$response = curl_exec($ch);

 

// Check for errors

if ($response === false) {

    echo "cURL Error: " . curl_error($ch);

} else {

    // Convert JSON response to an associative array

    $data = json_decode($response, true);

   

    // Display the fetched data

    echo "Title: " . $data['title'] . "<br>";

    echo "Body: " . $data['body'] . "<br>";

}

 

// Close the cURL session

curl_close($ch);

?>

Output:

makefile

Copy code

Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit 

Body: quia et suscipit suscipit recusandae consequuntur expedita et cum...


Comparison of file_get_contents() and cURL

Feature

file_get_contents()

cURL

Ease of Use

Simple and easy to use

More complex setup required

Supported Request Types

Only GET requests

Supports GET, POST, PUT, DELETE

Headers Support

Limited

Fully customizable

Error Handling

Limited

Detailed error handling


Conclusion

1.  For simple GET requests, file_get_contents() is sufficient.

2.  For advanced features like POST requests or custom headers, use cURL.

3.  Always handle errors gracefully to improve application reliability.


Assignment for Practice

1.  Use file_get_contents() to fetch a list of users from the API: https://jsonplaceholder.typicode.com/users.

o    Display each user’s name and email.

2.  Use cURL to send a POST request to the API: https://jsonplaceholder.typicode.com/posts.

o    Send sample data (title and body) and display the response.

By completing these exercises, you'll gain hands-on experience in making API requests using PHP.

4o

You said:

WRITE SOME ASSIGNMENTS FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with explanation

ChatGPT said:

ChatGPT

Assignments with Step-by-Step Solutions

Below are some assignments based on the topic Making API Requests in PHP, with detailed solutions for each step.


Assignment 1: Fetch User Details Using file_get_contents()

Task:
Fetch a list of users from the API https://jsonplaceholder.typicode.com/users and display their names and emails.

Solution:

Step 1: Define the API URL

Define the API endpoint from where the data will be fetched.

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/users";

?>

Step 2: Use file_get_contents() to Fetch Data

Fetch the data using the file_get_contents() function.

php

Copy code

<?php

$response = file_get_contents($url); // Get response as a JSON string

?>

Step 3: Check for Errors

Ensure that the response is not false.

php

Copy code

<?php

if ($response === false) {

    die("Failed to fetch data from the API.");

}

?>

Step 4: Convert JSON to Array

Decode the JSON response into a PHP array for easier processing.

php

Copy code

<?php

$data = json_decode($response, true); // Convert JSON to associative array

?>

Step 5: Loop Through the Array and Display User Data

Iterate through the data to display user names and emails.

php

Copy code

<?php

foreach ($data as $user) {

    echo "Name: " . $user['name'] . "<br>";

    echo "Email: " . $user['email'] . "<br><br>";

}

?>

Complete Code:

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/users";

 

// Fetch data from the API

$response = file_get_contents($url);

 

// Check if the response is valid

if ($response === false) {

    die("Failed to fetch data from the API.");

}

 

// Convert JSON response to an array

$data = json_decode($response, true);

 

// Display names and emails of users

foreach ($data as $user) {

    echo "Name: " . $user['name'] . "<br>";

    echo "Email: " . $user['email'] . "<br><br>";

}

?>


Assignment 2: Send a POST Request Using cURL

Task:
Send a POST request to the API https://jsonplaceholder.typicode.com/posts with the following data:

  • title: "Learning PHP APIs"
  • body: "This is a sample post for learning purposes."

Display the response from the API.


Solution:

Step 1: Define the API URL

Set the API endpoint URL where the data will be sent.

php

Copy code

<?php

$url = "https://jsonplaceholder.typicode.com/posts";

?>

Step 2: Initialize cURL

Start a cURL session using curl_init().

php

Copy code

<?php

$ch = curl_init(); // Initialize cURL

?>

Step 3: Prepare Data for the POST Request

Create an array with the data you want to send, then encode it as JSON.

php

Copy code

<?php

$data = [

    "title" => "Learning PHP APIs",

    "body" => "This is a sample post for learning purposes."

];

$jsonData = json_encode($data); // Convert data to JSON

?>

Step 4: Set cURL Options

Configure cURL to use the POST method, send the JSON data, and include headers.

php

Copy code

<?php

curl_setopt($ch, CURLOPT_URL, $url); // Set the URL

curl_setopt($ch, CURLOPT_POST, true); // Use POST method

curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); // Attach data

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as string

curl_setopt($ch, CURLOPT_HTTPHEADER, [

    "Content-Type: application/json", // Set content type to JSON

]);

?>

Step 5: Execute the Request

Send the request and capture the response.

php

Copy code

<?php

$response = curl_exec($ch); // Execute the POST request

?>

Step 6: Check for Errors

Check if the request was successful or if there were any errors.

php

Copy code

<?php

if ($response === false) {

    echo "cURL Error: " . curl_error($ch);

} else {

    echo "Response from API: " . $response;

}

?>

Step 7: Close the cURL Session

Close the session to free resources.

php

Copy code

<?php

curl_close($ch); // Close cURL session

?>

Complete Code:

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/posts";

 

// Initialize cURL session

$ch = curl_init();

 

// Data to send in the POST request

$data = [

    "title" => "Learning PHP APIs",

    "body" => "This is a sample post for learning purposes."

];

$jsonData = json_encode($data); // Convert data to JSON

 

// Set cURL options

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, [

    "Content-Type: application/json"

]);

 

// Execute the POST request

$response = curl_exec($ch);

 

// Check for errors

if ($response === false) {

    echo "cURL Error: " . curl_error($ch);

} else {

    echo "Response from API: " . $response;

}

 

// Close the cURL session

curl_close($ch);

?>

Expected Output:

A JSON response indicating that the data was successfully received, including a new ID for the created post.

json

Copy code

{

  "id": 101,

  "title": "Learning PHP APIs",

  "body": "This is a sample post for learning purposes."

}


Assignment 3: Error Handling in cURL

Task:
Modify Assignment 2 to handle the following errors:

1.  Invalid API URL.

2.  Network timeout.

Solution:

  • Set a timeout option in cURL using CURLOPT_TIMEOUT.
  • Validate the URL and check for errors using curl_error().

Updated Code:

php

Copy code

<?php

// API URL

$url = "https://invalid.url/posts"; // Invalid URL for demonstration

 

// Initialize cURL session

$ch = curl_init();

 

// Data to send

$data = [

    "title" => "Learning PHP APIs",

    "body" => "This is a sample post for learning purposes."

];

$jsonData = json_encode($data);

 

// Set cURL options

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, [

    "Content-Type: application/json"

]);

curl_setopt($ch, CURLOPT_TIMEOUT, 5); // Set timeout to 5 seconds

 

// Execute the POST request

$response = curl_exec($ch);

 

// Check for errors

if ($response === false) {

    echo "Error: " . curl_error($ch);

} else {

    echo "Response from API: " . $response;

}

 

// Close the cURL session

curl_close($ch);

?>

Output (for invalid URL):

javascript

Copy code

Error: Could not resolve host: invalid.url


By practicing these assignments, students will gain hands-on experience with real-world API interactions in PHP.

4o

You said:

some more

ChatGPT said:

ChatGPT

Additional Assignments with Step-by-Step Solutions

Here are more assignments to practice making API requests in PHP.


Assignment 4: Fetch Posts from an API and Display in an HTML Table

Task:
Fetch posts from the API https://jsonplaceholder.typicode.com/posts and display the Post ID, Title, and Body in an HTML table.

Solution:

Step 1: Define the API URL

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/posts";

?>

Step 2: Fetch Data Using file_get_contents()

php

Copy code

<?php

$response = file_get_contents($url);

if ($response === false) {

    die("Error: Unable to fetch data from API.");

}

$data = json_decode($response, true); // Decode JSON into an array

?>

Step 3: Create an HTML Table and Display the Data

php

Copy code

<?php

echo "<table border='1'>";

echo "<tr><th>Post ID</th><th>Title</th><th>Body</th></tr>";

 

foreach ($data as $post) {

    echo "<tr>";

    echo "<td>" . $post['id'] . "</td>";

    echo "<td>" . $post['title'] . "</td>";

    echo "<td>" . $post['body'] . "</td>";

    echo "</tr>";

}

 

echo "</table>";

?>

Complete Code:

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/posts";

 

// Fetch data from API

$response = file_get_contents($url);

if ($response === false) {

    die("Error: Unable to fetch data from API.");

}

$data = json_decode($response, true); // Decode JSON

 

// Display data in an HTML table

echo "<table border='1'>";

echo "<tr><th>Post ID</th><th>Title</th><th>Body</th></tr>";

 

foreach ($data as $post) {

    echo "<tr>";

    echo "<td>" . $post['id'] . "</td>";

    echo "<td>" . $post['title'] . "</td>";

    echo "<td>" . $post['body'] . "</td>";

    echo "</tr>";

}

 

echo "</table>";

?>


Assignment 5: Send a PUT Request Using cURL

Task:
Update the title of a post using the API https://jsonplaceholder.typicode.com/posts/1 with the following data:

  • title: "Updated Title Using cURL"

Solution:

Step 1: Define the API URL

php

Copy code

<?php

$url = "https://jsonplaceholder.typicode.com/posts/1"; // Update post with ID 1

?>

Step 2: Prepare the Data

php

Copy code

<?php

$data = [

    "title" => "Updated Title Using cURL"

];

$jsonData = json_encode($data);

?>

Step 3: Set cURL Options for PUT Request

php

Copy code

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // Use PUT method

curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, [

    "Content-Type: application/json"

]);

?>

Step 4: Execute the Request and Check for Errors

php

Copy code

<?php

$response = curl_exec($ch);

if ($response === false) {

    echo "Error: " . curl_error($ch);

} else {

    echo "Response from API: " . $response;

}

curl_close($ch);

?>

Complete Code:

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/posts/1";

 

// Data to update

$data = [

    "title" => "Updated Title Using cURL"

];

$jsonData = json_encode($data);

 

// Initialize cURL session

$ch = curl_init();

 

// Set cURL options

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, [

    "Content-Type: application/json"

]);

 

// Execute the PUT request

$response = curl_exec($ch);

if ($response === false) {

    echo "Error: " . curl_error($ch);

} else {

    echo "Response from API: " . $response;

}

 

// Close the cURL session

curl_close($ch);

?>


Assignment 6: Fetch Comments for a Specific Post

Task:
Fetch comments for a post with ID 1 from the API https://jsonplaceholder.typicode.com/comments?postId=1 and display the name, email, and body of each comment.

Solution:

Step 1: Define the API URL

php

Copy code

<?php

$url = "https://jsonplaceholder.typicode.com/comments?postId=1";

?>

Step 2: Fetch Data Using file_get_contents()

php

Copy code

<?php

$response = file_get_contents($url);

if ($response === false) {

    die("Error: Unable to fetch data from API.");

}

$data = json_decode($response, true);

?>

Step 3: Loop Through the Comments and Display Them

php

Copy code

<?php

foreach ($data as $comment) {

    echo "<h3>" . $comment['name'] . " (" . $comment['email'] . ")</h3>";

    echo "<p>" . $comment['body'] . "</p>";

}

?>

Complete Code:

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/comments?postId=1";

 

// Fetch data

$response = file_get_contents($url);

if ($response === false) {

    die("Error: Unable to fetch data from API.");

}

$data = json_decode($response, true); // Decode JSON

 

// Display comments

foreach ($data as $comment) {

    echo "<h3>" . $comment['name'] . " (" . $comment['email'] . ")</h3>";

    echo "<p>" . $comment['body'] . "</p>";

}

?>


Assignment 7: Delete a Post Using cURL

Task:
Delete a post with ID 1 using the API https://jsonplaceholder.typicode.com/posts/1.

Solution:

Step 1: Define the API URL

php

Copy code

<?php

$url = "https://jsonplaceholder.typicode.com/posts/1";

?>

Step 2: Set cURL Options for DELETE Request

php

Copy code

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

?>

Step 3: Execute the Request and Display the Response

php

Copy code

<?php

$response = curl_exec($ch);

if ($response === false) {

    echo "Error: " . curl_error($ch);

} else {

    echo "Post Deleted. Response from API: " . $response;

}

curl_close($ch);

?>

Complete Code:

php

Copy code

<?php

// API URL

$url = "https://jsonplaceholder.typicode.com/posts/1";

 

// Initialize cURL session

$ch = curl_init();

 

// Set cURL options

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

 

// Execute the DELETE request

$response = curl_exec($ch);

if ($response === false) {

    echo "Error: " . curl_error($ch);

} else {

    echo "Post Deleted. Response from API: " . $response;

}

 

// Close the cURL session

curl_close($ch);

?>


These assignments provide hands-on experience with various HTTP methods (GET, POST, PUT, DELETE) and error handling while interacting with APIs in PHP.

4o

You said:

write 50 MCQs on above topic

ChatGPT said:

ChatGPT

Here are 50 multiple-choice questions (MCQs) based on the topic "Making API Requests in PHP":


MCQs on Making API Requests in PHP


1. Which PHP function is used to send GET requests to an API?
a) file_get_contents()
b) curl_exec()
c) fopen()
d) file_put_contents()

Answer: a) file_get_contents()


2. What is the default request type when using file_get_contents()?
a) POST
b) GET
c) PUT
d) DELETE

Answer: b) GET


3. Which PHP library is commonly used for making complex API requests?
a) cURL
b) PDO
c) Guzzle
d) OpenSSL

Answer: a) cURL


4. How do you execute a GET request using cURL in PHP?
a) curl_setopt($ch, CURLOPT_URL, $url); curl_exec($ch);
b) curl_get($ch, $url);
c) curl_send($ch, $url);
d) curl_execute($ch, $url);

Answer: a) curl_setopt($ch, CURLOPT_URL, $url); curl_exec($ch);


5. Which PHP function is used to decode a JSON response?
a) json_encode()
b) json_decode()
c) json_parse()
d) json_transform()

Answer: b) json_decode()


6. Which HTTP method is used to update an existing resource using cURL?
a) GET
b) POST
c) PUT
d) DELETE

Answer: c) PUT


7. Which cURL option is used to set the HTTP request method?
a) CURLOPT_CUSTOMREQUEST
b) CURLOPT_HTTPMETHOD
c) CURLOPT_REQUESTMETHOD
d) CURLOPT_METHOD

Answer: a) CURLOPT_CUSTOMREQUEST


8. What is the correct cURL option to send data in a POST request?
a) CURLOPT_POSTFIELDS
b) CURLOPT_HEADER
c) CURLOPT_POST
d) CURLOPT_URL

Answer: a) CURLOPT_POSTFIELDS


9. In which format do you usually receive API responses in web development?
a) XML
b) CSV
c) JSON
d) TXT

Answer: c) JSON


10. Which of the following is NOT a valid HTTP request method?
a) GET
b) POST
c) PUT
d) UPDATE

Answer: d) UPDATE


11. How do you send a DELETE request using cURL in PHP?
a) curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
b) curl_setopt($ch, CURLOPT_REQUESTMETHOD, "DELETE");
c) curl_setopt($ch, CURLOPT_DELETE, true);
d) curl_setopt($ch, CURLOPT_METHOD, "DELETE");

Answer: a) curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");


12. What should you use to check if file_get_contents() returns false?
a) isset()
b) empty()
c) is_null()
d) === false

Answer: d) === false


13. How do you include headers in a cURL request?
a) curl_setopt($ch, CURLOPT_HEADERS, $headers);
b) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
c) curl_setopt($ch, CURLOPT_INCLUDEHEADER, true);
d) curl_setopt($ch, CURLOPT_HEADERFIELDS, $headers);

Answer: b) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


14. What does the CURLOPT_RETURNTRANSFER option do in cURL?
a) It forces the cURL request to return data as a string.
b) It sends the response to the terminal.
c) It returns the response as an array.
d) It disables the return of any response.

Answer: a) It forces the cURL request to return data as a string.


15. In cURL, which function initializes a session?
a) curl_init()
b) curl_start()
c) curl_open()
d) curl_session()

Answer: a) curl_init()


16. Which of the following is the correct cURL option to set the URL for a request?
a) CURLOPT_URL
b) CURLOPT_DEST
c) CURLOPT_URLPATH
d) CURLOPT_HTTPURL

Answer: a) CURLOPT_URL


17. What does curl_error($ch) return in case of a cURL error?
a) null
b) false
c) An error message
d) An error code

Answer: c) An error message


18. How do you close a cURL session in PHP?
a) curl_shutdown($ch);
b) curl_end($ch);
c) curl_close($ch);
d) curl_stop($ch);

Answer: c) curl_close($ch);


19. Which of the following is a valid URL to fetch data from a mock API?
a) https://api.mock.com/data
b) https://jsonplaceholder.typicode.com/posts
c) https://api.mockurl
d) https://example.com/data.json

Answer: b) https://jsonplaceholder.typicode.com/posts


20. What does json_decode() do to a JSON string in PHP?
a) Converts the string into an array or object.
b) Converts the string into XML.
c) Decodes the string into text.
d) Encrypts the string.

Answer: a) Converts the string into an array or object.


21. Which PHP function is used to handle errors when fetching data from an API using file_get_contents()?
a) error_log()
b) try-catch
c) die()
d) set_error_handler()

Answer: c) die()


22. Which HTTP method is typically used to send form data to a server?
a) POST
b) GET
c) PUT
d) PATCH

Answer: a) POST


23. Which of the following is the correct way to specify the content type for a JSON request in cURL?
a) CURLOPT_HTTPHEADER => "Content-Type: text/json"
b) CURLOPT_HTTPHEADER => "Content-Type: application/json"
c) CURLOPT_HTTPHEADER => "Content-Type: application/text"
d) CURLOPT_HTTPHEADER => "Content-Type: json/application"

Answer: b) CURLOPT_HTTPHEADER => "Content-Type: application/json"


24. What does the following cURL code snippet do?
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer <token>']);

a) Sends an authentication token to the server.
b) Sends a username and password for authentication.
c) Specifies the content type for the request.
d) Initiates an OAuth login flow.

Answer: a) Sends an authentication token to the server.


25. Which cURL option should be set to handle cookies in a cURL request?
a) CURLOPT_COOKIEFILE
b) CURLOPT_COOKIEJAR
c) CURLOPT_COOKIE
d) CURLOPT_FOLLOWLOCATION

Answer: b) CURLOPT_COOKIEJAR


26. What should you do after curl_exec($ch) if you want to check if there was a cURL error?
a) Use curl_errno($ch) to check for errors.
b) Use curl_error($ch) to check for errors.
c) Use curl_error($ch) to get the response.
d) Both a and b.

Answer: d) Both a and b.


27. Which option in cURL allows you to follow redirects automatically?
a) CURLOPT_FOLLOWLOCATION
b) CURLOPT_REDIRECT
c) CURLOPT_AUTOREDIRECT
d) CURLOPT_FOLLOWREDIRECT

Answer: a) CURLOPT_FOLLOWLOCATION


28. What should be done when a request fails in cURL?
a) Retry the request automatically.
b) Log the error message using curl_error().
c) Ignore the failure and continue.
d) Proceed with default data.

Answer: b) Log the error message using curl_error().


29. Which method is used to send data in a GET request using cURL?
a) CURLOPT_POSTFIELDS
b) CURLOPT_URL
c) CURLOPT_HTTPGET
d) Data is included in the URL.

Answer: d) Data is included in the URL.


30. How do you authenticate a request using basic authentication in cURL?
a) curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
b) curl_setopt($ch, CURLOPT_USERNAME, 'username');
c) curl_setopt($ch, CURLOPT_AUTH, 'username:password');
d) curl_setopt($ch, CURLOPT_AUTHENTICATION, 'username:password');

Answer: a) curl_setopt($ch, CURLOPT_USERPWD, 'username:password');


31. Which HTTP method is typically used to delete a resource in a REST API?
a) GET
b) POST
c) PUT
d) DELETE

Answer: d) DELETE


32. What does the CURLOPT_RETURNTRANSFER option in cURL do?
a) Tells cURL to return the response as a string.
b) Tells cURL to save the response to a file.
c) Tells cURL to redirect to another URL.
d) Tells cURL to ignore the response.

Answer: a) Tells cURL to return the response as a string.


33. What should you do if the API response is not in JSON format but in XML?
a) Use json_decode() to parse the response.
b) Use simplexml_load_string() to parse the response.
c) Use json_encode() to convert the response.
d) Ignore the response.

Answer: b) Use simplexml_load_string() to parse the response.


34. In PHP, how can you set a timeout for a cURL request?
a) curl_setopt($ch, CURLOPT_TIMEOUT, 10);
b) curl_setopt($ch, CURLOPT_TIMEOUT, 0);
c) curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10000);
d) curl_setopt($ch, CURLOPT_TIME_LIMIT, 10);

Answer: a) curl_setopt($ch, CURLOPT_TIMEOUT, 10);


35. Which function is used to get the HTTP status code from a cURL response?
a) curl_getinfo()
b) curl_status()
c) curl_response_code()
d) curl_http_code()

Answer: a) curl_getinfo()


36. Which of these methods can be used to send data using a GET request?
a) Query parameters in the URL
b) Request body
c) Header fields
d) HTTP cookies

Answer: a) Query parameters in the URL


37. What is the default content type for cURL requests?
a) application/xml
b) application/json
c) text/html
d) No default content type

Answer: d) No default content type


38. Which method would you use to check if an API response has a specific header?
a) get_header()
b) curl_getinfo()
c) curl_get_header()
d) header_exists()

Answer: b) curl_getinfo()


39. Which PHP cURL option is used to disable SSL verification?
a) CURLOPT_SSL_VERIFYHOST
b) CURLOPT_SSL_VERIFYPEER
c) CURLOPT_SSL_VERIFY
d) CURLOPT_SSL_NO_VERIFY

Answer: b) CURLOPT_SSL_VERIFYPEER


40. What is the main benefit of using cURL over file_get_contents()?
a) cURL allows for more flexible request methods (GET, POST, PUT, DELETE).
b) file_get_contents() is faster for large responses.
c) cURL only supports GET requests.
d) file_get_contents() cannot handle binary responses.

Answer: a) cURL allows for more flexible request methods (GET, POST, PUT, DELETE).


41. How do you set a custom user-agent string in cURL?
a) curl_setopt($ch, CURLOPT_USERAGENT, 'myCustomUserAgent');
b) curl_setopt($ch, CURLOPT_AGENT, 'myCustomUserAgent');
c) curl_setopt($ch, CURLOPT_USER, 'myCustomUserAgent');
d) curl_setopt($ch, CURLOPT_CUSTOMUSERAGENT, 'myCustomUserAgent');

Answer: a) curl_setopt($ch, CURLOPT_USERAGENT, 'myCustomUserAgent');


42. How can you track multiple cURL requests in parallel?
a) Use curl_multi_* functions.
b) Use curl_exec() with an array of URLs.
c) Use curl_async() function.
d) Use curl_multi_exec() with multiple sessions.

Answer: a) Use curl_multi_* functions.


43. Which function should be used to parse XML data in PHP?
a) json_decode()
b) simplexml_load_string()
c) xml_parser()
d) xml_decode()

Answer: b) simplexml_load_string()


44. What is the default method used by file_get_contents() for sending data?
a) GET
b) POST
c) PUT
d) PATCH

Answer: a) GET


45. What should you use to handle JSON data in PHP when the response is empty?
a) json_decode() with default values.
b) json_encode() with empty string check.
c) json_decode() and check for null.
d) json_parse() for empty responses.

Answer: c) json_decode() and check for null.


46. What does the CURLOPT_VERBOSE option do in cURL?
a) Enables detailed debugging of cURL operations.
b) Specifies verbose output in the response body.
c) Forces cURL to return the headers only.
d) Limits the cURL output to error messages.

Answer: a) Enables detailed debugging of cURL operations.


47. What is the main advantage of using cURL over file_get_contents()?
a) Ability to handle different HTTP methods (GET, POST, PUT, DELETE).
b) Simpler syntax for simple API requests.
c) Only used for sending GET requests.
d) cURL does not require PHP extensions.

Answer: a) Ability to handle different HTTP methods (GET, POST, PUT, DELETE).


48. What is the purpose of CURLOPT_SSL_VERIFYPEER in cURL?
a) Verifies the SSL connection to the server.
b) Verifies the server's certificate validity.
c) Forces the connection to use a specific certificate.
d) Disables SSL verification for the request.

Answer: b) Verifies the server's certificate validity.


49. What does the curl_multi_* function allow you to do?
a) Execute multiple cURL requests in parallel.
b) Execute a single cURL request with multiple methods.
c) Process multiple responses from a single API request.
d) Combine different cURL requests into one response.

Answer: a) Execute multiple cURL requests in parallel.


50. What is the correct way to execute a POST request with JSON data using cURL?
a) curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
b) curl_setopt($ch, CURLOPT_POSTFIELDS, '{"key":"value"}');
c) curl_setopt($ch, CURLOPT_POST, true);
d) All of the above.

Answer: d) All of the above.

 


Tags

Post a Comment

0Comments

Post a Comment (0)