Jump to content

Madly new to PHP and a noob in need of discussion and help!


achan99

Recommended Posts

Hi Everyone!

 

First off I'd like to thank everyone who is willing to participate in helping me in this long journey! 

 

I am here to discuss a variety of PHP concepts that I will need help with in the following weeks and I greatly appreciate every response! Feel free to call me a noob, that's totally fine by me, but at least while your doing it please provide me some help and assistance. 

 

I want to get my hands dirty and am extremely motivated to learn the ins and outs of PHP and I need your help to do it! Thanks again everyone!

 

So here is my first problem.

 

I know cookies are saved using setcookie() function...but how do I know for sure that sessions that are created, via session_start() ? Is there a way to ensure that cookies are being written? What test can I do to ensure that cookies are being stored and accesible by my browser?

 

Thanks! 

 

 

EDIT: Yikes I am not sure why my thread got created twice! I'm sorry mods, that was not intentional! 

Please delete the other thread if possible! 

Edited by achan99
Link to comment
Share on other sites

My current preference for checking cookies is the Web Developer toolbar for Firefox:

https://addons.mozilla.org/en-US/firefox/addon/web-developer/

 

It provides a quick way to view, edit, and manually remove cookies which is handy for testing. Note that the toolbar looks to be available for other browsers, but I haven't used those versions:

http://chrispederick.com/work/web-developer/

Link to comment
Share on other sites

Hi everyone, thanks for your responses!! 

 

I am currently using the Firefox Web Developer tools to help me debug as well and it is definitely useful, however I don't think my application is dropping cookies into my web browser properly...  Using the FireFox web dev tool bar, i see two cookies that have been saved, but they are not coming from my code specifically... 

 

In fact, I tried to run this snippet independently from my overall project, and saw NOTHING in my web browser: 

<?php
   $value = 'somewhere over the rainbow';
   $pass = setcookie("testCookie", $value);
   echo $_COOKIE["testCookie"];
?>

Any thoughts on this?

 
Furthermore, there is this cookie_domain variable that gets passed into the setcookie function...i suspect that i've saved my cookie_domain variable incorrectly...but then why did my previous test (above) fail? 
  • To get this cookie domain variable, I simply type in "hostname" in my linux terminal...shouldn't that be enough to store in that cookie_domain variable?
Link to comment
Share on other sites

You can't set a cookie and immediately read from it because it hasn't been sent to the browser yet until the end of the requests cycle. Then, on the next page accessed, you can read from the cookie.

 

1) set cookie

2) at end of code execution cycle when the script sends all output to the browser, the cookie header is also sent to the browser

3) request a new page (or same page)

4) cookie data is sent back to the application in the headers from the browser

5) can now read from $_COOKIE in application

 

Try this:

if ( ! isset($_COOKIE['testcookie']))
{
  setCookie('testcookie', 'our value'); //must be created before any output
  echo 'cookie does not exist, so we just created it. Reload this page to see it.';
} else {
  echo 'cookie was created and its value is: ' . $_COOKIE['testcookie'];
}
  • Like 1
Link to comment
Share on other sites

Don't worry about being new to this and not knowing something.

This is a friendly place and you shouldn't be criticized.

 

Are your intentions to save a password in a cookie? I saw $pass as the variable

 

It's not safe storing passwords in a cookie.

Maybe you would like to use session instead and store the users name as a session

http://php.net/manual/en/book.session.php

 

have a user register/login system

passwords are hashed/encrypted using something like password_hash() and that is saved to a database

 

when a user logs in you use password_verify() on the password and check your database for a match

if there is a match in your query you can set a users session with an id or name, whatever you desire (also useful for setting permissions such as admin,user,guest)

$_SESSION['username'] = $row['username'];

 

for checking which user it is through a session can do something like this

<?php
session_start();
if(isset($_SESSION['username'])){
$user = $_SESSION['username'];
}
?>

Some random information about sessions, cookies and web storage:

 

With sessions the client does not have the ability to change the data.

