Bu ders için video bulunmamaktadır.

Bu derse başlamak veya ilerlemenizi kaydetmek için lütfen giriş yapın veya kayıt olun.

Ders İçeriği

Öğrenim Hedefleri

Bu dersin sonunda öğrenciler:
Oturum yönetimi ve kullanıcı kimlik doğrulama sistemleri geliştirebilecek
Dosya yükleme ve işleme özelliklerini uygulayabilecek
Email gönderimi ve API entegrasyonu yapabilecek
MVC yapısını anlayacak ve basit bir framework kullanabilecek
Kapsamlı bir web uygulaması geliştirebilecek

1. Oturum Yönetimi ve Kullanıcı Kimlik Doğrulama

Güvenli Şifre Yönetimi

<?php // Şifre hashleme function sifreHashle($sifre) { return password_hash($sifre, PASSWORD_DEFAULT); } // Şifre doğrulama function sifreDogrula($sifre, $hash) { return password_verify($sifre, $hash); } // Güçlü şifre kontrolü function gucluSifreKontrol($sifre) { $hatalar = []; if (strlen($sifre) < 8) { $hatalar[] = "Şifre en az 8 karakter olmalıdır."; } if (!preg_match('/[A-Z]/', $sifre)) { $hatalar[] = "Şifre en az bir büyük harf içermelidir."; } if (!preg_match('/[a-z]/', $sifre)) { $hatalar[] = "Şifre en az bir küçük harf içermelidir."; } if (!preg_match('/[0-9]/', $sifre)) { $hatalar[] = "Şifre en az bir rakam içermelidir."; } if (!preg_match('/[^A-Za-z0-9]/', $sifre)) { $hatalar[] = "Şifre en az bir özel karakter içermelidir."; } return $hatalar; } ?>

Kullanıcı Kayıt Sistemi

