Jump to content

TechnoDiver

Members
  • Posts

    203
  • Joined

  • Last visited

Posts posted by TechnoDiver

  1. Ok, I was busy trying to figure out how to change the php user that I never thought about changing permissions for 'daemon'. I've only ever seen my username and 'root' as owners or groups so was thinking I had to change the php user to my username. Thanks for the patience.

    I do have another question that happened while I was messing about with permissions that maybe you could answer - instead of changing the owner to 'daemon' I had decided to make a group, give it full permissions in the path and then add 'daemon' to that group. That didn't work. Since 'daemon' was also a group I eventually just made it the group owner of the relevant directories and files.

    My question is, since the group that is also my username was already the group owner, why couldn't I have just extended the group permissions and add the 'daemon' user to that group and have it work? I really thought that would work, but it didn't. Any good explanation as to why??

  2. 43 minutes ago, gw1500se said:

    No it can't. Add that code to the PHP file giving you the error then run that code as a user normally would from a web browser. In the case of Linux, the user will normally be 'apache'.

    Ok, I see that now. It comes back as daemon. I was just doing some searching around trying to work out the safest way to change this and I must have found a dozen or more different ways, suggestions etc etc. When I follow up on what they're saying I don't find anywhere that it says a user is 'daemon'  (only my username or root) so I have no idea which one to listen to and feel like I'm in territory where I shouldn't be experimenting too boldly. What would you do here?

  3. 8 hours ago, requinix said:

    Your user account is the owner and you've given yourself all the necessary permissions. But is PHP running as your user account?

    If that can be accurately checked by going into PHP interactive mode and entering

    echo exec('whoami');

    or

    print shell_exec( 'whoami' );

     

    Then yes, it's running as my user account

  4. Can someone please give me some guidance on how to deal with the following warning

    Quote

    Warning: move_uploaded_file(../usernet/img/60ff59c9f0a830.45733158.jpg): Failed to open stream: Permission denied in /opt/lampp/htdocs/site/admin/add_post.php on line 23

    Warning: move_uploaded_file(): Unable to move "/tmp/phpXNeGsj" to "../usernet/img/60ff59c9f0a830.45733158.jpg" in /opt/lampp/htdocs/site/admin/add_post.php on line 23

    All directories and files in the path have full owner permissions and I've made myself the owner of them all (I'm on a linux system). I've also done the same with the /tmp folder. I can't even think of anything else to change and haven't found anything online that solves the issue.

    in case it's needed, the php is as follows:

    <?php
    require("assets/initializations.php");
    
    if(isset($_POST['add_post']) && !empty($_FILES['post_image'])) {
        $filename = $_FILES['post_image']['name'];
        $file_tmp_name = $_FILES['post_image']['tmp_name'];
        $filesize = $_FILES['post_image']['size'];
    
        $file_ext = explode('.', $filename);
        $file_act_ext = strtolower(end($file_ext));
        $allowed = array('jpeg', 'jpg', 'png', 'gif');
    
        if(!in_array($file_act_ext, $allowed)) {
            header("Location: add_post.php?message=file_type_not_allowed");
        } else {
            if($filesize > 10000000) {
                header("Location: add_post.php?message=file_too_large");
    
            } else {
                $file_new_name = uniqid('', true) . "." . $file_act_ext;
                $dir = "../usernet/img/";
                $target_file = $dir . basename($file_new_name);
                move_uploaded_file($file_tmp_name, $target_file);
                echo "<script>alert('Image uploaded successfully');</script>";
            }
        }
    }

    I do get the javascript alert that's it's been successfully uploaded, but the image doesn't make it into the specified directory and I get the warnings at the top. I'm also, probably obviously from the path, using XAMPP server for development. TIA

  5. Those methods actually execute the query?!

    I feel dumb, it looks to me that $query is just being assigned a mysql query string to be used later, but yea, I get it now

    When you say that they could just return the result do you mean something like this?? ->

    $result = mysqli_fetch_array($query);
    return $result;

    If they would have just returned the result, as in my sample code directly above, I would have completely understood it as my confusion came from $query not being used again in the method

    Thanks for clarifying, it still doesn't feel right but I'll just get use to it lol

  6. I've been scrolling through some 3rd party code trying to get ideas and a deeper understanding of PHP. I came across these 2 simple methods in a class entitled 'Category' ->

    public function deleteCategory($id) {
        $query = mysqli_query($this->conn, "DELETE FROM top_categories WHERE top_cat_id=$id");
        if($query) {
            return true;
        } else {
            return false;
        }
    }
    
    public function updateCategory($id, $category) {
        $query = mysqli_query($this->conn, "UPDATE top_categories SET top_cat_title='$category' WHERE top_cat_id=$id");
        if($query) {
            return true;
        } else {
            return false;
        }
    }

    They're simple enough and work perfectly in the context of their functionality, but I don't understand how. Their instantiation and calls are ordinary but I don't understand how they do what they do. To me (a very untrained eye) they look like they initialize a variable ($query) and then check if it's initialized or not without actually doing anything with it.

    They've both been instantiated in a file that is included at the top of each page and the method calls are seemingly normal ->

    if(isset($_POST['edit_cat'])) {
      $cat_obj->updateCategory($cat_id, $_POST['cat_title']);
      header("Location: category.php?message=category-updated");
    }
    
    if(isset($_GET['cat_id'])) {
      $cat_obj->deleteCategory($_GET['cat_id']);
      header("Location: category.php?message=deleted-successfully");
    }

    Can someone with the time and will please explain how these 2 methods do the things they do?

  7. OK, so I got this issue working but it is ugly, to say the least. I realized what was actually confusing me was how to get the header() function at the top of the page and still work with the require() statements I had up there (require_once('load.php') and require('header.php').

    This is what I had in header.php -

    require_once("../../load.php");
    require('class/User.php');
    require('class/Category.php');
    
    $user = $user_obj->get_username(); 
    $cat_obj = new Category($conn, $user);

    but there's also HTML in header.php so I couldn't put the header() function before it nor after it in the add_category.php file (if I put it before then it didn't work because of the HTML getting sent before the header() function, and if I put it after than the necessary classes weren't instantiated in time.

    So I removed all the above code from the header.php file and put it at the top of both the add_category.php file AND the category.php file that it redirects to.

    It also seems completely wrong to me that the require_once('load.php') isn't in the header.php file and that all that code needs to be repeated in both pages rather than just in the header.php file.

    Is this correct or is there a far more efficient way that this could have been done?

  8. OK, thank you all for your responses. All of them got me thinking in a different way. I do alright with Python but I find with PHP in web development it's much harder for me to visualize the flow of data because of the different forms and protocols all working together, it's a level of abstraction I'm still training my mind for.

    Thanks again and I"ll work on cleaning up this code. The structure Mac_gyver gave will help for sure

     

    I think what really has me a bit lost on this particular problem is, if the redirect has to go on top, how to connect that to an action later in the page? I'm not even sure what to search for about this particular issue, do any of you have any links to resources where I could learn about this exact thing?

  9. Barand, thank you for your reply.

    I'm still a little lost on how to implement what you just taught me into this file. I'm sorry if I sound totally stupid.

    here is the complete add_category.php file -

    <?php require_once("../../load.php"); ?>
    
    <?php require('includes/header.php'); ?>
    
      <section id="container" class="">
    
        <?php require('includes/top_nav.php'); ?>
    
        <?php require('includes/side_bar.php'); ?>
        
        <section id="main-content">
          <section class="wrapper">
            
            <div class="row">
              <div class="col-lg-12">
                <h3 class="page-header"><i class="fa fa-laptop"></i> Add Category</h3>
                <ol class="breadcrumb">
                  <li><i class="fa fa-home"></i><a href="index.php">Home</a></li>
                  <li><i class="fa fa-laptop"></i>Category</li>
                  <li><i class="fa fa-plus"></i>Add Category</li>
                </ol>
              </div>
            </div>
            
            <?php
                if(isset($_POST['add_cat'])) {
                    $cat_obj->add_category($_POST['cat_title']);
                    header("Location: category.php");
                }
            ?>
    
            <div class="container row">
             
                <form action="" method="post" role="form" class="col-lg-6">
                    <h3>Add Category</h3>
                    <div class="form-group">
                        <input type="text" name="cat_title" placeholder="Category" class="form-control">
                    </div>
                    <div class="form-group">
                        <input type="submit" name="add_cat" placeholder="Add Category" class="btn btn-primary">
                    </div>
                </form>
    
            </div> <!-- end row-->
    
          </section> <!-- end wrapper -->
        </section> <!-- end main content-->
      </section> <!-- end container -->
      
      <!-- footer includes scripts -->
      <?php require('includes/footer.php'); ?>

    From what you're saying I'm getting this warning because of the HTML that appears before the php class call (if statement). I've tried putting that PHP code before the html and it doesn't redirect to category.php although I don't get the warning message either, but it does add the category to the db. Putting the html inside the php tags obviously just results in a lot of red flagged errors from my IDE, as would happen if I took out the ?> part of the tag

     

    Is there a more correct way to redirect to category.php at the end of that if statement? Again, sorry if I'm sounding stupid but I don't understand how to properly implement what you've responded.

  10. I've got an issue with a header redirect that is confusing me. I haven't been able to find any similar problems that have help me solve it and the PHP man page on headers isn't helping me either.

    <?php
      if(isset($_POST['add_cat'])) {
          $cat_obj->add_category($_POST['cat_title']);
          header("Location: admin/category.php");
      }
    ?>

    This code is in a file called add_category.php which is in the same directory as the category.php file I want it to redirect to.

    without the 'header..' line it works perfectly; but with the 'header..' line I get the following warning -

    Quote

    Warning: Cannot modify header information - headers already sent by (output started at /opt/lampp/htdocs/**/**/admin/add_category.php:2) in /opt/lampp/htdocs/**/**/admin/add_category.php on line 30

     

    but there's no other place sending headers (that I can see) and to my inexperienced eye it seems like it's cyclical logic as it's saying the same line I want to send the redirect is the one that already sent it. Would someone mind giving me an ELI5 breakdown of why this isn't working properly and maybe a route to solving the problem, please? TIA

  11. requinix, thank you. I was just coming back to here to post that I figured it out. It was indeed that I did not need the /opt/lampp/htdocs/ segment of the path.

    Thanks again to you and kicken for your responses

  12. Hi kicken, thanks for the response.

    I'm building a registration form and writing the user class right now. Eventually the photos will be uploaded to the db but right now it's just my info in the db so I can experiment with my code. I'm to the point I wanted to play around with the profile pic and simply wanted to insert one I have saved locally into my local phymyadmin as I haven't scripted the downloader yet.

    Nothing I do will display this image in the page, just the broken image icon. Again this is all in local development, I'm using XAMPP so the page isn't being served via https. I've tried file://localhost/[site name]/img/name.png and that doesn't work either, no problem if I use a web image url in the db (https://......). I don't get it. Maybe it's late and I'm being dumb. but I can't get this photo to show. The image is obviously stored in the site directory on XAMPP - /opt/lampp/htdocs/[site name]/img/[image name]..

  13. I hope this is the appropriate forum for this question. If not I apologize

    I'm trying to put a locally stored pic in a phpmyadmin db table. Not upload it to the db but put the path in the text field of the profile pic category. I can paste the link to a web photo in the text field area and it works fine, so my script is working, but for some reason I get the broken photo icon and not the photo when I use the local path in the same way that a web address works.

    I've used /opt/lampp/htdocs/[site name]/img/name.png and that doesn't work.

    I've tried localhost/[site name]/img/name.png and that doesn't work either.

    Some research got me to set the type as LONGBLOB and store the photo in the db, but that doesn't work either.

    Is there a special format for local paths that needs to be used? I can't find anything about that if there is.

    like I said - a url to an online photo works but I can't get a local path to work. Any guidance? TIA

  14. Ha! yea, I started to after that stray colon and then decided that I hadn't really "fixed" anything.

    MacGyver had pointed out that I had connected to the db twice, so I rewrote the code eliminating the constants in functions.php

    The code you just helped me with in the other thread is the rewrite of the code I posted in my OP here. Because it turned out to be sloppy coding I focused on that and never really got around to figure out how to get VSCodium to recognize them globally

     

  15.  I've had to rearrange a lot of code and I've been trying to put together a prepared statement in a registration form. I'm having a really hard time and being very new to PHP the issue is really confusing for me.

    first, I have this function:

    //PROCESS DB
    function process_database($post) {
      global $table;
      global $conn;
    
      //THIS FUCKING THING IS DRIVING ME
      //check database connection
      if ($conn->connect_error) {
        return false;
    
      } else {
        if($statement = $conn->prepare("INSERT INTO $table (username, email, password) VALUES ( ?, ?, ? )")){
          
          $username = $post['username'];
          $email = $post['email'];
          $password = $post['password'];
    
          $statement->bind_param("sss", $username, $email, $password);
    
          $statement->execute();
          
          //DEBUGGING
          echo "Added: ".$username.", ".$email.", ".$password."<br>";
    
          if(!$statement->execute()){
            printf("Connect Failed: %s\n", $conn->connect_error);
          } else {
            echo 'fuckin ay!!!';
          }
          //END DEBUG BLOCK
    
        } else {
          return false;
        }
      }
      return true; 
    }

    The issue is very strange. I'll post the function call so it's clear:

    //process database actions
      if (!process_database($data) ) {
        return array( 'status' => 0, 'message' => 'Unable to process database request' );
      }

    When I run the registration.py without process_database() everything is fine, so I'm confident in the error processing. Here's where it get weird -

    when I process the form

    Quote

    echo "Added: ".$username.", ".$email.", ".$password."<br>";

    is returned from the //DEBUGGING BLOCK but I also get back the error from the following if statement - "Connection Failed: ...."

    BUT I also get back the registration successful message that only shows if the function returns true

    In short, it's giving me 2 positive affirmations but also the Connection failed message and of course it's not adding anything to the database. I've been working this function all day, and I'm lost for answers. What's going on with this code? I can't see where I've gone wrong

  16. 12 minutes ago, mac_gyver said:

    ^ this is the problem. it apparently doesn't know that the point of constants are that they are global.

    What? This is normal behaviour in VScodium? Even with the require() of the config.php file that contains their assignment? Even with intelliphense and all the other PHP extensions I'm using?

    How do I fix it? Is there a fix?

  17. 2 minutes ago, mac_gyver said:

    what makes you think that?

    since you are making a database connection in config.php, why are you making another one inside the process_database() function? making a database connection is one of the slowest operations you can do on a page. you are doing it at least twice.

    l think it's not recognizing them because there's red error messages all over them saying they're undefined. I use VSCodium and it doesn't let you save the file for running with critical errors

    This is what the intellphense on VSCodium says on the hover over in function.php:

    Quote

    Undefined constant 'DB_USERNAME'.intelephense(1011)

    but it says that for them all, this is just the one I hovered over for the example

    Regarding the dual connection - I was just going over it all again and noticed this might be the issue, I see what you're saying. I'll fix it, is it the issue with my constants or is this a separate thing?

  18. Kicken - thanks for your response.

    I've made the calls on register.php like this:

    <?php require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php'); ?>
    <?php require_once( 'assets/functions.php' );

    at the top of functions.php I have this:

    //show errors
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    //require config file
    require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php');

    my config.php looks as it did in my OP and is located in the same directory as htdocs (research told me it's best to keep it outside the project) and I know that path works as I have another function in functions.php that queries the db for identical usernames and that function works as expected.

    the site structure is set up like this:
     

    Quote

     

    HTDOCS/SITENAME

    |- assets

    |-loginphp

          | -- assets

                |--- functions.php

         |-- irrelevant directory

         |-- includes

         |-- register.php

    |- irrelevant directory

    | - another irrelevant directory

    | - index.php

     

    everything happening in this script is happening inside the loginphp directory except for config/config.php is outside htdocs

  19. I've been working on a registration form and it seems like the better I get at solving more complex issues the smaller issues plague me the most.

    I've got the following function:

    //process database actions
    function process_database($post) {
      global $table;
    
      //connect to database
      $connect_db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
    
      //check database connection
      if ($connect_db->connect_error) {
        return false;
      } else {
        if ($stmt = $connect_db->prepare( "INSERT INTO $table (firstname, lastname, username, email, password) VALUES ( ?, ?, ?, ?, ? )" ) ) {
          $stmt->bind_param(NULL, $firstname, $lastname, $username, $email, $password);
    
          $firstname = $post['firstname'];
          $lastname = $post['lastname'];
          $username = $post['username'];
          $email = $post['email'];
          $password = $post['password'];
    
          if (!$stmt->execute()) {
            return false;
          }
        } 
      }
    
      return true;
    }

    This is in a functions.php file. The issue is in the $connect_db assignment that has the constants from the config.php file in it.

    That file looks like this:

    <?php
    ob_start();
    session_start();
    
    $timezone = date_default_timezone_set("America/xxxxxxx");
    
    $whitelist = array('username', 'email', 'email2', 'password', 'password2');
    //TODO here I've removed firstname and lastname from the whitelist as they're optional
    //may add them back and try to iterate around them in the future
    
    $table = 'users';
    
    define('DB_HOST', 'localhost');
    define('DB_USERNAME', 'root');
    define('DB_PASSWORD', '');
    define('DB_NAME', 'means');
    
    $conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
    
    if($conn->connect_errno) {
    
        printf("Connect Failed: %s\n", $conn->connect_error);
        exit();
        
    }
    
    ob_end_flush();
    ?>

    The constants defined in config.php are not being recognized in functions.php. I understand that constants are global and available throughout a script.

    I've connected to two files with the following line:

    //require config file
    require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php');

    as I have the config/config.php outside htdocs. I know this works because of a db query to check uniqueness of username that works properly.

    Why are these constants coming back as undefined in the process_database().function.php? Nothing I've tried works and I've run out of ideas. TIA

  20. Right, Right. I have that linked manual page open too and read about that, it didn't click what it meant. Thank you

     

    Out of curiosity, why is specifying a length required when an index was specifically used? Is there a use case where this is preferred or necessary?

    I'm only a very basic level with programming but I originally learned in Python and I've never seen this be necessary there

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.