Why I can't set cookie? - php

I'm coding a basic website and I want to set a cookie named 'color' at the beginning of the session.
For that mean, I used this code :
<?php
require_once("../model/connection.php");
if (!(empty($_POST['user_email'])) and !(empty($_POST['user_password']))){
$login = $_POST['user_email'];
$password = $_POST['user_password'];
$stmt = $conn->prepare('SELECT ID, color FROM Player WHERE mail = ? AND password = ?');
$stmt->bind_param('ss',$login,$password);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
session_start();
$row = $stmt->fetch_assoc();
$_SESSION['ID'] = $row['ID'];
setcookie("color", $row['color'], time() + 365*24*3600) or die('unable to create cookie');
header("Location: ../view/index.php");
}
}
else {
header("Location: ../view/index.php?error=false");
}
But when I call var_dump('$_COOKIE['color'], php returns
Notice: Undefined index: color in /Applications/MAMP/htdocs/controller/controller_game.php on line 7
There is certainly a basic thing I don't understand, sorry I'm a beginner.
By the way, my request is good, I tested it.
Thanks for your time.

Add the last parameter / and it should work. As follows
setcookie("color", $row['color'], time() + 365*24*3600, "/");
Hope this helps

Related

php PDO mysql - behavioural query

Happy New Year to all. I need to point out I am trying to use PDO exclusively and I'm a relative noob to using PDO, so please excuse the question if it appears plainly obvious.
I'm having a bit of a stupid moment because I cannot seem to understand a few things as to why a relatively simple email validation system I have (tried) to write is not quite working correctly. Everything is ok until the php at the end of the validation link is setting the email address as being validated. Here is my code, followed by questions:
Firstly I have an include file that holds the DB login. It looks like this:
<?php
// DATABASE SETTINGS
$hostname = "127.0.0.1";
$username = "devProduction";
$password = "ienx3rybcisuc";
$database = "devProduction";
try {
$conn = new PDO("mysql:host=$hostname; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// close the database connection (removed as I do this at the end of each call)
//$conn = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
And then in the page that actually received the user after they click on the link sent out to their email:
<?php
// Grab our includes
include '../conf/Funcs.php';
include '../conf/DBconfig.php'; // (This is the file displayed above)
require_once '../conf/Mobile_Detect.php';
// Check out what device is looking at us
$detect = new Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
$scriptVersion = $detect->getScriptVersion();
// Check to see if we are already logged in under an already validated account
if(isset($_COOKIE['AGMARDTuid']) || isset($_COOKIE['AGMARDTtoken'])) {
logout();
header("Location: ../");
exit;
} else {
$val = base64url_decode($_GET['val']);
$val = explode(":-:", $val);
$uid = $val[0];
$add = $val[1];
$key = $val[2];
// These are the three items that are pulled out of the URL $val value. This works fine
// It's only here to check it's working ok for the moment
echo "uid: ".$uid."<br>add: ".$add."<br>key: ".$key."<br><br>";
// Kill the process if either of the three values - $uid, $add, $key - are empty
if(($uid == "") || ($uid == NULL) || ($add == "") || ($add == NULL) || ($key == "") || ($key == NULL)) {
logout();
header("Location: ../");
exit;
} else {
// Seems everything is in order for email validation, so lets validate
$yes = "yes";
$NULL = NULL;
try {
$stmt = $conn->prepare("UPDATE $database.users SET `emailValidated` = :validate, `emailValidationKey` = :newkey WHERE `uid` = :uid AND `email` = :add AND `emailValidationKey` = :key");
$stmt->bindParam(':uid', $uid);
$stmt->bindparam(':add', $add);
$stmt->bindParam(':key', $key);
$stmt->bindParam(':validate', $yes);
$stmt->bindParam(':newkey', $NULL);
$stmt->execute();
$result = "success";
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); $result = "fail"; }
$conn = null;
echo "result: ".$result." (post sql)<br><br>";
if($result == "fail") {
echo "Email did not successfully validate, there was a problem<br><br>";
echo $conn . "<br>" . $e->getMessage();
} else if($result == "success"){
echo "Email successfully validated<br><br>";
echo $conn . "<br>" . $e->getMessage();
}
echo "<br><br>We got to the end!";
}
}
?>
The code works, kinda. The problem is, if there is NOT an account within the database that matches all three values passed to the script from the URL, it still displays as having updated (validated) an account, even though it has not. Why is this?
Also, for the section that I am binding some parameters, specifically these two:
$stmt->bindParam(':validate', $yes);
$stmt->bindParam(':newkey', $NULL);
Why do I seem to have to assign $yes = "yes"; and "$NULL = NULL; as variables beforehand? I did try:
$stmt->bindParam(':validate', 'yes');
$stmt->bindParam(':newkey', NULL);
and
$stmt->bindParam(':validate', yes);
$stmt->bindParam(':newkey', NULL);
and
$stmt->bindParam(':validate', 'yes');
$stmt->bindParam(':newkey', 'NULL');
all without success.
Answers and info and suggestions always welcome and appreciated. Thank you!
C
You should use bindValue instead bindParam when you want to pass a value (or the result of a function) in the prepared statement.
$id = 100;
$datas = array('a', 'b', 'c');
$stmt = $db->prepare("SELECT * FROM user WHERE id = :id AND status > :status AND justForExample = :other");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindValue(':status', 1, PDO::PARAM_INT);
$stmt->bindValue(':other', implode("", $datas), PDO::PARAM_STR);
$stmt->execute();
The documentation to BindValue
The documentation to BindParam
More informations about the difference

PHP Session expiration - works stand alone but not in a function

when I issue this code from a function, the cookies expire at the end of the session
$validuntil = '2024-02-17';
$validuntil = strtotime ($validuntil);
setcookie ('vid',$vid,$validuntil,'/');
setcookie ('pwd',$pwd,$validuntil,'/');
However, executing the exact same code in a stand alone php file sets the cookies to expire on the correct date.
Here is the function
function validuser ($vid, $pwd){
global $pdo;
$stmnt = $pdo->prepare ("select * from members where vid = :vid and password = :password");
$stmnt->bindParam (':vid',$vid);
$stmnt->bindParam (':password', $pwd);
$stmnt->execute();
if ( $stmnt->rowCount() != 1){
header("Location:invalid.php");
break;
}
$member = $stmnt->fetch (PDO::FETCH_OBJ);
if ($member->nickname!="")
$_SESSION['user']= $member->nickname." ".$member->lname;
else
$_SESSION['user']= $member->fname." ".$member->lname;
$validuntil = '2024-02-17';
$validuntil = strtotime ($validuntil);
setcookie ('vid',$vid,$validuntil,'/');
setcookie ('pwd',$pwd,$validuntil,'/');
$_SESSION['ulot'] = $member->ulot;
$_SESSION['valid'] = '101150';
$_SESSION['admin'] = $member->admin == 1;
$_SESSION['vid'] = $member->vid;
$_SESSION['resid'] = $member->vid;
$_SESSION['pwd'] = $member->pwd;
$_SESSION['user'] = $member->fname." ".$member->lname;
header ("Location:mainmenu.php");
}
Can someone please explain this and how I fix it.
Thanks,

optimizing php code for less php processing

I am having some problem with my apache server when handling big amount of traffic. after some optimizations I did. I still have the same problem. I check my log file and it turned out that I have a lot of php processing. The following code is getting processed about 800 times a minute (when I have high traffic) and casing my server to crash.
1) is there any parts of the code that I need to rewrite that would make it take less php processing ?
2) is it a good idea to have all of this code before the html starts ?
<?php
$ip = $_SERVER['REMOTE_ADDR'];
mysql_connect('', '', '');
mysql_select_db('');
if(empty($_GET['i']) == false){
$get_image = mysql_real_escape_string($_GET['i']);
$check_if_image = mysql_query("SELECT `id`, `image_name`, `image_type`, `image_caption`, `image_voteup`, `image_votedown`, `image_views`, `fb_userid` FROM images_new WHERE image_name = '$get_image'");
if(mysql_num_rows($check_if_image) == 1){
$result = mysql_fetch_assoc($check_if_image);
$image_id = $result['id'];
$image_name = $result['image_name'];
$image_type = $result['image_type'];
$image_caption = stripslashes($result['image_caption']);
$image_voteup = $result['image_voteup'];
$image_votedown = $result['image_votedown'];
//$image_date = $result['image_date'];
$image_views = $result['image_views'];
$fb_username = $result['fb_username'];
$fb_userid = $result['fb_userid'];
//next image
$next_image_id = $image_id + 1;
$check_next_image = mysql_query("SELECT `image_name` FROM images_new WHERE id = '$next_image_id'");
if(mysql_num_rows($check_next_image) == 1){
$next_image_result = mysql_fetch_assoc($check_next_image);
$next_image_name = $next_image_result['image_name'];
}
// pre image
$pre_image_id = $image_id - 1;
$check_pre_image = mysql_query("SELECT `image_name` FROM images_new WHERE id = '$pre_image_id'");
if(mysql_num_rows($check_pre_image) == 1){
$pre_image_result = mysql_fetch_assoc($check_pre_image);
$pre_image_name = $pre_image_result['image_name'];
}
//shares, comments, and likes
$fb_page_url = "http://www.xxx.com/images.php?i=".$get_image;
$fb_url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($fb_page_url);
$fb_xml = file_get_contents($fb_url);
$fb_xml = simplexml_load_string($fb_xml);
$fb_shares = $fb_xml->link_stat->share_count;
$fb_likes = $fb_xml->link_stat->like_count;
$fb_likes_and_shares = $fb_likes + $fb_shares;
$fb_comments = $fb_xml->link_stat->commentsbox_count;
//facebook
require_once('scripts/facebook.php');
$config = array('appId' => '','secret' => '');
$params = array('scope'=>'user_likes,publish_actions,email,offline_access,user_birthday');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($user){
try{
$user_profile = $facebook->api('/me','GET');
$user_id = $user_profile['username'];
$expire_time = time() + 30758400;
//insert cookie id
if (!isset($_COOKIE['id'])){
$cookie_id = $user_profile['username'];
setcookie("id", $cookie_id, $expire_time, '/');
}
//insert cookie name
if (!isset($_COOKIE['name'])){
$user_name = $user_profile['first_name'];
setcookie("name", $user_name, $expire_time, '/');
}
//check if the user like the fan page
$isFan = $facebook->api(array(
"method" => "pages.isFan",
"page_id" => ''
));
}catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
}else{//if no user
if(isset($_COOKIE['name'])){
$user_name = $user_profile['first_name'];
setcookie("name", $user_name, time() - 30758400, '/');
}
}
//increase views
if($facebook->getUser()){
mysql_query("UPDATE images_main SET image_views = image_views + 1 WHERE image_name='$image_name'");
mysql_query("UPDATE images_new SET image_views = image_views + 1 WHERE image_name='$image_name'");
}
}else{//image was not found in the database.
header('Location: index.php');
}
}else{//redirect if get is empty
header('Location: index.php');
}
?>
I would say the key factor is your call to the Facebook API, such things are always expensive and easily cacheable, put that code in a separate page/include and cache it as you like.
Also as a side note, you should consider reducing the number of db queries and you may wish to update your db driver... as invariably everyone points out #Madara Uchiha
I see a few items right off the bat.
First query:
$check_if_image = mysql_query("SELECT `id`, `image_name`, `image_type`, `image_caption`, `image_voteup`, `image_votedown`, `image_views`, `fb_userid` FROM images_new WHERE image_name = '$get_image'");
If you only need one result back, put a 'LIMIT 1' at then end (unless this field has a UNIQUE index, in which case this shouldn't matter). Also make sure this field is indexed and preferably a VARCHAR field instead of TEXT or BLOB.
Next, you are running 2 queries to get the previous and next images. I would combine this into 1 query like this:
SELECT `image_name` FROM images_new WHERE id IN ('$next_image_id', '$pre_image_id')
Also, you can apply the first optimization I mentioned to these 2 queries:
if($facebook->getUser()){
mysql_query("UPDATE images_main SET image_views = image_views + 1 WHERE image_name='$image_name'");
mysql_query("UPDATE images_new SET image_views = image_views + 1 WHERE image_name='$image_name'");
}
Lastly, going through the Facebook API is going to add load time that you cannot do much about. Hopefully this gets you started down the right path.

PHP and Oracle Session Login

Here it's I have a problem with my PHP Code + Oracle Login form.
In this PHP file, I make login function. But I have an error like this :
Warning: oci_num_rows() expects parameter 1 to be resource, string given in C:\xampp\htdocs\developers\it\session.php on line 12
Wrong
-
<?php
session_start();
include ("config.php");
$username = $_POST['username'];
$password = $_POST['password'];
$do = $_GET['do'];
if($do=="login")
{
$cek = "SELECT PASSWORD, USER_LEVEL FROM T_USERS WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = oci_parse($conn, $cek);
oci_execute($result);
if(oci_num_rows($cek)==1)
{
$c = oci_fetch_array($result);
$_SESSION['username'] = $c['username']; ociresult($c,"USERNAME");
$_SESSION['USER_LEVEL'] = $c['USER_LEVEL']; ociresult($c,"USER_LEVEL");
if($c['USER_LEVEL']=="ADMINISTRATOR")
{
header("location:supervisor.php");
}
else if($c['user_level']=="User")
{
header("location:user.php");
}
else if($c['user_level']=="Root")
{
header("location:administrator.php");
}
else if($c['user_level']=="Manager")
{
header("location:manager.php");
}
else if($c['user_level']=="Admin")
{
header("location:admin.php");
}
else if($c['user_level']=="Director")
{
header("location:director.php");
}
}
else
{
echo "Wrong";
}
}
?>
I have tried to search in google, but still don't find anything.
Someone knows, what's the problem ?
Thanks for advance.
According to your script instead of
if(oci_num_rows($cek)==1)
you should call
if(oci_num_rows($result)==1)
You probably want to use $result and not $cek when you're asking for the number of rows returned from oci_num_rows(). However, you really want to avoid using $username and $password directly in the string like that. It'll make you wide open for SQL injection attacks, so look into using oci_parse together with oci_bind_by_name.
After that you should also always call exit() after the sequence of redirects, as the script will continue running if you don't (and that might be a security issue other places).
I also got the same case, so I tricked it with a script like this, but I don't know whether there was an impact or not. because the session and validation went smoothly.
$username =$_POST['username'];
$password = $_POST['password'];
$conn = oci_connect('xxx', 'xxx', 'localhost/MYDB');
$pass_encription = md5($password);
$query = "SELECT * from *table_name* WHERE *field1*='".$username."' and *field2*='".$password."'";
$result = oci_parse($conn, $query);
oci_execute($result);
$exe = oci_fetch($result);
if ($exe > 0)
{
oci_close($conn);
oci_execute($result);
$row =oci_fetch_array($result);
$sid = $row['field_1_parameter'];
$snama = $row['field_2_parameter'];
$sjab = $row['field_3_parameter'];
$session = array (
'field_1_array' =>$sid,
'field_2_array' =>$snama,
'field_3_array' =>$sjab
);
if($sjab == 'Administrator')
{
$this->session->set_userdata($session);
redirect('redirecting_page');
}
`

Session lost after page redirect in php

When I use php header redirection all session variables are lost... Some people say that adding exit(); just after the header(""); will solve the problem but it doesn't seem to be the solution...
Can anyone please help?
Here is how I store variable into the session:
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['usr_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
if(empty($err)){
header("Location: myaccount.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
Redirection code:
//connect database
require_once 'dbc.php';
page_protect();
$authorID = $_SESSION['user_id'];
if ( !empty($_POST["answ_content"]) && $authorID != 0 ) {
//vaqciot html chveulebriv texad
$content = htmlentities($_POST["answ_content"],ENT_COMPAT,'UTF-8');
$dro = date('Y-m-d H:i:s');
$qID = $_POST["question_ID"];
$author = $_SESSION["user_name"];
$sql="INSERT INTO wp_comments (comment_ID, comment_post_ID, comment_author, comment_author_IP, comment_date, comment_content, user_id)
VALUES
(NULL, '$qID', '$author', '123.123.123.123', '$dro', '$content', '$authorID')";
$result = mysql_query($sql);
//pasuxebis raodenobis ertit gazrda
$increase = "UPDATE wp_posts SET comment_count = comment_count+1 WHERE ID = $qID";
mysql_query($increase);
//gadamisamarteba shekitxvis gverdze
$url = 'Location:http://example.com/site/answ/question.php?ID=' .$qID;
header($url);
} else {
echo 'error';
}
You need to put exit(); after your header redirection, otherwise you have just loaded two pages of content into 1 page.
Also make sure you have session_start(); at the top of all your scripts.
You aren't starting the session. In order to use session variables and have them carry across pages, you need to put
session_start();
at the top of each page before anything else.
I was trying to set the session id of my own using :
session_id('own_generated_session_id_string');
But as the documentation says, you have to use this before
session_start();
Using it after session_start(), clears the session parameters.
Simples! make sure the page you are coming from (e.g. www.example.com) redirects to a (eg.g www.example.com/redirect.php) notice www at the beginning. If you change that from page to page, then yes things get wonky.
These sessions does not always work as we expect sometimes. I had a similar problem with my website using sessions that get lost. I basically solved it by injecting the value I want to keep on the session into the hidden text field the first time the page loads. Then the second time I call the page(page submit) I simply read the value from the hidden text field and carry on with rest of my code.
That's more easier and cleaner than using sessions in this case!
exit; should be placed after header redirection or session_regenerate_id(true); can be used
You just need to check the file permission in /var/lib/php directory
give yje public permisssion to /var/lib/php/session directory.
and all done.
Include session_start(); in both the files before the session.
Note don't use session_destroy() in the redirected file.

Categories