Doubt Simple School System

Asked

Viewed 130 times

2

Well I’m doing a job for college, I’m already halfway through, but to do the precise end:

  • The teacher can register a pdf/image in his area.
  • And the student on his page can see/download this attachment.

What I have so far saves only images.

The form to save the attachment.

<form action="gravar.php" method="POST" enctype="multipart/form-data"> 
    <label for="imagem">Imagem:</label> 
    <input type="file" name="imagem"/> <br/> 
    <input type="submit" value="Enviar"/>
</form>

And the part to save the image in the database.

<?php 
$imagem = $_FILES["imagem"];
$host = "localhost";
$username = "root"; 
$password = ""; 
$db = "sistema"; 

if ($imagem != NULL) { 
    $nomeFinal = time().'.jpg'; 
    if (move_uploaded_file($imagem['tmp_name'], $nomeFinal)) { 
        $tamanhoImg = filesize($nomeFinal);
        $mysqlImg = addslashes(fread(fopen($nomeFinal, "r"), $tamanhoImg));

        mysql_connect($host,$username,$password) or die("Impossível Conectar"); 
        @mysql_select_db($db) or die("Impossível Conectar"); 
        mysql_query("INSERT INTO anexo (PES_IMG) VALUES ('$mysqlImg')") or die("O sistema não foi capaz de executar a query"); 

        unlink($nomeFinal);
        header("location:exibir.php");
    }
} else { 
    echo "Você não realizou o upload de forma satisfatória."; 
} 
?>

And here I display the recorded image, in a PHP:

<?php 
$host = "localhost"; 
$username = "root"; 
$password = ""; 
$db = "sistema"; 

mysql_connect($host,$username,$password) or die("Impossível conectar ao banco."); 
@mysql_select_db($db) or die("Impossível conectar ao banco"); 

$result = mysql_query("SELECT * FROM anexo") or die("Impossível executar a query"); 
while ($row = mysql_fetch_object($result)) { 
    echo "<img src='getImagem.php?PicNum=$row->PES_ID' \">"; 
} 

?>

But what I would like to show this attachment only when the student in his area clicked on the "attachment" link and he would see only the attachment to that work and not all the others.

  • 3

    Poorly indented code is the root of many evils... Here is a tutorial on how to do this correctly that appears on the first page of google: https://www.youtube.com/watch?v=NfS4HpRZciA

1 answer

1

To save a file in a database and download it later, it is necessary to save the mimetype of the file, name, size, etc.

For this it is necessary to create a table as follows

CREATE TABLE upload (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(30) NOT NULL,
    type VARCHAR(30) NOT NULL,
    size INT NOT NULL,
    content MEDIUMBLOB NOT NULL,
    PRIMARY KEY(id)
);

The guy MEDIUMBLOB up to 16 megabytes more or less, however there are the following types that must be used according to your need.

  • TINYBLOB
  • BLOB
  • MEDIUMBLOB
  • LONGBLOB

To recover the information from the file being uploaded there is the global variable $_FILES which has the following information:

// O nome original do arquivo 
$_FILES['userfile']['name'];

// O mimetype do arquivo. Esta informação é dada pelo browser do usuário.
// Por exemplo para uma imagem JPG seria "image/jpg"
$_FILES['userfile']['type'];

// O tamanho da imagem em bytes.
$_FILES['userfile']['size'];

// O nome do arquivo temporário criado quando o servidor recebe a
// requisição, e armazena para que o arquivo possa ser trabalhado.
$_FILES['userfile']['tmp_name'];

// O código de erro associado ao arquivo, caso houver. 
$_FILES['userfile']['error'];

To write to the database just create the following script

save php.

$host = "localhost";
$username = "root"; 
$password = ""; 
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados."); 
mysql_select_db($db) or die("Não foi possível selecionar o banco de dados."); 