<?php function kullaniciKayit($pdo, $kullanici_adi, $email, $sifre) { try { // Şifre güçlülük kontrolü $sifreHatalari = gucluSifreKontrol($sifre); if (!empty($sifreHatalari)) { throw new Exception(implode(" ", $sifreHatalari)); } // Email benzersizlik kontrolü $stmt = $pdo->prepare("SELECT id FROM kullanicilar WHERE email = ?"); $stmt->execute([$email]); if ($stmt->fetch()) { throw new Exception("Bu email adresi zaten kullanılıyor."); } // Kullanıcı adı benzersizlik kontrolü $stmt = $pdo->prepare("SELECT id FROM kullanicilar WHERE kullanici_adi = ?"); $stmt->execute([$kullanici_adi]); if ($stmt->fetch()) { throw new Exception("Bu kullanıcı adı zaten kullanılıyor."); } // Şifreyi hashle $hashedSifre = sifreHashle($sifre); // Email doğrulama token'ı oluştur $dogrulamaToken = bin2hex(random_bytes(32)); // Kullanıcıyı kaydet $sql = "INSERT INTO kullanicilar (kullanici_adi, email, sifre, dogrulama_token, aktif) VALUES (?, ?, ?, ?, 0)"; $stmt = $pdo->prepare($sql); $stmt->execute([$kullanici_adi, $email, $hashedSifre, $dogrulamaToken]); $kullaniciId = $pdo->lastInsertId(); // Email doğrulama maili gönder emailDogrulamaGonder($email, $dogrulamaToken); return $kullaniciId; } catch(Exception $e) { throw new Exception("Kayıt hatası: " . $e->getMessage()); } } ?>

Kullanıcı Giriş Sistemi

<?php session_start(); function kullaniciGiris($pdo, $email, $sifre, $beniHatirla = false) { try { $sql = "SELECT id, kullanici_adi, email, sifre, aktif FROM kullanicilar WHERE email = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$email]); $kullanici = $stmt->fetch(PDO::FETCH_ASSOC); if (!$kullanici) { throw new Exception("Email veya şifre hatalı."); } if (!$kullanici['aktif']) { throw new Exception("Hesabınız henüz aktifleştirilmemiş. Email adresinizi kontrol edin."); } if (!sifreDogrula($sifre, $kullanici['sifre'])) { // Başarısız giriş denemesini kaydet basarisizGirisKaydet($pdo, $email); throw new Exception("Email veya şifre hatalı."); } // Oturum bilgilerini ayarla $_SESSION['kullanici_id'] = $kullanici['id']; $_SESSION['kullanici_adi'] = $kullanici['kullanici_adi']; $_SESSION['email'] = $kullanici['email']; $_SESSION['giris_zamani'] = time(); // Beni hatırla özelliği if ($beniHatirla) { $token = bin2hex(random_bytes(32)); $expires = time() + (30 * 24 * 60 * 60); // 30 gün // Token'ı veritabanına kaydet $sql = "INSERT INTO hatirla_tokenlari (kullanici_id, token, expires) VALUES (?, ?, ?)"; $stmt = $pdo->prepare($sql); $stmt->execute([$kullanici['id'], hash('sha256', $token), $expires]); // Cookie'yi ayarla setcookie('hatirla_token', $token, $expires, '/', '', true, true); } // Son giriş zamanını güncelle $sql = "UPDATE kullanicilar SET son_giris = NOW() WHERE id = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$kullanici['id']]); return true; } catch(Exception $e) { throw new Exception($e->getMessage()); } } function oturumKontrol() { if (!isset($_SESSION['kullanici_id'])) { return false; } // Oturum zaman aşımı kontrolü (2 saat) if (isset($_SESSION['giris_zamani']) && (time() - $_SESSION['giris_zamani'] > 7200)) { oturumSonlandir(); return false; } return true; } function oturumSonlandir() { session_destroy(); // Hatırla cookie'sini sil if (isset($_COOKIE['hatirla_token'])) { setcookie('hatirla_token', '', time() - 3600, '/', '', true, true); } } ?>

2. Dosya Yükleme ve İşleme

Güvenli Dosya Yükleme

<?php function dosyaYukle($dosya, $hedefKlasor = 'uploads/') { try { // Dosya yükleme hatalarını kontrol et if ($dosya['error'] !== UPLOAD_ERR_OK) { throw new Exception("Dosya yükleme hatası: " . $dosya['error']); } // Dosya boyutu kontrolü (5MB) $maxBoyut = 5 * 1024 * 1024; if ($dosya['size'] > $maxBoyut) { throw new Exception("Dosya boyutu çok büyük. Maksimum 5MB olmalıdır."); } // Dosya türü kontrolü $izinliTurler = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf']; $dosyaTuru = mime_content_type($dosya['tmp_name']); if (!in_array($dosyaTuru, $izinliTurler)) { throw new Exception("Bu dosya türü desteklenmiyor."); } // Dosya uzantısı kontrolü $dosyaUzantisi = strtolower(pathinfo($dosya['name'], PATHINFO_EXTENSION)); $izinliUzantilar = ['jpg', 'jpeg', 'png', 'gif', 'pdf']; if (!in_array($dosyaUzantisi, $izinliUzantilar)) { throw new Exception("Bu dosya uzantısı desteklenmiyor."); } // Benzersiz dosya adı oluştur $yeniDosyaAdi = uniqid() . '_' . time() . '.' . $dosyaUzantisi; $hedefYol = $hedefKlasor . $yeniDosyaAdi; // Hedef klasörü oluştur if (!is_dir($hedefKlasor)) { mkdir($hedefKlasor, 0755, true); } // Dosyayı taşı if (!move_uploaded_file($dosya['tmp_name'], $hedefYol)) { throw new Exception("Dosya yüklenirken hata oluştu."); } return [ 'dosya_adi' => $yeniDosyaAdi, 'dosya_yolu' => $hedefYol, 'dosya_boyutu' => $dosya['size'], 'dosya_turu' => $dosyaTuru ]; } catch(Exception $e) { throw new Exception($e->getMessage()); } } // Resim boyutlandırma function resimBoyutlandir($kaynak, $hedef, $maxGenislik, $maxYukseklik) { $resimBilgisi = getimagesize($kaynak); $genislik = $resimBilgisi[0]; $yukseklik = $resimBilgisi[1]; $tur = $resimBilgisi[2]; // Oranı koru $oran = min($maxGenislik / $genislik, $maxYukseklik / $yukseklik); $yeniGenislik = $genislik * $oran; $yeniYukseklik = $yukseklik * $oran; // Kaynak resmi oluştur switch ($tur) { case IMAGETYPE_JPEG: $kaynakResim = imagecreatefromjpeg($kaynak); break; case IMAGETYPE_PNG: $kaynakResim = imagecreatefrompng($kaynak); break; case IMAGETYPE_GIF: $kaynakResim = imagecreatefromgif($kaynak); break; default: throw new Exception("Desteklenmeyen resim formatı."); } // Yeni resim oluştur $yeniResim = imagecreatetruecolor($yeniGenislik, $yeniYukseklik); // PNG şeffaflığını koru if ($tur == IMAGETYPE_PNG) { imagealphablending($yeniResim, false); imagesavealpha($yeniResim, true); } // Resmi boyutlandır imagecopyresampled($yeniResim, $kaynakResim, 0, 0, 0, 0, $yeniGenislik, $yeniYukseklik, $genislik, $yukseklik); // Resmi kaydet switch ($tur) { case IMAGETYPE_JPEG: imagejpeg($yeniResim, $hedef, 90); break; case IMAGETYPE_PNG: imagepng($yeniResim, $hedef); break; case IMAGETYPE_GIF: imagegif($yeniResim, $hedef); break; } // Belleği temizle imagedestroy($kaynakResim); imagedestroy($yeniResim); } ?>

3. Email Gönderimi

PHPMailer ile Email Gönderimi

<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php'; function emailGonder($alici, $konu, $mesaj, $html = true) { $mail = new PHPMailer(true); try { // SMTP ayarları $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'your-email@gmail.com'; $mail->Password = 'your-app-password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; $mail->CharSet = 'UTF-8'; // Gönderen bilgileri $mail->setFrom('your-email@gmail.com', 'Web Sitesi'); $mail->addAddress($alici); // Email içeriği $mail->isHTML($html); $mail->Subject = $konu; $mail->Body = $mesaj; $mail->send(); return true; } catch (Exception $e) { throw new Exception("Email gönderilemedi: {$mail->ErrorInfo}"); } } function emailDogrulamaGonder($email, $token) { $konu = "Email Adresinizi Doğrulayın"; $mesaj = " <h2>Email Doğrulama</h2> <p>Hesabınızı aktifleştirmek için aşağıdaki bağlantıya tıklayın:</p> <a href='http://yoursite.com/dogrula.php?token=$token'>Hesabımı Aktifleştir</a> <p>Bu bağlantı 24 saat geçerlidir.</p> "; return emailGonder($email, $konu, $mesaj); } function sifreSifirlamaGonder($email, $token) { $konu = "Şifre Sıfırlama"; $mesaj = " <h2>Şifre Sıfırlama</h2> <p>Şifrenizi sıfırlamak için aşağıdaki bağlantıya tıklayın:</p> <a href='http://yoursite.com/sifre-sifirla.php?token=$token'>Şifremi Sıfırla</a> <p>Bu bağlantı 1 saat geçerlidir.</p> "; return emailGonder($email, $konu, $mesaj); } ?>

4. API Entegrasyonu

RESTful API Oluşturma

<?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type'); class API { private $pdo; public function __construct($pdo) { $this->pdo = $pdo; } public function handleRequest() { $method = $_SERVER['REQUEST_METHOD']; $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $pathParts = explode('/', trim($path, '/')); $resource = $pathParts[1] ?? ''; $id = $pathParts[2] ?? null; try { switch ($resource) { case 'kullanicilar': $this->handleKullanicilar($method, $id); break; case 'posts': $this->handlePosts($method, $id); break; default: $this->sendResponse(404, ['error' => 'Endpoint bulunamadı']); } } catch (Exception $e) { $this->sendResponse(500, ['error' => $e->getMessage()]); } } private function handleKullanicilar($method, $id) { switch ($method) { case 'GET': if ($id) { $this->getKullanici($id); } else { $this->getKullanicilar(); } break; case 'POST': $this->createKullanici(); break; case 'PUT': $this->updateKullanici($id); break; case 'DELETE': $this->deleteKullanici($id); break; default: $this->sendResponse(405, ['error' => 'Method not allowed']); } } private function getKullanicilar() { $stmt = $this->pdo->query("SELECT id, kullanici_adi, email, kayit_tarihi FROM kullanicilar"); $kullanicilar = $stmt->fetchAll(PDO::FETCH_ASSOC); $this->sendResponse(200, $kullanicilar); } private function getKullanici($id) { $stmt = $this->pdo->prepare("SELECT id, kullanici_adi, email, kayit_tarihi FROM kullanicilar WHERE id = ?"); $stmt->execute([$id]); $kullanici = $stmt->fetch(PDO::FETCH_ASSOC); if ($kullanici) { $this->sendResponse(200, $kullanici); } else { $this->sendResponse(404, ['error' => 'Kullanıcı bulunamadı']); } } private function createKullanici() { $data = json_decode(file_get_contents('php://input'), true); if (!$data || !isset($data['kullanici_adi']) || !isset($data['email'])) { $this->sendResponse(400, ['error' => 'Gerekli alanlar eksik']); return; } $stmt = $this->pdo->prepare("INSERT INTO kullanicilar (kullanici_adi, email) VALUES (?, ?)"); $stmt->execute([$data['kullanici_adi'], $data['email']]); $id = $this->pdo->lastInsertId(); $this->sendResponse(201, ['id' => $id, 'message' => 'Kullanıcı oluşturuldu']); } private function sendResponse($statusCode, $data) { http_response_code($statusCode); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; } } // API'yi başlat $api = new API($pdo); $api->handleRequest(); ?>

Harici API Kullanımı

<?php function apiIstegi($url, $method = 'GET', $data = null, $headers = []) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => array_merge([ 'Content-Type: application/json', 'User-Agent: MyApp/1.0' ], $headers) ]); if ($data && in_array($method, ['POST', 'PUT', 'PATCH'])) { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = curl_error($ch); curl_close($ch); if ($error) { throw new Exception("cURL hatası: " . $error); } $decodedResponse = json_decode($response, true); return [ 'status_code' => $httpCode, 'data' => $decodedResponse, 'raw' => $response ]; } // Örnek kullanım: Hava durumu API'si function havaDurumuGetir($sehir) { $apiKey = 'your-api-key'; $url = "http://api.openweathermap.org/data/2.5/weather?q={$sehir}&appid={$apiKey}&units=metric&lang=tr"; try { $response = apiIstegi($url); if ($response['status_code'] === 200) { return $response['data']; } else { throw new Exception("Hava durumu bilgisi alınamadı"); } } catch (Exception $e) { throw new Exception("API hatası: " . $e->getMessage()); } } ?>

5. Basit MVC Yapısı

Model-View-Controller Örneği

<?php // Model (models/User.php) class User { private $pdo; public function __construct($pdo) { $this->pdo = $pdo; } public function getAll() { $stmt = $this->pdo->query("SELECT * FROM kullanicilar ORDER BY id DESC"); return $stmt->fetchAll(PDO::FETCH_ASSOC); } public function getById($id) { $stmt = $this->pdo->prepare("SELECT * FROM kullanicilar WHERE id = ?"); $stmt->execute([$id]); return $stmt->fetch(PDO::FETCH_ASSOC); } public function create($data) { $stmt = $this->pdo->prepare("INSERT INTO kullanicilar (kullanici_adi, email) VALUES (?, ?)"); return $stmt->execute([$data['kullanici_adi'], $data['email']]); } public function update($id, $data) { $stmt = $this->pdo->prepare("UPDATE kullanicilar SET kullanici_adi = ?, email = ? WHERE id = ?"); return $stmt->execute([$data['kullanici_adi'], $data['email'], $id]); } public function delete($id) { $stmt = $this->pdo->prepare("DELETE FROM kullanicilar WHERE id = ?"); return $stmt->execute([$id]); } } // Controller (controllers/UserController.php) class UserController { private $userModel; public function __construct($pdo) { $this->userModel = new User($pdo); } public function index() { $users = $this->userModel->getAll(); include 'views/users/index.php'; } public function show($id) { $user = $this->userModel->getById($id); if (!$user) { header("HTTP/1.0 404 Not Found"); include 'views/404.php'; return; } include 'views/users/show.php'; } public function create() { if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = [ 'kullanici_adi' => $_POST['kullanici_adi'], 'email' => $_POST['email'] ]; if ($this->userModel->create($data)) { header('Location: /users'); exit; } } include 'views/users/create.php'; } } // Router (index.php) $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $pathParts = explode('/', trim($path, '/')); $controller = $pathParts[0] ?? 'home'; $action = $pathParts[1] ?? 'index'; $id = $pathParts[2] ?? null; switch ($controller) { case 'users': $userController = new UserController($pdo); switch ($action) { case 'index': $userController->index(); break; case 'show': $userController->show($id); break; case 'create': $userController->create(); break; default: header("HTTP/1.0 404 Not Found"); include 'views/404.php'; } break; default: include 'views/home.php'; } ?>

Pratik Alıştırmalar

1.Kullanıcı Yönetim Sistemi: Kayıt, giriş, profil fotoğrafı yükleme
2.Blog Sistemi: Yazı ekleme, resim yükleme, yorum sistemi
3.E-ticaret Sitesi: Ürün yönetimi, sepet sistemi, ödeme entegrasyonu
4.API Geliştirme: RESTful API oluşturma ve tüketme