Using sessions forces the client to log in each time because they get lost expire times and garbage collection.

It's possible to use a combination of sessions and cookies to keep that user logged in longer, although I would lean towards creating an access token instead.

Cookies were useful a while, many people are blocking them now.

Depending what country are in such as the UK, you are in have to supply a warning are saving their cookies and they accept it.

There are cookies and also html5 has web storage

localStorage

http://www.w3.org/TR/webstorage/#the-localstorage-attribute

localStorage can store 5 mb versus cookies having a limit of 4095 bytes per cookie

Cookies are primarily to be read server-side while localStorage is meant as client-side only

If localStorage is saved from a secured ssl such as https it doesn't work for non https

If your server needs to read from localStorage and is lots of data it's not worth sending the data back with javascript/ajax in the HTTP header or like in hidden forms

localStorage has no expiration date, it only gets removed via javascript, clearing browser cache or the browser is closed.

 

There is also sessionStorage

http://www.w3.org/TR/webstorage/#the-sessionstorage-attribute

When a new HTMLDocument is created, the user agent must check to see if the document's top-level browsing context has allocated a session storage area for that document's origin. If it has not, a new storage area for that document's origin must be created.

 

localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit.

 

Leaving the tab or page were on sessionStorage is gone while localStorage can remain.

 

Cookies, localStorage and sessionStorage can easily be read or changed from within the client/browser and should not be used for storage of secure data.

There is attempts modern browsers to prevent Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag... but I wouldn't rely on it.

If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

 

If you want to save a pile of information and is just for the clients purposes, localStorage is the best way.

If is some sort of temporary data just for a user that page then sessionStorage

If the data is to be used for your own server then normal cookies is a better way to go.

 

Summing it all up...it's better to use sessions unless is not important data.

Link to comment
Share on other sites

Hi Everyone! Thanks again for providing your feedback! 

 

I've picked up a little bit from everyones comments and have been able to rectify my issue, by making a workaround. So previously the code would be setting cookies to a specific domain, given that the connection was over HTTPS, and setting the expire time to 0 (which i still don't know why that was the case)...anyways, as I continued to read through the code, I realized that the cookie was only being checked for the name, and if it was indeed set, then the code would proceed on the correct path. So what I decided to do was temporarily get rid of a number of the parameters (temporarily) just to get the code base working so I can make the modifications my organization is requesting me to make. 

 

 

@CroNix, Yes you are 100% right! Cookies were being saved except it would only show up after I refreshed the page. It makes a lot of sense that cookies are first created in the backend server and then pushed to the browser after the script has ended. I suppose that knowledge was pretty critical to know in order for me to understand my test. 

 

My test application, helped me in two ways. It showed me why the code was previously not saving the cookies successfully, and then it helped me as I realized that I could save the cookie in a much easier fashion by avoiding the domain and security parameters of the function, setcookie... 

 

@QuickOldCar, I was not saving that as a password, I was just using that variable to check whether setcookie was returning a successful value or failure value, ie pass, but hahah i suppose that's bad naming convention! Thank you for the lesson on Sessions. In fact, no passwords are saved in my database for my application, we are using a kerberos token system to confirm whether the user has entered the correct password for their userID. The cookie in my code is just to check whether the user has logged in or been idle for the past x number of minutes. Thanks for the information on session information and saving passwords! I will certainly be using those in forthcoming personal projects that I'd like to take on in the near future. 

 

------

 

And just some backstory for everyone on why I need all this help. I am actually a student who was on an internship. At my internship, I wasn't really being too stimulated...there wasn't much problem solving, i was just kind of the grunt that copied and pasted commands into the command line...I didn't really get the problem solving experience I was looking for...Anyways, I called back an organization who had hired me previous to my internship to do consulting with them when I proposed a software project to create a comprehensive database for instructors. I have a good relationship with this organization, when I told them about my issue with the internship and asked if they had any openings, I was fortunate enough to find out that they did have an opening for a specific project they needed some work on. 

 