if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
    $fileName = $_FILES['userfile']['name'];
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];

    $fp      = fopen($tmpName, 'r');
    $content = fread($fp, filesize($tmpName));
    $content = addslashes($content);
    fclose($fp);

    $query = "INSERT INTO upload (name, size, type, content ) VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

    mysql_query($query) or die('Error, query failed');
}
mysql_close(); // Não esqueça de finalizar a conexão.
header("Location: listar.php");
exit(); // Sempre que quiser fazer algum redirecionamento, finalize o script para evitar erros no envio de cabeçalho.

Create a page to list the files for the user click on the links and download.

list.php

<?php

$host = "localhost";
$username = "root"; 
$password = ""; 
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados."); 
mysql_select_db($db) or die("Não foi possível selecionar o banco de dados."); 

?>

<html>
    <head>
        <title>Arquivos</title>
    </head>
    <body>
    <?php

    $query = "SELECT id, name FROM upload";
    $result = mysql_query($query) or die('Error, query failed');
    if (mysql_num_rows($result) == 0) {
        echo "Database is empty <br>";
    } else {
        while (list($id, $name) = mysql_fetch_array($result)) {
            echo '<a href="download.php?id=' . $id . '">' . $name . '</a> <br>';
        }
    }
    ?>
</body>
</html>
<?php mysql_close() ?>

And the file to allow the download of the file

download php.

<?php
if (isset($_GET['id'])) {
    $host = "localhost";
    $username = "root"; 
    $password = ""; 
    $db = "sistema";

    mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados."); 
    mysql_select_db($db) or die("Não foi possível selecionar o banco de dados.");

    $id    = (int) $_GET['id'];
    $query = "SELECT name, type, size, content FROM upload WHERE id = '$id'";

    $result = mysql_query($query) or die('Error, query failed');
    list($name, $type, $size, $content) = mysql_fetch_array($result);

    header("Content-length: $size");
    header("Content-type: $type");
    header("Content-Disposition: attachment; filename=$name");

    echo $content;

    mysql_close();
    exit();
}

This example is used to save files to the database, but you can save the actual image to the server and store in the database only the image name for download, so you wouldn’t need the file download.php and your files would look like this:

save php.

The attached field in the database table now stores only the file name.

$host = "localhost";
$username = "root"; 
$password = ""; 
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados."); 
mysql_select_db($db) or die("Não foi possível selecionar o banco de dados."); 

if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
    $fileName = $_FILES['userfile']['name'];
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];

    $pasta = __DIR__ . '/';
    $nomeFinal = time().'.jpg'; 
    if (move_uploaded_file($imagem['tmp_name'], $pasta . $nomeFinal)) { 
        $query = "INSERT INTO upload (anexo) VALUES ('$nomeFinal')";
        mysql_query($query) or die('Error, query failed');
    }
}
mysql_close(); // Não esqueça de finalizar a conexão.
header("Location: listar.php");
exit(); // Sempre que quiser fazer algum redirecionamento, finalize o script para evitar erros no envio de cabeçalho.

list.php

<?php

$host = "localhost";
$username = "root"; 
$password = ""; 
$db = "sistema";

mysql_connect($host,$username,$password) or die("Impossível conectar com o banco de dados."); 
mysql_select_db($db) or die("Não foi possível selecionar o banco de dados."); 

?>

<html>
    <head>
        <title>Arquivos</title>
    </head>
    <body>
    <?php

    $query = "SELECT id, anexo FROM upload";
    $result = mysql_query($query) or die('Error, query failed');
    if (mysql_num_rows($result) == 0) {
        echo "Database is empty <br>";
    } else {
        while (list($id, $anexo) = mysql_fetch_array($result)) {
            echo '<a href="caminho/da/pasta/' . $anexo . '" target="_blank">' . $anexo . '</a> <br>';
        }
    }
    ?>
</body>
</html>
<?php mysql_close() ?>
  • thanks friend , already helped me a lot =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.