{"id":13793479,"url":"https://github.com/VolkanSah/GPT-Security-Best-Practices","last_synced_at":"2025-05-12T20:31:02.516Z","repository":{"id":156284538,"uuid":"632909798","full_name":"VolkanSah/GPT-Security-Best-Practices","owner":"VolkanSah","description":"The purpose of this document is to outline the security risks and vulnerabilities that may arise when implementing ChatGPT in web applications and to provide best practices for mitigating these risks.","archived":false,"fork":false,"pushed_at":"2025-02-06T10:51:55.000Z","size":556,"stargazers_count":26,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-12T08:45:26.967Z","etag":null,"topics":["ajax","ajax-request","chatgpt","chf","code-security","html","js","php","security","security-risks","server-side","serverside-rendering","vulnerabilities","vulnerabilities-fix"],"latest_commit_sha":null,"homepage":"https://github.com/VolkanSah/ChatGPT-Security-Best-Practices","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/VolkanSah.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["volkansah"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"lfx_crowdfunding":null,"custom":null}},"created_at":"2023-04-26T11:34:22.000Z","updated_at":"2025-03-08T23:10:40.000Z","dependencies_parsed_at":"2024-01-07T06:08:38.084Z","dependency_job_id":"34c70b07-9837-4aa5-b9ab-5f1d1336a9b2","html_url":"https://github.com/VolkanSah/GPT-Security-Best-Practices","commit_stats":null,"previous_names":[],"tags_count":3,"template":true,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FGPT-Security-Best-Practices","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FGPT-Security-Best-Practices/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FGPT-Security-Best-Practices/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FGPT-Security-Best-Practices/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/VolkanSah","download_url":"https://codeload.github.com/VolkanSah/GPT-Security-Best-Practices/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253816692,"owners_count":21968867,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ajax","ajax-request","chatgpt","chf","code-security","html","js","php","security","security-risks","server-side","serverside-rendering","vulnerabilities","vulnerabilities-fix"],"created_at":"2024-08-03T23:00:22.135Z","updated_at":"2025-05-12T20:31:02.482Z","avatar_url":"https://github.com/VolkanSah.png","language":null,"funding_links":["https://github.com/sponsors/volkansah"],"categories":["❤️ Thank you for your support!"],"sub_categories":["👣 other GPT stuff"],"readme":"# GPT Security Best Practices\n\n[Source of this GPT Security Best Practices](https://github.com/VolkanSah/GPT-Security-Best-Practices/) look for updates before you use these tips if it is forked!\n\nAs an AI language model enthusiast, I often find myself alarmed by the way sensitive data is carelessly handled in various applications. While the excitement around GPT is understandable, the improper handling of sensitive information poses significant challenges for administrators and security professionals managing servers rented by clients. This document aims to provide best practices for securely implementing GPT in web applications to prevent security vulnerabilities and protect sensitive data.\n\n## Table of Contents\n- [Introduction](#Introduction)\n- [Security Risks and Vulnerabilities](#Security-Risks-and-Vulnerabilities)\n- [Using Environment Variables in PHP](#Using-Environment-Variables-in-PHP)\n- [Best Practices for Implementing GPT](#Best-Practices-for-Implementing-GPT)\n- [Choosing the Appropriate API Endpoint](#Choosing-the-Appropriate-API-Endpoint)\n- [Code Example](#Code-Example)\n- [Credits](#Credits)\n\n\n## Introduction\nThe purpose of this document is to outline the security risks and vulnerabilities that may arise when implementing GPT in web applications and to provide best practices for mitigating these risks.\n\n## Security Risks and Vulnerabilities\n- Storing sensitive data in JavaScript\n- Exposing API keys and request URLs in the browser console\n\n1. Use server-side languages like PHP for handling sensitive data and functions\nInstead of using JavaScript to handle sensitive data, use server-side languages like PHP. This will keep the data secure and away from the client-side, where it could be accessed through the browser console.\n\n```php\n\u003c?php\n$api_key = \"your_api_key_here\";\n$request_url = \"https://api.openai.com/v1/engines/davinci-codex/completions\";\n```\n\n2. Use AJAX for communication between the front-end and back-end\nWith AJAX, you can asynchronously send data to and retrieve data from the server without exposing sensitive information in the browser console.\n\nFront-end (JavaScript with jQuery)\n```javascript\nfunction sendRequest(inputText) {\n  $.ajax({\n    url: 'backend.php',\n    type: 'POST',\n    data: { input: inputText },\n    success: function(response) {\n      // Process and display the response from GPT\n    },\n    error: function() {\n      // Handle error cases\n    }\n  });\n}\n```\n\nBack-end (PHP)\n```php\n\u003c?php\n$api_key = \"your_api_key_here\";\n$request_url = \"https://api.openai.com/v1/engines/davinci-codex/completions\";\n\n$inputText = $_POST['input'];\n\n// Process the input and send a request to GPT\n\n// Return the response to the front-end\n```\n\n3. Secure your API key\nStore your API key in a secure location, such as an environment variable, and not in the source code. This will prevent accidental exposure of the key in public repositories.\n\n## Using Environment Variables in PHP\nYou can store your API key as an environment variable by adding it to your server's environment configuration or by using a .env file (with the help of a library like PHP dotenv).\n\nCreate a .env file in your project's root directory:\n\n```\nGPT_API_KEY=your_api_key_here\n```\n\nInstall the vlucas/phpdotenv package using Composer:\n\n```\ncomposer require vlucas/phpdotenv\n```\n\nLoad the environment variables from the .env file in your PHP script:\n\n```php\n\u003c?php\nrequire_once 'vendor/autoload.php';\n\nuse Dotenv\\Dotenv;\n\n$dotenv = Dotenv::createImmutable(__DIR__);\n$dotenv-\u003eload();\n```\n\nAccess the API key from the environment variables:\n\n```php\n\u003c?php\n$api_key = getenv('GPT_API_KEY');\n$request_url = \"https://api.openai.com/v1/engines/davinci-codex/completions\";\n```\n\nBy using environment variables, your API key will be kept secure and separated from your source code. Remember to add the .env file to your .gitignore file to prevent it from being accidentally committed to your public repository.\n\n## Best Practices for Implementing GPT\n4. Validate and sanitize user inputs\nEnsure that user inputs are validated and sanitized before processing them. This will prevent potential security vulnerabilities, such as XSS attacks.\n\nBack-end (PHP)\n```php\n\u003c?php\n// Sanitize user input before processing\n$inputText = filter_input(INPUT_POST, 'input', FILTER_SANITIZE_STRING);\n```\n\n5. Use HTTPS for secure communication\nWhen deploying your web application, ensure that you use HTTPS to encrypt the communication between the client and the server, preventing man-in-the-middle attacks.\n\n6. Limit API request rate\nTo prevent abuse of your GPT API key and control costs, implement rate-limiting on your server-side code. This will limit the number of requests made to the GPT API within a specified time frame.\n\nBack-end (PHP)\n```php\n\u003c?php\n// Implement rate-limiting logic here\n// ...\n\n// Only proceed with the request if the rate limit is not exceeded\nif ($is_rate_limit_ok) {\n  // Send a request to GPT API\n}\n```\n\n7. Use Content Security Policy (CSP)\nImplement CSP headers to prevent XSS attacks and other vulnerabilities by controlling the resources the user agent is allowed to load for a given page.\n\n8. Use Security Headers\nImplement security headers such as X-Frame-Options, X-Content-Type-Options, and others to protect your application from common security vulnerabilities.\n\n## Choosing the Appropriate API Endpoint\nWhen implementing GPT, it's crucial to select the appropriate API endpoint based on your specific use case. OpenAI provides various endpoints for different purposes. Here are the current OpenAI endpoints:\n\nENDPOINT | MODEL NAME\n-- | --\n/v1/chat/completions | gpt-3.5-turbo, gpt-3.5-turbo-0301, gpt-3.5-turbo-0613, gpt-3.5-turbo-16k, gpt-3.5-turbo-16k-0613, gpt-4, gpt-4-0314, gpt-4-0613, gpt-4-32k, gpt-4-32k-0314, gpt-4o (variants: gpt-4o-2024-05-13, gpt-4o-2024-08-06, gpt-4o-2024-11-20), gpt-4o-audio-preview (e.g. gpt-4o-audio-preview-2024-10-01, gpt-4o-audio-preview-2024-12-17), gpt-4o-realtime-preview (e.g. gpt-4o-realtime-preview-2024-10-01, gpt-4o-realtime-preview-2024-12-17), gpt-4o-mini (gpt-4o-mini-2024-07-18), gpt-4o-mini-audio-preview (gpt-4o-mini-audio-preview-2024-12-17), gpt-4o-mini-realtime-preview (gpt-4o-mini-realtime-preview-2024-12-17), o1 (o1-2024-12-17), o1-mini (o1-mini-2024-09-12), o1-preview (o1-preview-2024-09-12), o3-mini (o3-mini-2025-01-31)\n/v1/completions | ada, ada-code-search-code, ada-code-search-text, ada-search-document, ada-search-query, ada-similarity, babbage, babbage-code-search-code, babbage-code-search-text, babbage-search-document, babbage-search-query, babbage-similarity, code-davinci-edit-001, code-search-ada-code-001, code-search-ada-text-001, code-search-babbage-code-001, code-search-babbage-text-001, curie, curie-instruct-beta, curie-search-document, curie-search-query, curie-similarity, davinci, davinci-instruct-beta, davinci-search-document, davinci-search-query, davinci-similarity, text-ada-001, text-babbage-001, text-curie-001, text-davinci-001, text-davinci-002, text-davinci-003, text-davinci-edit-001, text-embedding-ada-002, text-search-ada-doc-001, text-search-ada-query-001, text-search-babbage-doc-001, text-search-babbage-query-001, text-search-curie-doc-001, text-search-curie-query-001, text-search-davinci-doc-001, text-search-davinci-query-001, text-similarity-ada-001, text-similarity-babbage-001, text-similarity-curie-001, text-similarity-davinci-001\n/v1/edits | text-davinci-edit-001, code-davinci-edit-001\n/v1/audio/transcriptions | whisper-1\n/v1/audio/translations | whisper-1\n/v1/fine-tunes | davinci, curie, babbage, ada\n/v1/embeddings | text-embedding-ada-002, text-search-ada-doc-001, text-search-ada-query-001, text-search-babbage-doc-001, text-search-babbage-query-001, text-search-curie-doc-001, text-search-curie-query-001, text-search-davinci-doc-001, text-search-davinci-query-001\n/v1/moderations | text-moderation-latest, text-moderation-stable\n\n### Cost\nDifferent endpoints have varying costs per token or per request. Choose an endpoint that fits within your budget.\n\n### Performance\nSome endpoints offer faster response times, while others are more suited for heavy-duty tasks. Consider the performance needs of your application when selecting an endpoint.\n\n### Specific Use Case\nEach endpoint has its own strengths and weaknesses. Evaluate the unique requirements of your application and choose the endpoint that best meets those needs.\n\n## Code Example\nAn example of how to use the /v1/chat/completions endpoint with the gpt-3.5-turbo model in a web application.\n\nUpdate the $request_url in your back-end PHP script:\n\n```php\n\u003c?php\n$api_key = getenv('GPT_API_KEY');\n$request_url = \"https://api.openai.com/v1/chat/completions\";\n```\n\nCreate a function to send a request to the GPT API:\n\n```php\n\u003c?php\nfunction send_chat_completion_request($api_key, $request_url, $messages) {\n  $ch = curl_init();\n\n  $data = array(\n    'model' =\u003e 'gpt-3.5-turbo',\n    'messages' =\u003e $messages\n  );\n\n  curl_setopt($ch, CURLOPT_URL, $request_url);\n  curl_setopt($ch, CURLOPT_POST, 1);\n  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));\n  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n  curl_setopt($ch, CURLOPT_HTTPHEADER, array(\n    \"Content-Type: application/json\",\n    \"Authorization: Bearer $api_key\"\n  ));\n\n  $response = curl_exec($ch);\n  $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);\n  curl_close($ch);\n\n  return array('response' =\u003e $response, 'httpcode' =\u003e $httpcode);\n}\n```\n\nCall the send_chat_completion_request() function and process the GPT API response:\n\n```php\n\u003c?php\n$inputText = filter_input(INPUT_POST, 'input', FILTER_SANITIZE_STRING);\n$messages = array(\n  array('role' =\u003e 'system', 'content' =\u003e 'You are talking to a helpful assistant.'),\n  array('role' =\u003e 'user', 'content' =\u003e $inputText)\n);\n\n$result = send_chat_completion_request($api_key, $request_url, $messages);\n\nif ($result['httpcode'] == 200) {\n  $json_response = json_decode($result['response'], true);\n  $assistant_reply = $json_response['choices'][0]['message']['content'];\n\n  // Return the response to the front-end\n  echo $assistant_reply;\n} else {\n  // Handle error cases\n  echo \"Error: \" . $result['response'];\n}\n```\n\nThis example shows how to use the /v1/chat/completions endpoint with the gpt-3.5-turbo model. The send_chat_completion_request() function sends a request to the API with the input text and receives the generated response. The assistant's reply is then returned to the front-end.\n\n## Other Note\nAdditional resources and notes that might be helpful for understanding and implementing the best practices mentioned in this document.\n\n- [Secure Implementation of Artificial Intelligence (AI)](https://github.com/VolkanSah/Implementing-AI-Systems-Whitepaper/tree/main)\n\n### Credits\nS. Volkan Kücükbudak\n\n\n- ## Your Support\nIf you find this project useful and want to support it, there are several ways to do so:\n\n- If you find the white paper helpful, please ⭐ it on GitHub. This helps make the project more visible and reach more people.\n- Become a Follower: If you're interested in updates and future improvements, please follow my GitHub account. This way you'll always stay up-to-date.\n- Learn more about my work: I invite you to check out all of my work on GitHub and visit my developer site https://volkansah.github.io. Here you will find detailed information about me and my projects.\n- Share the project: If you know someone who could benefit from this project, please share it. The more people who can use it, the better.\n**If you appreciate my work and would like to support it, please visit my [GitHub Sponsor page](https://github.com/sponsors/volkansah). Any type of support is warmly welcomed and helps me to further improve and expand my work.**\n\nThank you for your support! ❤️\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FVolkanSah%2FGPT-Security-Best-Practices","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FVolkanSah%2FGPT-Security-Best-Practices","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FVolkanSah%2FGPT-Security-Best-Practices/lists"}