This is the specific project I am struggling with, I told them that while my skill may be limited, I have the desire and motivation to want to figure everything out and learn on the fly. 

 

You guys have, already provided me an extreme wealth of knowledge and I really appreciate all the help you guys have provided without being critical about my experience. So I definitely want to extend my thanks to everyone who has participated and will continue to help/participate in the future. I will definitely have more questions and many more struggles to overcome in the forthcoming weeks. 

 

I am so happy to be doing some thing that is quite challenging, I need to overcome my fear on coding hahaha -> this is hilarious too because I study electrical and computer engineering and have been through a number of ridiculous coding courses, like operating systems xD hahaha. 

 

Anyways, I sincerely appreciate everyones help! I'll be posting more on this thread as more problems arise!

 

THANKS EVERYONE!!!!! 

Link to comment
Share on other sites

  • 4 weeks later...

Hi Everyone,

 

I want to thank you guys for your help again and of course throw more questions at you guys! 

 

So today, I am querying my database for some data, however I am getting mysql 2014 error. -> This corresponds to Command out of sync and cannot run this command now. 

 

I know that when this error comes up when there is an existing query which has not yet been completely fetched from the stmt object...

 

--- To preface this whole situation, I am building off code that has already been implemented. There is already a database query being made and is successful. 

 

My query, which sits below that previous query, I get this 2014 error... but the first query is successful. If I swap these two queries, put mine on top, I am still getting that same error. Do you guys have any ideas what this might be causing this? Or any suggestions to logs I should be looking to? 

 

I have a while loop which checks stmt->fetch, and will keep looping until completely empty, then it closes the stmt object... 

 

I'll post code if necessary, But I'd like to avoid it if possible. 

 

 

THANKS! 

Link to comment
Share on other sites

This is the general structure of the code I am working with / building. 

$query = "SELECT FROM WHERE QUERY HERE";

$stmt = $this->db->prepare(query);
$stmt->bind_param(...);
$stmt->execute() or throw_exception;
$stmt->bind_result(...);
while( $stmt->fetch();
{
$fetched_stuff = stuff_from_bind_result;

}

$stmt->close();
return $fetched_stuff; 

I don't see how a the stmt object might have stuff in its buffer when I am fetching within the while loop. As such I don't know where to look to solve this problem..ANY HELP IS MUCH APPRECIATED!

 

THANKS! 

Link to comment
Share on other sites

I'm not sure if it is bad to keep posting on your message without any one responding, but I can't edit my response. If this is against the rules could some one advise on this please! THANK YOU!

 

 

I have further developments... The query that was previously written here by the last developer...also seems to get errno 2014 but is capable of accessing the database and pulling data from it. 

 

So what is stopping my stmt objects from getting the data i expect? Whenever I got to the while loop in my code (the stmt->fetch( ) ) I get an unintialized response from that call and as a result does not enter the while loop to pull data into the respective variables I need...

Link to comment
Share on other sites

You should write a new post for new problems.

 

Posting actual code helps as well.

 

The mysql 2014 error is probably occurring because are trying to fetch new results while there was still old results being fetched

You can try adding closeCursor()

$stmt->closeCursor();

 

 

If the first results are not too large you can save them into an array and then run additional queries. Close the loop then do it.

Is $fetched_stuff always one item?

fetch() will fetch only one record, fetchAll() will fetch all the records and could then make $fetched_stuff an array by doing $fetched_stuff[] = stuff_from_bind_result;

Link to comment
Share on other sites

QuickOldCar! Thanks for your suggestion... but I am not sure that it is because a query is being made prior to my query calls... What I just tried was replacing my code snippet with their code snippet so I am querying from their table twice...by doing that it means it is either my code which is wrong...which is unlikely because I literally took their code and changed variables...or something to do with the table its self... 

 

I will try using closeCursor() 

 

$fetched_stuff is not always one item, it can be be as many items as needed to have bound with bind_result 

 

but i still don't think that is the real underlying issue.. 

 

and btw, I will certainly make a new thread for each problem I have ! Thanks for that suggestion too! 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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