Help with retrieving/posting content from file to another

Hey all!!!
Have 2 issues that fall under the same issue, instead of creating 2 topic pages back to back I thought it would be better include both here-
1. Retrieving content to be placed on Bootstrap style card:

     <?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
      $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
      if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
      } else {
        echo "File is not an image.";
        $uploadOk = 0;
      }
    }

    // Check if file already exists
    if (file_exists($target_file)) {
      echo "Sorry, file already exists.";
      $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
      echo "Sorry, your file is too large.";
      $uploadOk = 0;
    }

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
      $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
      echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
      if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
      } else {
        echo "Sorry, there was an error uploading your file.";
      }
    }
    ?>

    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
         <form action="upload.php" method="post" enctype="multipart/form-data">
      <textarea rows="4" cols="50" name="comment" form="usrform">Share thoughts</textarea>
           Upload Image:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
    </form>
    <button type="submit" form="nameform" value="Submit">Submit</button>

          </div>
        </li>
    <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    <span style="font-size: 48px; color: #C0C0C0;">
    <i class="fas fa-camera"></i>
            </span>
    </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
    <form action="upload.php" method="post" enctype="multipart/form-data">
            <div class="col-lg-10">
                                 <input type="text" name="page_url" class="form-control" id="input_url" placeholder="Page embed URL" value="<?php echo !empty($userData['_url'])?$userData['url']:''; ?>">
                            <input type="submit" class="btn btn-primary" name="proSubmit">
             </div>
      </form>

    <--This  booststrap card section will contain output of the forms

     <div class="card hovercard">
      <div class="card-body info">
                      <div class="title">
                          <a href="#"><?php echo $record['uname']; ?></a>
                      </div>
            <div class="desc"> <a target="_blank"
    href="<?php echo $record['file']; ?>"><?php echo $record['text']; ?></a></div>
                      <div
    class="desc"><?php echo $record['url']; ?></div>
            <div

                  </div>

                      </a>
                  </div>
              </div>

2. Retrieving content to be placed on profile page:
<ā€“Update section

    <?php

     session_start();
     include "connect.php"; if(isset($_POST['edit']))
     {    $id=$_SESSION['id'];
        $uname=$_POST['uname'];
        $bio= $_POST['bio'];    $select= "select * from users where id='$id'";
        $sql = mysqli_query($conn,$select);
        $row = mysqli_fetch_assoc($sql);    $res= $row['id'];
        if($res === $id)
        {

           $update = "update users set uname='$uname',bio='$bio' where id='$id'";
           $sql2=mysqli_query($conn,$update);if($sql2)
           {
               /*Successful*/
               header('location:pro.php');
           }
           else
           {
               /*sorry your profile is not update*/
               header('location:proedit.php');
           }
        }
        else
        {
            /*sorry your id is not match*/
            header('location:proedit.php');
        } }?>


    <?php
    if(is_array($_FILES)) {
    if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
    $sourcePath = $_FILES['userImage']['tmp_name'];
    $targetPath = "images/".$_FILES['userImage']['name'];
    if(move_uploaded_file($sourcePath,$targetPath)) {
    ?>
    <img class="image-preview" src="<?php echo $targetPath; ?>" class="upload-preview" />
    <?php
    }
    }
    }
    ?>

    <--Edit profile section
    <form id="uploadForm" action="proupdate.php" method="post">
    <div id="targetLayer">No Image</div>
    <div id="uploadFormLayer">
    <input name="userImage" type="file" class="inputFile" /><br/>
    <input type="submit" value="Submit" class="btnSubmit" />

      <form action="proupdate.php" method="post">
       uname: <input type="text" name="uname"><br>

         bio: <input type="text" id="name" name="name" required
             minlength="4" maxlength="8" size="10"><br>

       <input type="submit" name="edit">

      </form>

      <--Section to display final results on profile page

      <div class="page-content"><?php include 'proupdate.php';?></div>

Greatly appreciate any helpā€¦thank ya so very much :blush:

Well, you showed us some code, but, you did not ask any questions. What do you want help with?

In general, profiles and content is never kept in files. That is a crazy way especially if the site is busy with many users. Normally these are kept in a database table. One for users and one for content. Anyway, please ask a question and we might be able to help!

1 Like

Sorry for the confusion @ErnieAlex ā€¦

My question is the php code correct so that the html code can work successfully?

I combined both so I didnā€™t have to create multiple post. I have my files setup correctly within my hostšŸ˜Š

Sir@ErnieAlex
Iā€™ve tried testing the php/html code for both and it didnā€™t work. Feel that Iā€™m missing something but canā€™t figure out where

Well, we can not just look at your code and guess what is wrong. You need to ā€œdebugā€ your code.
I see you are using a database for the profile. I think you need to learn how to debug you code. First, are you using Wamp or Xamp to test your code on, or do you have real server?

