این آموزش در وبسایت mypress.ir و برای افرادی که در امر برنامه نویسی تازه کارند قرار داده شده است . در این آموزش یاد میگیرید که چگونه یک فایل را توسط php و یک فرم ساده html بر روی سرور منتقل کنید.
مرحله اول : ساخت فرم
در ابتدای کار ما نیاز به یک فرم html داریم که کاربر بتواند فایل خود را از درون حافظه رایانه اش انتخاب نمایید و بر روی سرور انتقال دهد .
برای این کار می توانیم از فرمی نظیر فرم زیر استفاده نماییم .
کد html ای که فرم بالا از آن ساخته شده است را می توانید در زیر ببینید
مرحله دوم : ساخت upload.php
// Configuration - Your Options
$allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './files/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// We'll start handling the upload in the next step
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>
در کد php بالا :
در آرایه allowd_filetypes$ نوع فایل های مجاز برای آپلود را مشخص می کنیم و با متغیر max_filesize$ بیشترین حجمی را که فایل می تواند داشته باشد را مشخص میکنیم و در متغیر بعدی مکانی ذخیره سازی فایل ها که باید خودتان بسازید را مشخص می کنیم .
در قسمت های بعدی اسکریپت ما فایل را چک می کند و از فیلتر های مشخص شده عبور می دهد . در قسمت اول اسکریپت چک می کند که نوع فایل مجاز است یا خیر . در قسمت دوم حجم فایل و در قسمت سوم قابل ذخیره بودن مقصد را چک می کند .
و در آخر اگر فایل با ملاک های مشخص شده سازگاری داشت بر روی سرور منتقل می شود .
امیدوارم مورد استفاده قرار بگیرد .
::گروه پاسارگاد::هات اسکریپت::آستالاویستا::هات کلیک::آی پی 2 لوکیشن::ایکس دیک::هات هاست::
Powered by HAM3D.net
