Erreurs PHP courantes : solutions aux problèmes fréquemment rencontrés

Barbara Streisand
Libérer: 2024-10-14 13:31:44
original
327 Les gens l'ont consulté

Common PHP Errors: Solutions to Frequently Encountered Issues

PHP는 웹 개발에 널리 사용되는 강력한 스크립트 언어이지만 다른 언어와 마찬가지로 디버그하기 어려울 수 있는 오류가 발생하기 쉽습니다. 일부 오류는 간단하고 수정하기 쉽지만 일부 오류는 좀 더 복잡할 수 있습니다. 이 문서에서는 가장 일반적인 PHP 오류 중 일부를 다루고 이러한 오류를 신속하게 해결하는 데 도움이 되는 솔루션을 제공합니다.

1. 구문 오류

문제:

PHP 인터프리터가 예상 구조와 일치하지 않는 코드를 발견하면 구문 오류가 발생합니다. 이는 가장 기본적인 오류 유형이며 구문 오류, 예상치 못한 토큰 메시지 등 무서운 구문 분석 오류가 발생하는 경우가 많습니다.

일반적인 원인:

  • 세미콜론(;)이 누락되었습니다
  • 일치하지 않는 괄호, 중괄호 또는 괄호
  • 따옴표의 잘못된 사용
  • 맞춤법이 잘못된 키워드

예:

echo "Hello World" // Missing semicolon
Copier après la connexion

해결책:

코드에 구두점이 없거나 추가되었는지 다시 확인하세요. 열고 닫는 괄호, 대괄호, 따옴표가 모두 일치하는지 확인하세요.

echo "Hello World"; // Fixed
Copier après la connexion

2. 정의되지 않은 변수 오류

문제:

초기화되지 않은 변수를 사용하려고 하면 '정의되지 않은 변수' 오류가 발생합니다. 이 경우 PHP는 주의: 정의되지 않은 변수 오류를 발생시킵니다.

예:

echo $username; // Undefined variable
Copier après la connexion

해결책:

코드에서 변수를 사용하기 전에 변수가 초기화되었는지 확인하세요. isset()을 사용하여 변수가 설정되었는지 확인하여 이 알림을 억제할 수도 있습니다.

if (isset($username)) {
    echo $username;
} else {
    echo "No username provided";
}
Copier après la connexion

3. 치명적 오류: 정의되지 않은 함수 호출

문제:

이 오류는 정의되지 않은 함수를 호출하려고 할 때 발생합니다. 함수 이름의 철자를 잘못 입력했거나 함수가 포함된 필수 파일을 포함하는 것을 잊었기 때문에 발생할 수 있습니다.

예:

myFunction(); // Undefined function
Copier après la connexion

해결책:

함수가 스크립트에 올바르게 정의되었거나 포함되어 있는지 확인하세요. 그리고, 함수명에 오타가 있는지 확인해보세요.

function myFunction() {
    echo "Hello World!";
}

myFunction(); // Fixed
Copier après la connexion

4. 헤더가 이미 전송되었습니다

문제:

이 오류는 출력이 이미 브라우저에 전송된 후 PHP가 헤더(예: header() 또는 setcookie() 사용)를 수정하려고 시도할 때 발생합니다. 오류 메시지는 일반적으로 다음과 같습니다. 경고: 헤더 정보를 수정할 수 없습니다. 헤더가 이미 전송되었습니다...

예:

echo "Some output";
header("Location: /newpage.php"); // Causes error because output was already sent
Copier après la connexion

해결책:

header() 함수가 호출되기 전에 출력(공백 또는 BOM 포함)이 전송되지 않는지 확인하세요. 사용자를 리디렉션해야 하는 경우 출력이 생성되기 전에 header()가 호출되는지 확인하세요.

header("Location: /newpage.php"); // This must appear before any echo or print statements
exit();
Copier après la connexion

5. 잘못된 권한

문제:

PHP 스크립트에 파일이나 디렉터리에 액세스할 수 있는 적절한 읽기 또는 쓰기 권한이 없을 때 권한 오류가 발생합니다. 경고: fopen(/path/to/file): 스트림을 열지 못했습니다: 권한이 거부되었습니다.

와 같은 오류가 표시될 수 있습니다.

해결책:

파일 및 디렉터리 권한을 확인하세요. 일반적으로 웹 서버 사용자는 파일에 대한 읽기 권한과 업로드 또는 파일 조작이 발생하는 디렉터리에 대한 쓰기 권한이 있어야 합니다. 권한을 조정하려면 다음 명령을 사용하십시오.

chmod 755 /path/to/directory
chmod 644 /path/to/file
Copier après la connexion

참고: 권한을 과도하게 설정하면 보안 위험이 발생할 수 있으므로 권한을 설정할 때 주의하세요.

6. 메모리 한도 소진

문제:

PHP에 할당된 메모리가 부족해지면 치명적인 오류: 허용된 메모리 크기 X바이트가 소진되었습니다.라는 오류가 표시됩니다. 이는 스크립트가 php.ini에 설정된 제한보다 더 많은 메모리를 사용할 때 발생합니다.

해결책:

PHP 스크립트에 다음 줄을 추가하여 일시적으로 메모리 제한을 늘릴 수 있습니다.

ini_set('memory_limit', '256M'); // Adjust as needed
Copier après la connexion

또는 php.ini 파일에서 메모리 제한을 영구적으로 늘릴 수도 있습니다.

memory_limit = 256M
Copier après la connexion

가능한 경우 메모리 사용량을 줄이려면 코드를 최적화하세요.

7. MySQL 연결 오류

문제:

때때로 MySQL 데이터베이스 연결이 실패하여 치명적인 오류: 포착되지 않은 mysqli_sql_Exception: 'username'@'localhost' 사용자에 대한 액세스가 거부되었습니다.

Common Causes:

  • Incorrect database credentials (hostname, username, password, database name)
  • The MySQL server is not running
  • Incorrect PHP MySQL extension (e.g., using mysql_connect() instead of mysqli_connect())

Solution:

Ensure that your credentials are correct and that the MySQL server is running. Also, make sure to use the appropriate connection function. Here's a correct example using mysqli_connect():

$mysqli = new mysqli('localhost', 'username', 'password', 'database');

if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}
Copier après la connexion

8. File Upload Errors

Problem:

File uploads often fail due to improper settings or file size limitations. You may encounter errors like UPLOAD_ERR_INI_SIZE or UPLOAD_ERR_FORM_SIZE.

Solution:

Check and adjust the following php.ini settings as needed:

file_uploads = On
upload_max_filesize = 10M
post_max_size = 12M
Copier après la connexion

Also, make sure your form tag has the correct enctype attribute:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>
Copier après la connexion

9. Undefined Index/Offset

Problem:

This notice occurs when you try to access an array element that doesn’t exist, causing a Notice: Undefined index or Notice: Undefined offset error.

Example:

echo $_POST['username']; // Undefined index if 'username' is not in the form data
Copier après la connexion

Solution:

Always check if the array key exists before trying to access it. Use isset() or array_key_exists() to prevent this error.

if (isset($_POST['username'])) {
    echo $_POST['username'];
} else {
    echo "Username not provided.";
}
Copier après la connexion

10. Class Not Found

Problem:

PHP throws a Fatal error: Class 'ClassName' not found error when you try to instantiate a class that hasn’t been defined or included properly.

Solution:

Ensure that the file containing the class is included using require() or include(). Alternatively, use PHP’s spl_autoload_register() function to automatically load class files.

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$object = new ClassName();
Copier après la connexion

11. Maximum Execution Time Exceeded

Problem:

If your PHP script takes too long to execute, you may encounter the Fatal error: Maximum execution time of X seconds exceeded error. This usually happens when working with large datasets or external API calls.

Solution:

You can increase the maximum execution time temporarily with:

set_time_limit(300); // Extends to 300 seconds (5 minutes)
Copier après la connexion

To set it globally, adjust the max_execution_time directive in the php.ini file:

max_execution_time = 300
Copier après la connexion

PHP errors are inevitable, but knowing how to tackle the most common ones can save you a lot of debugging time. Whether it's a syntax issue, database connection problem, or file permission error, understanding the root cause and solution is key to becoming a proficient PHP developer.

By following the guidelines in this article, you should be able to identify and resolve these issues effectively. Keep your error reporting enabled during development to catch these errors early and ensure smoother coding!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!