Jump to content

Drongo_III

Members
  • Posts

    579
  • Joined

  • Last visited

Posts posted by Drongo_III

  1. That's great.

     

    Out of interest. If I perform the check outlined above to see if session ID isset are there any potential security issues with just performing that check? OR should i also do additional checks?

     

    Thanks for all your help btw guys!

     

     

    I don't really see reason to store there password in a session, a username is fine though, and track them through their user id and all should be fine ;).

  2. Thanks

     

    That makes a lot of sense.

     

    If I wanted to track a specific user - lets say I wanted them to be able to post an entry on the site - would it be bad practice to use their username and/or their encrypted password as session variables to track them as them?

     

     

    You could use $_session['id'] which is a unique I'd that you van assign each user that is registered. You can then use that to see if the session Id is set. If it isn't, you can use header() to redirect the unregistered users to the login/register page. Hope this helps

  3. Hi Guys

     

    New to php so stick with me.

     

    I'm trying to create a simple login script that will grant a user access to content that is only viewable by those people who are logged in.

     

    I'm ok doing the login part and authenticating the password etc. But once the user gets directed to the content page how can I ensure that only a registered user who is logged in sees that page? (probably missing something very obvious here). I've tried reading around but not found much on this specific question.

     

    Should I set the user's username and password (which is encrypted) as session variables and authenticate them as the first stage of each page they visit?  Or is there a better way of doing this?

     

    Don't worry, not looking for you to write the code just a description of the best way of doing it would be great!

     

    Thanks,

     

    Drongo

  4. Fabulous! Thank you so much for your help! It all makes a lot more sense now :)

     

     

    Exactly! Just that this part:

    <?php
    move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $new_filename);
    echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    ?>

     

    could be put in a conditional, so that you know if the upload works:

    <?php
    if (move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $new_filename)) {
         echo 'Stored in: upload/' . $new_filename;
    } else {
         echo 'An error occurred while uploading.';
    }
    ?>

  5. Hi Guilty

     

    Thanks for such a quick reply.

     

    Sorry to labour the point. I've incorporated your code into mine. Is what I've done correct? It works fine but I want to be sure I'm doing it the right way. :)

     

    <?php
    
    
    
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 200000000))
      {
      
    
    
    $file = $_FILES['file']['name'];
    
    //get the file extension, we'll need it to construct the new filename
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    
    $new_filename = "any_filename_you_want2222332.$ext";
    
    
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $new_filename);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    
    
          }
    
    else
      {
      echo "Invalid file";
      }
    
    
    
    
    
    
    
    
    // ############ THIS IS THE DATABASE PART ###############
    
    
    
    $title = $_POST['title'];
    
    $body = $_POST['body'];
    
    
    
    $con = mysql_connect("localhost","zzzzzzzz_testing","RB.x;)c*=a4z");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    
    // Create table
    
    mysql_select_db("zzzzzzzz_newtest", $con);
    
    
    
    mysql_query("INSERT INTO page_stuff (body_text, title, image)
    VALUES ( '$body', '$title', '$image_name')");
    
    
    mysql_close($con);
    
    
    
    
    ?> 
    
    
    
    
    
    
    
    

     

     

     

    Instead of $_FILES['file']['name'], you can use whatever you want. Take this example:

     

    <?php
    $file = $_FILES['file']['name'];
    
    //get the file extension, we'll need it to construct the new filename
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    
    $new_filename = "any_filename_you_want.$ext";
    ?>

  6. Hi Undertaker

     

    I'm new to php and I came across this same thing a few weeks ago.

     

    The explanation of it is well covered in the post above.

     

    One thing worth noting (if you don't already know) is that you can access query strings by using the $GET array.

     

    Just thought that was worth mentioning as it wasn't obvious to me...or maybe I'm just slow!

     

    Drongo :)

  7. Hi guys

     

    Still learning php and have what is probably quite a newbie question!

     

    I have an upload script (below) that uploads images but I can't work out how to change the name of the file before it's moved from it's temporary location to the 'uploads' directory. I've tried a few things but nothing seems to work and I'm a bit stuck.

     

    The ultimate goal is to time stamp the new image name so that it will be unique but the first step is to figure out how to change the name.

     

    Any help would be much appreciated!

     

    Thanks,

     

    Drongo

     

    The script I'm using is as follows:

     

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 200000000))
      {
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
    
        if (file_exists("upload/" . $_FILES["file"]["name"]))
          {
          echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    
          }
        }
      }
    else
      {
      echo "Invalid file";
      }
    

     

  8.  

    Thanks for all the info Quick!

     

    I think I have a much better idea of how it's done now. Looks to be a case of appending IDs to each link via query strings and i suppose i can then use that info to dynamically load specific content from the database. Going to have a fiddle and will let you know if i have any questions.

     

    Thanks loads for all the links and info! :)

     

    Let me give you a few demo of codes I wrote up and can look at them a bit.

     

    A simple navigation

    http://get.blogdns.com/navigation/

     

    This one creates single posts

    http://get.blogdns.com/dynaindex/post-variable.php

     

    Here's some pagination ones.

    http://get.blogdns.com/paginate/

    http://get.blogdns.com/dynaindex/paginate.php

     

    A post in the forum parsing urls

    http://www.phpfreaks.com/forums/index.php?topic=319755.0

     

    This is the function code to find path one

    http://www.phpfreaks.com/forums/index.php?topic=319755.msg1506929#msg1506929

     

    If any more questions feel free to ask.

  9. Hi Quick

     

    Thanks for your post. I get what you've said but that just leaves me with the mystery of how you tell the script what look for. So if I've clicked on a link for www.mysite.com/4, then how do i tell the script that the user has clicked on a link and wants to visit page 4?

     

    Sorry if i'm being slow and missing something obvious :/

     

     

    That unique key of 4 you speak of could be a GET value, doing an if/else statement of the GET could determine what content is displayed on the same page by using includes or writing the different mysql queries inside the if/else statement.

  10. Hi Guys

     

    Just learning php.

     

    I want to write my own simple cms to get to grips with how things work (not necessarily to use as i realise there are millions of open source cmses available that are much more secure and clever).

     

     

    I'm ok with capturing and storing data in a database and i know the rudmiments of php so far.

     

    What i'm not so clear about, and what's missing from all the tutorials i've read, is how you load the data stored in a database relating to a specific page. All examples i've seen simply access the database and dump all the content into a page.

     

    So lets say i stored some body text in a database table with a unique key of 4.

     

    I then click on a link somewhere in the website, lets say it's www.mysite.com/4 (lets assume i've done the clever stuff with .htaccess)

     

    What is the best way of loading that specific page content?

     

    Do you access the header url and strip out the end part? Then compare that to your database ? Or is there a better way?

     

    Sorry if this is vague i'm just after a brief explanation and i'll go do the leg work to find out how to do it :)

     

    Thank you!

  11. Thanks David

     

    Really helpful explanation. I'm ensuring a sharp learning curve but the fundamentals are starting to click into place. Thanks for your help!

     

    In PHP 5, you can use a reference in the foreach:

    $cars[0]="Saab";
    $cars[1]="Volvo";
    $cars[2]="BMW";
    $cars[3]="Toyota";
    
    foreach ($cars as $key => &$value)  // <-- $value is a reference
    {
      $value = "TEST";
      echo $key . " " . $value . "<br />";
    }

    You have to watch out though. After the loop, $value still references the last element of the array. So if you use $value again, you could overwrite the array value. It is best to unset $value immediately after the loop.

    $cars[0]="Saab";
    $cars[1]="Volvo";
    $cars[2]="BMW";
    $cars[3]="Toyota";
    
    foreach ($cars as $key => &$value)  // <-- $value is a reference
    {
      $value = "TEST";
      echo $key . " " . $value . "<br />";
    }
    // Get rid of the reference
    // unset($value); // without this line we're borked.
    
    // more code
    
    $value = someCalculationFunction();
    // NOW we have changed $cars[3]. OOPS!

     

     

    Your other example was running in an infinite loop because of the <= which should have been just <.

     

    for ($i=0; $i <= count($cars); $i++)
    {
      echo $cars[$i];
      $cars[$i] = "2";
    }

     

    The loop condition is evaluated every time through the loop. When it started count($cars) was 4. After processing $i=3 and incrementing $i; it is now 4 which is LESS THAN OR EQUAL TO 4, so it ran again. This time, we added an element $cars[4]. So the test is $i (which is 4) is less than or equal to count($cars) (which is 5 now), so it continued to run. Since the array indexes start at zero, you need to use $i < count($cars). However, using count() as the condition adds extra work since the array is counted every time the loop repeats. It is more efficient to capture the count before the loop (oh, and use less than):

     

    $times = count($cars);
    for ($i=0; $i < $times; $i++)
    {
      echo $cars[$i];
      $cars[$i] = "2";
    }

  12. Hi Jcbones

     

    Well your tweaks worked a treat and I think I now see where I was going wrong.

     

    Sorry to post with such a simple one but I really couldn't find an answer on google and I was feeling slightly demoralised by getting stuck at such a simple hurdle - I suppose you have to start somewhere! :)

     

    Thanks for your help!

     

    Drongo

     

     

    $cars[0]="Saab";
    $cars[1]="Volvo";
    $cars[2]="BMW";
    $cars[3]="Toyota";
    
    
    
    foreach ($cars as $key => $value)
      {
    
    $cars[$key] = "TEST"; //change the value.
    echo $key . " " . $value . "<br />"; //this will still output Saab, BMW, Toyota, etc.  Because the value of "$value" has already been set, before we alter it.
    
      }
    
    echo '<pre>'; print_r($cars); echo '</pre>';//this should print an array full of "TEST".
    

    AND

    for ($i=0; $i < count($cars); $i++) {
    echo $cars[$i]; //this should print your array Saab, BMW, Toyota, etc.
    
    $cars[$i] = 2; //we now change the value of the array to 2.
    }
    echo '<pre>'; print_r($cars); echo '</pre>';//should show that cars is an array full of 2's.
    

     

    That should clear it up.  Let us know.

  13. Hi

     

    Just learning PHP and I'm struggling with a very simple problem.

     

    I'm playing around with arrays as i figure they're one of the most important things to know inside out but I can't work out how to change the value of an array element via a loop. I can obviously do it if I just directly write $cars[2] = "test" but not having any luck with the loop.

     

    I've tried using "foreach" and passing a new value to the $value variable but when i do a print_r the values in the array are unchanged.

     

    
    
    
    $cars[0]="Saab";
    $cars[1]="Volvo";
    $cars[2]="BMW";
    $cars[3]="Toyota";
    
    
    
    foreach ($cars as $key => $value)
      {
    
    $value = "TEST";
    echo $key . " " . $value . "<br />";
    
      }
    
    print_r($cars)

     

     

    I then tried using a for loop

     

    for ($i=0; $i <= count($cars); $i++)
    
    {
    
    echo $cars[$i];
    
    $cars[$i] = "2";
    
    
    }
    

     

    But this code just threw up a fatal error as follows:

     

    "Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 16 bytes) in /home/zzzzzzzz/public_html/php_testing/arrays.php on line 27"

     

    So would someone be kind enough to explain where i'm going wrong and why i get the fatal error on the second for loop.

     

    Thanks

     

    Drongo

  14. Thank you Chem!

     

    It works like a dream! And I'm quite in awe of the skills.

     

    I won't pretend i fully understand everything you did but your comments help a lot.

     

    Thanks to you too lightbearer. I'm flooded with options :)

     

    Right gonna sit down with this script and workout what each part is doing...

     

    I'll Admit i got bored :P

     

    <?php
    
    $email = "From:   lenny@gmail.com
    Sent:   07 September 2010 21:58
    To:   bilbo bagins, sam gamgee, billy bob
    Subject:   Subject: fun run 2011 - Registered interest
    
    Follow Up Flag:   Follow up
    Flag Status:   Completed
    
    Name: Lenny Davis
    Address: Ground Floor 500 High Street
    Address2: test address 2
    Postcode: xs34 4fg
    Phone: 034343554335
    Email: lenny@gmail.com
    DOB: 11.03.86
    Half or Full: full run 
    How did you hear: Took part in the Full fun run 2010
    From:   beth@aol.com
    Sent:   07 September 2010 18:58
    To:   bilbo bagins, sam gamgee, billy bob
    Subject:   Subject: fun run 2011 - Registered interest
    
    Follow Up Flag:   Follow up
    Flag Status:   Completed
    
    Name: Beth Collagin
    Address: 76 Commercial place, merthyr road, Caerphilly
    Postcode: Ce34 2vB
    Phone: 0423433423424
    Email: beth@aol.com
    DOB: 
    Half or Full: full run 
    How did you hear: Took part in the Full run 2010
    From:   nick@googlemail.com
    Sent:   07 September 2010 17:59
    To:   bilbo bagins, sam gamgee, billy bob
    Subject:   Subject: fun run 2011 - Registered interest
    
    Follow Up Flag:   Follow up
    Flag Status:   Completed
    
    Name: nic jones
    Address: 92 Drury grove
    Postcode: cr3 2vu
    Phone: 077434342354
    Email: nick@googlemail.com
    DOB: 13/12/1973
    Half or Full: full run
    How did you hear: Took part in the Full run 2010";
    
    preg_match_all("#([a-z 0-9]+)\.+)#i",$email,$matches);
    
    // First we sort it into different people/emails
    $user_id = 0;
    $user_emails = array(); // Will hold all the data
    $fields = array();	// We're going to use this for startnig the CSV file, it will hold all the different fields used in the text file.
    
    // Iterate each match - 
    for($i=0;$i<count($matches[0]);$i++){
    
    // Set some variables to make it easier to work out; (trim() removes whitespace padding)
    $field = trim($matches[1][$i]);
    $data = trim($matches[2][$i]);
    
    // Check or add field to fields array
    if(!in_array($field, $fields)){
    	$fields[] = $field;
    }
    
    // We check if the current field is "From" (strtolower() turns all letters in a string lowercase. so it can match any case)
    if(strtolower($field) == "from"){
    	$user_id++;
    }
    
    // Add item to the user_emails array
    $user_emails[$user_id][$field] = $data;
    }
    
    // because we are using a variable number of fields we have to make a dynamic way of creating the csv contents.
    
    // We start with a template of all fields available:
    $template = array_flip($fields); // Now keys have been switched with their values
    for($i=1;$i<count($template);$i++){ // This is just nulling the values so we dnot get the indexes as values.
    $template[$fields[$i]] = null;
    }
    
    $csv_file = '"'.implode('","', $fields).'"'."\n"; // define our csv start line (the field names)
    
    // Now we loop each user
    for($i=1;$i<=count($user_emails);$i++){
    
    // Use the template
    $content = $template; // basically a copy, so we dont overwrite our template
    
    $content = array_merge($content,$user_emails[$i]);
    
    $csv_file .= '"'.implode('","', $content).'"'."\n";
    
    
    }
    
    
    echo($csv_file);
    
    // Save as CSV File:
    $h = fopen("test.csv", "w");
    fwrite($h, $csv_file);
    fclose($h);
    
    ?>

     

    Take note of whats going on :P.

     

    Btw - Was easier imo to use the same regex, just used some PHP code to seperate the different users, rather than the regex itself which i doubt is even possible in this scenario since you need multi-dimensional arrays.

     

    Added CSV also

  15. Hi Chem

     

    Thanks for sticking with this one! I'm learning lots as we go.

     

    The format of the data runs as follows with the exact spacing as you see it (all data here is made up.)

     

    From: lenny@gmail.com

    Sent: 07 September 2010 21:58

    To: bilbo bagins, sam gamgee, billy bob

    Subject: Subject: fun run 2011 - Registered interest

     

    Follow Up Flag: Follow up

    Flag Status: Completed

     

    Name: Lenny Davis

    Address: Ground Floor 500 High Street

    Postcode: xs34 4fg

    Phone: 034343554335

    Email: lenny@gmail.com

    DOB: 11.03.86

    Half or Full: full run 

    How did you hear: Took part in the Full fun run 2010

    From: beth@aol.com

    Sent: 07 September 2010 18:58

    To: bilbo bagins, sam gamgee, billy bob

    Subject: Subject: fun run 2011 - Registered interest

     

    Follow Up Flag: Follow up

    Flag Status: Completed

     

    Name: Beth Collagin

    Address: 76 Commercial place, merthyr road, Caerphilly

    Postcode: Ce34 2vB

    Phone: 0423433423424

    Email: beth@aol.com

    DOB: 

    Half or Full: full run 

    How did you hear: Took part in the Full run 2010

    From: nick@googlemail.com

    Sent: 07 September 2010 17:59

    To: bilbo bagins, sam gamgee, billy bob

    Subject: Subject: fun run 2011 - Registered interest

     

    Follow Up Flag: Follow up

    Flag Status: Completed

     

    Name: nic jones

    Address: 92 Drury grove

    Postcode: cr3 2vu

    Phone: 077434342354

    Email: nick@googlemail.com

    DOB: 13/12/1973

    Half or Full: full run

    How did you hear: Took part in the Full run 2010

     

     

    Things to note:

     

    The fields that read:

     

    Follow Up Flag: Follow up

    Flag Status: Completed

     

    These only appear on some records. On other records these fields are absent but the format remains exactly the same (only without those fields). I am happy to remove all instances of those fields as they have no value. Same goes for the "To:" field, the "Sent:" field and the "Subject:" field. I'm not sure if that will make the REGEX any easier. If removing those fields makes things harder then I don't mind if they are left in.

     

    I hope this helps and thanks again! I will hopefully learn lots from your example!

     

     

     

     

    Give us an example of a few entries with as much variation as there will be.

    The more entries the more accurate my REGEX will be.

     

    Also making a CSV is very simple and i can tell you how to make it after we jump this regex hurdle (as the data structure will change and so will the method used to create the CSV file).

     

    hope this helps

  16. Hi chemical

     

    That’s really useful to know. I’ve seen regular expression syntax in coding before but never really knew what it was or how to use it. Now I’ve read a tiny bit about them I can see I was missing out on a massively powerful tool! Though it looks like there is lots to learn on regular expressions…the old adage of the “the more you learn the more you realise you know nothing at all” is leaping to mind!

     

    However, to reign this back to more basic terms I could use a little more help.

     

    You see the regular expression with pre_match)_all will create a very clean array of registration data. But the reason I used the explode() function and split the string at the boundardy “ZZZ” was to end up with a single full string of registration data for each array entry (i.e. each array element would contain one person’s registration data). This was easy to implode() with a line break to create a csv – i.e. a csv with each line representing one registrant (though my csv didn’t come out quite as expected).

     

    The bit I’m now confused about is how you use the shiny preg_match array and turn this into a CSV with each line displaying registration data.

     

    It’s complicated a little more by the fact that some of the registration data contains two address lines and some don’t contain any.

     

    Could you input a special marker (like my ZZZ) at the start and end of each registration entry and then implode the array only at that boundary?

     

    Any suggestions on how to overcome this would be so, so appreciated!

     

     

    I would highly reccommend learning REGEX syntaxes and practices using preg_match_all. If you do learn REGEX learn the PECL standard as thats what PHP's preg functions use.

     

    for ex,

     

    preg_match_all("#([a-z 0-9]+)\.+)#i",$email,$matches);
    print_r($matches);

     

    This is a very simple regex that captures 2 sub-patterns:

    the first part of each line (which consists of 1 or more of: [space] a-z 0-9)

    as long as it has a colon (:) after and before:

    The second sub-pattern which captures anything up until a new line (\n etc).

     

    hope this helps

    Good Luck

  17. Hi

     

    I'm learning php and trying to write a script to extract registration information from a large text file. Sadly my meagre knowledge of php is letting me down a bit. It's a case of knowing what you want the script to do but not having the knowlege of how to 'say it'.

     

    So i was hoping that if I posted my code here someone could either give me a few pointers on where i am going wrong or suggest  a better way.

     

    The text file data luckily has a recurring format as follows (for brevity i've only included one entry, which contains made up information):

     

     

     

    From: bella_done@yahoo.co.uk

    Sent: 02 February 2011 22:50

    To: Jonny tum, patsy fells, dingly bongo

    Subject: Subject: Fun Run 2010

     

    Categories: Fun Run

     

    Name: Bella Donna

    Address: 14 brondle avenue

    Postcode: cd83 1rg

    Phone: 0287343510

    Email: bella_don@yahoo.co.uk

    DOB: 15/11/1945

    Half or Full: Full fun run

    How did you hear: Took part in 2010

     

    As you can see the data has a convenient boundary at the 'from' field and the colon (or so it occurred to me) so I created my script as follows:

     

    
    // the string being analysed
    $the_string = "
    From:	bella_done@yahoo.co.uk
    Sent:	02 February 2011 22:50
    To:	Jonny tum, patsy fells, dingly bongo
    Subject:	Subject: Fun Run 2010
    
    Categories:	Fun Run
    
    Name: Bella Donna 
    Address: 14 brondle avenue 
    Postcode: cd83 1rg 
    Phone: 0287343510 
    Email: bella_don@yahoo.co.uk 
    DOB: 15/11/1945 
    Half or Full: Full fun run 
    How did you hear: Took part in 2010";
    
    // remove all formatting to work with a clean string
    
    $clean_string = strip_tags($the_string);
    
    
    
    // remove form field entries from the data and replace with commas and a ZZZ boundary
    
    $remove_fields = array("Categories:" => "","Name:" => ",","Address:" => ",","Postcode:" => ",","Phone:" => 
    
    ",","Email:" => ",","DOB:" => ",","Half or Full:" => ",","How did you hear:" => ",","From:" => "ZZZ","Sent:" => 
    
    ",","To:" => ",",  );
    
    
    $new_string = strtr("$clean_string",$remove_fields);
    
    
    // split the data at the boundary ZZZ
    
    $string_to_array = explode("ZZZ", $new_string);
    
    $new_string2 = implode("</br>",$string_to_array);
    
    echo $new_string2; 
    
    
    
    
    $myFile = "address_list.csv";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = $new_string2;
    fwrite($fh, $stringData);
    fclose($fh);
    
    
    

     

    One major problem is when i write the new data to a csv file the csv contains spacings that cause it to be reproduced in a column form rather than as separate fields for each comma boundary.

     

    So can anyone suggest either

     

    a) a better way of extracting the data from the text file (doesn't need to be 100% clean and perfect)

     

    b) How can i stop the spaces in the csv (i thought i would have fixed this when i stripped the tags from the string at the start??).

     

    Any help would be greatly received by a newbie phper.

     

    It's my first shot at performing anything moderately taxing so if I've made some blaring oversites I would very much welcome your wisdom!

     

    Thank you

     

    Drongo

×
×
  • 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.