Scriptul PHP din spatele acestui formular de upload:
uf-v.1.0.php
<?php
/*
Titlu: Cum fac un formular de upload in PHP?
Autor: Marian Barbu aka AccesInterzis
Website: http://www.accesinterzis.ro
2010 (c) Toate drepturile rezervate
*/
#1
if (isset($_POST['upload'])) {
/*
Rezolv problema spatiilor goale din numele imaginii.
*/
#2
$filename = trim($_FILES['userfile']['name']);
$filename = str_replace(' ', '_', $filename);
#3
if (empty($filename)) {
$error_message = 'You didn\'t enter any file.';
} else {
#3.1
if (strlen($filename) > 30) {
$error_message = 'The filename must have up to 30 characters.';
} else {
#3.2
if (!preg_match('/^[a-z0-9._-]+\.[a-z]{2,4}$/i', $filename)) {
$error_message = 'The filename isn\'t valid.';
} else {
/*
Verific daca fisierul este o imagine. Content-type-ul unei imaginii este o
valoare de genul image/jpeg, image/pjpeg, image/gif, image/png.
*/
#3.3
if (!preg_match('/^image\//', $_FILES['userfile']['type'])) {
$error_message = 'You are allowed to upload only images.';
} else {
/*
Functia PHP getimagesize() ma asigura 100% ca ceea ce urca utilizatorul
e o imagine si nimic altceva.
*/
#3.4
$properties = getimagesize($_FILES['userfile']['tmp_name']);
if ($properties == false) {
$error_message = 'The file isn\'t an image.';
} else {
/*
Specific tipurile de imagini care pot fi urcate pe server.
*/
$allowed_extensions = array('.jpg', '.jpeg', '.gif', '.png');
$extension = substr($filename, strrpos($filename,'.'), 100);
$extension = strtolower($extension);
#3.5
if (!in_array($extension, $allowed_extensions)) {
$error_message = 'You aren\'t allowed to upload <strong>'.$extension.'</strong> files.';
} else {
/***/
/*
Imaginea poate avea maxim 100 kb.
*/
#3.6
if (($_FILES['userfile']['size']/1024) > 100) {
$error_message = 'The file can have up to <strong>100 kb</strong>.';
} else {
/*
Restrictionez latimea pe care imaginea o poate avea.
*/
#3.7
if ($properties[0] > 100) {
$error_message = 'The width must be up to 100px.';
} else {
/*
Restrictionez inaltimea pe care imaginea o poate avea.
*/
#3.8
if ($properties[1] > 100) {
$error_message = 'The height must be up to 100px.';
} else {
/*
Daca folderul "images" nu exista pe server atunci il creez.
*/
#3.9
if (!is_dir('images')) {
mkdir('images', 0777);
}
#3.10
if (file_exists('images/'.$filename)) {
$error_message = 'The file <strong>'.$filename.'</strong> already exists.';
} else {
/*
Acum ca m-am asigurat ca ceea ce vrea utilizatorul sa urce este o imagine si nu altceva
si acea imagine nu exista deja pe server, pot urca linistit imaginea de pe PC-ul utilizatorului
pe serverul de hosting. Din motive de securitate schimb numele initial al imaginii utilizatorului.
Noul nume este generat aleatoriu.
*/
#3.11
$alphabet = 'abcdefghijklmnoprqstuvxyz';
$new_fn = '';
for ($i = 0; $i < 10; $i++) {
$new_fn .= substr($alphabet, rand(0,strlen($alphabet) - 1), 1);
}
#3.12
if (substr(sprintf('%o', fileperms('images')), -4) != 777) {
$error_message = 'The folder has not the right permissions to read it.';
} else {
$count = 0;
$open = opendir ('images');
while ($image_name = readdir($open)) {
//. reprezinta folderul curent iar .. reprezinta folderul anterior
if ($image_name != '.' && $image_name != '..') {
$image_extension = substr($image_name, strpos($image_name,'.'),100);
$image_extension = strtolower($image_extension);
if (in_array($image_extension,$allowed_extensions)) {
$count++;
}
}
}
#3.13
if (move_uploaded_file($_FILES['userfile']['tmp_name'], 'images/'.($count + 1).'_'.$new_fn.$extension)) {
$confirmation = 'The file <strong>'.$filename.'</strong> was succesfully uploaded.';
} else {
$confirmation = 'Something is wrong with the server.';
}
}
}
}
}
}
/***/
}
}
}
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>How do I make a upload form?</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="How do I make a upload form?" />
<meta name="keywords" content="upload,form,php,script,image,file" />
<meta name="abstract" content="How do I make a upload form?" />
<meta name="author" content="AccesInterzis" />
<meta name="copyright" content="AccesInterzis" />
<meta name="robots" content="index,follow" />
<meta name="revisit-after" content="7 days" />
<link href="http://www.accesinterzis.ro/myportofolio/css/reset.css" type="text/css" rel="stylesheet" media="all" />
<style type="text/css">
/*INCEPUT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE UPLOAD*/
form#upload_form {
width:240px;
margin:10px auto;
}
form#upload_form div {
margin:0 0 5px 0;
}
form#upload_form input#upload {
width:auto;
color:#FFF;
background-color:#333;
border:1px #000 solid !important;
cursor:pointer;
}
form#upload_form input#upload:hover {
color:#333;
background-color:#fff;
border:1px #333 solid;
}
/*Inceput - stilurile erorilor*/
form#upload_form p {
color:#c00;
padding:0 0 5px 0;
font-size:10px;
text-align:left;
}
/*Sfarsit - stilurile erorilor*/
/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE UPLOAD*/
</style>
</head>
<body>
<form action="<?php echo htmlentities(strip_tags('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']), ENT_QUOTES, 'utf-8'); ?>" method="post" id="upload_form" enctype="multipart/form-data">
<?php if ($confirmation) echo '<p>'.$confirmation.'</p>'; ?>
<?php if ($error_message) echo '<p>'.$error_message.'</p>'; ?>
<div>
<input name="userfile" type="file" value="ABC" id="userfile" />
</div>
<div>
<input name="upload" type="submit" id="upload" value="upload" />
</div>
</form>
<?php echo $count.' sadf safsa'; ?>
</body>
</html>
Pentru o mai buna organizare a codului este indicat ca scriptul PHP de deasupra DOCTYPE-ului, care verifica daca fisierul este o imagine (valida) si urca imaginea de pe PC-ul utilizatorului pe server, sa se bage intr-un fisier include si sa fie apelat prin functia PHP include().
<?php @include('includes/upload_file.inc.php'); ?>
Publica acest articol pe Twitter
Articole asemanatoare: