Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once('../includes/db.php');
require_once('../includes/config.php');
require_once('../includes/generators.php');
require_once('../includes/modals.php');

ConnectToDatabase();

$table = 'users';
$user_id = 'user_id';
$userId = $_SESSION[$user_id];

$successMessage = null;
$post_id = null;

if (isset($_SESSION['post_data'], $_SESSION['post_files'])) {
    $_POST = $_SESSION['post_data'] ?? null;
    $_FILES['fileUpload'] = $_SESSION['post_files'] ?? null;
}

if (isset($_POST["type"]) && isset($_POST["pageId"])) {
    // Get common form data
    $title = isset($_POST["title"]) ? $_POST["title"] : "";
    $description = isset($_POST["desc"]) ? $_POST["desc"] : "";
    $type = $_POST["type"];
    $privacy = isset($_POST["privacy"]) ? $_POST["privacy"] : "";
    $price = isset($_POST["price"]) ? $_POST["price"] : "";
    $pageId = $_POST["pageId"];
    $pageUuid = isset($_POST["pageUuid"]) ? $_POST["pageUuid"] : "";
    $schedule_from = isset($_POST["datesFrom"]) ? $_POST["datesFrom"] : "";
    $schedule_to = isset($_POST["datesTo"]) ? $_POST["datesTo"] : "";
    $fileNumber = isset($_FILES['fileUpload']) ? count($_FILES["fileUpload"]["name"]) : 0; // Initialize $fileNumber
    $createdAt = date("Y-m-d H:i:s");
    $updatedAt = date("Y-m-d H:i:s");
    $shareLimit = (int) $_POST['share_limit'];

    function guidv4($data = null)
    {
        // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
        $data = $data ?? random_bytes(16);
        assert(strlen($data) == 16);

        // Set version to 0100
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        // Set bits 6-7 to 10
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

        // Output the 36 character UUID.
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }

    $postUuid = guidv4();
    $taggedUserIds;
    $blockedUserIds;

    // Check if the post type is 'message'
    if ($type === 'text') {
        $commentChecked = isset($_POST['commentCheckbox']) && $_POST['commentCheckbox'] === 'on';
        $commentValue = $commentChecked ? 1 : 0;

        $stmt = $mysqli_link->prepare("INSERT INTO page_posts (`post_uuid`, `page_uuid`, `pageId`, `ownerId`, `description`, `tagged`, `blocked`, `type`, `title`, `price`, `schedule_from`, `schedule_to`, `fileNumber`, `allow_comments`, `privacy`, `createdAt`, `updatedAt`, `share_limit`)
                                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)");
        $stmt->bind_param("ssissssssssiissssi", $postUuid, $pageUuid, $pageId, $userId, $description, $taggedUserIds, $blockedUserIds, $type, $title, $price, $schedule_from, $schedule_to, $fileNumber, $commentValue, $privacy, $createdAt, $updatedAt, $shareLimit);
        if ($stmt->execute()) {
            // Get the inserted post's ID
            $post_id = $stmt->insert_id;

            $messageContent = isset($_POST["text_message"]) ? $_POST["text_message"] : "fff";
            $stmt2 = $mysqli_link->prepare("INSERT INTO page_posts_texts (post_id, text_message) VALUES (?,?)");
            $stmt2->bind_param("is", $post_id, $messageContent);
            if ($stmt2->execute()) {
                $successMessage = "Posted successfully";
            } else {
                $dangerMessage = 'Text Not posted';
            }
        } else {
            $successMessage = "Error posting message.";
            echo "Error: " . $stmt->error;
        }

        $stmt->close();
    } else {
        // Handle other post types (image, video, book) only if files are present
        if ($fileNumber > 0 && isset($_FILES['fileUpload'])) {
            $taggedUserIds = isset($_POST['taggedUsers']) && !empty($_POST['taggedUsers']) ? implode(', ', array_map('intval', $_POST['taggedUsers'])) : "";
            $blockedUserIds = isset($_POST['blockedUsers']) && !empty($_POST['blockedUsers']) ? implode(', ', array_map('intval', $_POST['blockedUsers'])) : "";
            $commentChecked = isset($_POST['commentCheckbox']) && $_POST['commentCheckbox'] === 'on';
            $commentValue = $commentChecked ? 1 : 0;

            $stmt = $mysqli_link->prepare("INSERT INTO page_posts (post_uuid, page_uuid, pageId, ownerId, description, tagged, blocked, type, title, price, schedule_from, schedule_to, fileNumber, allow_comments, privacy, createdAt, updatedAt, share_limit)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssissssssssiissssi", $postUuid, $pageUuid, $pageId, $userId, $description, $taggedUserIds, $blockedUserIds, $type, $title, $price, $schedule_from, $schedule_to, $fileNumber, $commentValue, $privacy, $createdAt, $updatedAt, $shareLimit);

            if ($stmt->execute()) {
                // Get the inserted post's ID
                $post_id = $stmt->insert_id;

                // Handle file uploads for image, video, book posts
                for ($i = 0; $i < $fileNumber; $i++) {
                    $FileName = $_FILES["fileUpload"]["name"][$i];
                    $FileTempName = $_FILES["fileUpload"]["tmp_name"][$i];
                    $uploadError = $_FILES["fileUpload"]["error"][$i];

                    if ($uploadError !== UPLOAD_ERR_OK) {
                        $dangerMessage = 'File upload error for file: ' . $FileName . ' (Error code: ' . $uploadError . ')';
                        continue;
                    }

                    // Define the folder for storing uploaded files
                    $folder = __DIR__ . '/posts/images/';
                    if (!file_exists($folder)) {
                        mkdir($folder, 0777, true);
                    }

                    // Define the target path for the uploaded file
                    $targetPath = $folder . $FileName;

                    // Check if the uploaded file exists
                    if (file_exists($FileTempName)) {
                        // Attempt to move the file to the destination
                        if (move_uploaded_file($FileTempName, $targetPath)) {
                            // File moved successfully
                            // Proceed with inserting file details into the database
                            // Example: Insert into page_posts_images (post_id, file_path) VALUES (?, ?);
                        } else {
                            // Error moving file
                            $dangerMessage = 'Error moving file: ' . $FileName;
                            continue; // Skip to the next file
                        }
                    } else {
                        // Uploaded file does not exist at temporary location
                        $dangerMessage = 'Uploaded file does not exist at temporary location: ' . $FileTempName;
                        continue; // Skip to the next file
                    }
                }
            } else {
                $dangerMessage = "Error posting content.";
            }

            $stmt->close();
        } else {
            $successMessage = 'No files found';
        }
    }
}

echo json_encode($dangerMessage);
?>


What I have tried:

I want to upload a file before posting data but brings an error. "Uploaded file does not exist at temporary location: D:\\xammp\\tmp\\phpA020.tmp"
Posted
Comments
Andre Oosthuizen 23-Feb-24 16:30pm    
The answer lies in the description... The file you are trying to access is NOT in the path that you specified...
[EDIT] Just realized this is an old post a few days old... AI generated code, no idea how to solve the issue apart from copy and paste, ouch!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900