[SOLVED] Uploading picture on a blog post

General discussions related to php

Moderators: egami, macek, gesf

Post Reply
LaPtiteBete
New php-forum User
New php-forum User
Posts: 2
Joined: Thu Apr 08, 2021 12:04 pm

Thu Apr 08, 2021 12:20 pm

Hello everybody! :)

I'm a beginner in PHP, and I try to make a blog by following a tutorial on YouTube (which is very well done! but as it dates from 2015, there are small things that do not work properly anymore. I have managed to fixa few bugs so far, but now I'm completely stuck...)

I try to configure a function that allows uploading an image from your hard drive to your server.
The blog uses Materialize. I took the code from the Materialize website, because the one from the tutorial did not work (anymore).

Here is my write.php file:

Code: Select all

<!-- Formulaire de création des articles -->
<h2>Poster un article</h2>
<?php
	/* Commande d'envoi du formulaire si les champs sont renseignés */
	if(isset($_POST['post'])) {
		$title = htmlspecialchars(trim($_POST['title']));
		$content = htmlspecialchars(trim($_POST['content']));
		$posted = isset($_POST['public']) ? "1" : "0";
		$errors = [];

		/* Affichage d'erreur si tous les champs ne sont pas renseignés */
		if(empty($title) || empty($content)) {
			$errors['empty'] = "Veuillez remplir tous les champs.";
		}
		
		if(!empty($_FILES['image']['name'])) {
			$file = $_FILES['image']['name'];
			$extensions = ['.png','.jpg','.jpeg','.gif','.PNG','.JPG','.JPEG','.GIF'];
			$extension = strrchr($file,'.');

			/* Affichage d'erreur si l'extension n'est pas reconnue */
			if(!in_array($extension,$extensions)) {
				$errors['image'] = "Cette extension d'image n'est pas valide.";
			}
		}
		
		if(!empty($errors)) {
			?>
			<!-- En cas d'erreur, affichage de celle-ci -->
				<div class="card red">
					<div class="card-content white-text">
						<?php
							foreach($errors as $error) {
								echo $error."<br/>";
							}
						?>
					</div>
				</div>
			<?php
		} else {
		
			/* En l'absence d'erreur, exécution de la fonction d'envoi de l'article vers la base de 		données */
			post($title,$content,$posted);

			/* S'il y a une image, uploader celle-ci */
			if(!empty($_FILES['image']['name'])) {
				post_img($_FILES['image']['tmp_name'], $extension);
			} else {
				$id = $db->lastInsertId();
				header("Location:index.php?page=post&id=".$id);
			}
		}
	}
?>

<form method="post" enctype="mutlipart/form-data">
	<div class="row">
	
		<!-- Titre de l'article -->
		<div class="input-field col s12">
			<input type="text" name="title" id="title">
			<label for="title">Titre de l'article</label>
		</div>

		<!-- Contenu de l'article -->
		<div class="input-field col s12">
			<textarea class="materialize-textarea" name="content" id="content"></textarea>
			<label for="content">Contenu de l'article</label>
		</div>

		<!-- Bouton permettant de télécharger une image -->
		<div class="col s12">
			<div class="file-field input-field">
				<div class="btn col s2">
					<span>Image de l'article</span>
					<input type="file" name="image" class="col s12">
				</div>
				<div class="file-path-wrapper">
					<input class="file-path validate" type="text">
				</div>
			</div>
		</div>

		<div class="col s6">
			<!-- Curseur permettant de rendre l'article public -->
			<p>Public ?</p>
				<div class="switch">
					<label>
						Non
							<input type="checkbox" name="public" />
							<span class="lever"></span>
						Oui
					</label>
				</div>
			</div>
			<div class="col s6 right-align">
			<br/><br/>
			<!-- Bouton d'envoi de l'article -->
			<button class="btn" type="submit" name="post">Publier</button>
		</div>
	</div>
</form>
(I'm sorry... the comments are in french, but I can translate them if it helps (?))

Here is my write.func.php file :

Code: Select all

<?php
    /* Fonction d'envoi de l'article vers la base de données */
    function post($title,$content,$posted) {
        global $db;

        $p = [
            'title'     => $title,
            'content'   => $content,
            'writer'    => $_SESSION['admin'],
            'posted'    => $posted
        ];

        $sql = "
        INSERT INTO nic_posts(title,content,writer,date,posted) 
        VALUES(:title,:content,:writer,NOW(),:posted)
        ";
        $req = $db->prepare($sql);
        $req->execute($p);
    }

    function post_img($tmp_name, $extension) {
        global $db;
        $id = $db->lastInsertId();
        $i = [
            'id'    => $id,
            'image' => $id.$extension   // $id = 25 ; $extension = .jpg ; $id.$extension = 25.jpg
        ];
        $sql = "UPDATE nic_posts SET image = :image WHERE id = :id";
        $req = $db->prepare($sql);
        $req->execute($i);
        move_uploaded_file($tmp_name,"../img/posts/".$id.$extension);
        header("Location:index.php?page=post&id=".$id);
    }
The database connection is made with this main-functions.php file:

Code: Select all

<?php
    /*  Le "session_start()" est à mettre au début de chaque page qui utilise les sessions ($_SESSION). 
    Il est plus sûr de l'inclure à la page "main-functions.php". */
    session_start();

    /* Identifiants de connexion à la base de données */
    $dbhost = 'localhost';
    $dbname = 'nic_blog';
    $dbuser = 'root';
    $dbpassword = '';

    /* Fonction de connexion à la base de données */
    try {
        $db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname,$dbuser,$dbpassword,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
    } catch(PDOexception $e) {
        die("Une erreur est survenue lors de la connexion à la base de données.");
    }
?>
Sending post without image works well.
Sending post with an image also works, but the image is not uploaded to the "posts" directory; it is the default image: post.png, which is displayed instead...

Any idea, please ?... :(
Last edited by LaPtiteBete on Fri Apr 09, 2021 9:05 am, edited 1 time in total.
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 412
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Fri Apr 09, 2021 2:30 am

I personally would just save the whole filename along with the path in the database table:

Code: Select all

   /*
     * Set the paths to the correct folders
     */
    $dir_path = 'assets/uploads/';

    /*
     * Create unique image name.
     */
    $new_file_name = $dir_path . 'img-gallery-' . time() . '-600x400.' . $file_ext;

    move_uploaded_file($file_tmp, $new_file_name);
and call it a day.
Life is a fig newton of your imagination! https://www.miniaturephotographer.com
LaPtiteBete
New php-forum User
New php-forum User
Posts: 2
Joined: Thu Apr 08, 2021 12:04 pm

Fri Apr 09, 2021 9:04 am

Strider64 wrote:
Fri Apr 09, 2021 2:30 am
I personally would just save the whole filename along with the path in the database table:

Code: Select all

   /*
     * Set the paths to the correct folders
     */
    $dir_path = 'assets/uploads/';

    /*
     * Create unique image name.
     */
    $new_file_name = $dir_path . 'img-gallery-' . time() . '-600x400.' . $file_ext;

    move_uploaded_file($file_tmp, $new_file_name);
and call it a day.
Good afternoon Strider, and thank you very much for your answer , and for this function I didn't know yet !

Someone just found out that I inverted two letters in my code :
I wrote mutlipart, instead of multipart on line 60 :oops: :

Code: Select all

<form method="post" enctype="mutlipart/form-data">

I fixed it and it seems to work, hooray ! :D
Post Reply