Next, are you getting error messages from the PHP code? If Wamp/Xamp, you can look in the root folder of that system on your hard disk and look in the logs folder. Erase all the logs there, run your code, look there again and see what errors you got. Post them for us and we can help with them. If on a server, you need to use the serverā€™s control panel to view the logs in and they are harder to read. Again, clear them, run your code and check the logs.

If you want to debug your code step by step, you can add this type of line to your codeā€¦

die("*** Got Here! ***");

Just add it in somewhere near the start of the page. ( In the PHP section of course!) And, run your page and see if your PHP script gets to that point. If it does, it will end the page and show the got-here notice. If it does not show, then move it up a few lines. If it shows, move it down further. In this manner, you can find out where the script is failing. And, once you locate the area it is failing, you can dump variables to see what data is in them and track down the problem.

A couple quick general things to look at are:
Make sure your ā€œuploadsā€ folder is exists on the server and has WRITE permissions set.
You are letting the user create the name for their profile image. Normally, you would assign the name to something like their profile ID number. Since the userā€™s table always contains an ID, it is a good way to save the image name as.

In general your code looks good. Hope these comments help you locate your errors.

1 Like

Thank ya again @ErnieAlex :blush:

Iā€™m running it on a real server so will look at the log they provide and will contact for more help if needed.

I appreciate your help it means alot!!!

Update us and we can helpā€¦

1 Like

Hi!

First off, I am not an expert.

The php below successfully uploads files to my little webpage. I got it from the web somewhere and adapted it for my purpose. In my case these are .mp3 files. I download them as a batch, because this is homework from students.

The form has fields for name, student number, email, a message if they need to say something and week number . I save those in a text file.

I always test these on my localhost first, putting lots of echo ā€˜blablaā€™ include ā€˜somethingā€™ exit() along the way, one after the other, until everything works. When one step works, I blank out that echo and go to the next one.
This is for testing the steps along the way, blank it out when the step works. If you have an array as variable, use print_r($array) to see it. If you are echoing anything before a header(ā€˜Location: /uploadFiles20EAP/upload_files_V1.html.phpā€™); statement, that header(ā€˜Location ā€¦ā€™) wonā€™t work, so use include during testing.

 echo '$variable is ' . $variable;
    include 'form.html.php';
    exit();

This is the code to upload a file

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
	$q1 = $_POST['cn'];
	$q2 = $_POST['sn'];
	$q3 = $_POST['email'];
	$q4 = $_POST['message'];
	$q5 = $_POST['week'];
	
  if (is_uploaded_file($_FILES['my_upload']['tmp_name'])) 
  { 
  	//First, Validate the file name
  	if(empty($_FILES['my_upload']['name']))
  	{
  		$_SESSION['error'] = "The file name is empty! <br>
  		Please select a file. <br>
		Your file could not be sent. <br>";
		header('Location: /uploadFiles20EAP/upload_files_V1.html.php');
  		exit();
  	}
 
  	$upload_file_name = $_FILES['my_upload']['name'];
  	//Too long file name?
  	if (strlen($upload_file_name)>50)
  	{
  		$_SESSION['error'] = "The file name is too long! <br>
  		Please make the file name shorter. <br>
		Your file could not be sent. <br>";
		header('Location: /uploadFiles20EAP/upload_files_V1.html.php');
  		exit();
  	}
 
  	//replace any non-alpha-numeric characters in the file name
  	$upload_file_name = preg_replace("/[^A-Za-z0-9 \.\-_]/", '', $upload_file_name);

 //set a limit to the file minimum size
  	if ($_FILES['my_upload']['size'] < 150000) 
  	{
		$_SESSION['error'] = "错čÆÆļ¼ļ¼ <br>	
		The file you are sending is too small. <br>
		Your file should be more than 150KB. <br>
		This is cannot be the homework. <br>
		Please check the file you are sending and send again. <br>
		Your file could not be sent. <br>";
		header('Location: /uploadFiles20EAP/upload_files_V1.html.php');
  		exit();        
    }
    
  	//set a limit to the file upload size
  	if ($_FILES['my_upload']['size'] > 9900000) 
  	{
		$_SESSION['error'] = "错čÆÆļ¼ļ¼ <br>	
		The file you are sending is too big. <br>
		The maximum size should be less than 6MB <br>
		Please send a smaller file or send the file in an email. <br>
		Your file could not be sent. <br>";
		header('Location: /uploadFiles20EAP/upload_files_V1.html.php');
  		exit();        
    }
 
    //Save the file $q5 is WeekX, $q2 is student number
    $dest=__DIR__.'/files/' . $q5 .'_' . $q2. '_' . $upload_file_name;
    if (move_uploaded_file($_FILES['my_upload']['tmp_name'], $dest)) 
    {
    	$_SESSION['error'] = "Your file was successfully uploaded";
    }
  }
1 Like

Sir @Pedroski55 this is so very coolā€¦thank yašŸ˜Š

Iā€™ve taken code from others and fixed to fit in with what I want as well.

Sponsor our Newsletter | Privacy Policy | Terms of Service