I am only just starting to get to grips with PHP, so please forgive me if I have missed something obvious. My problem is this:
I have a script that validates when a payment has been made, when a payment has been made it includes the following:
include 'newtest/generate.php';
"generate.php" creates a random single use URL, finds the user that is logged in and emails the link to them. It finds the users email like this:
include 'includes/common.inc.php';
$query = "SELECT * FROM " . $DBPrefix . "users WHERE id = " . $user->user_data['id'];
$result = mysql_query($query);
$USER = mysql_fetch_assoc($result);
$usermail = $USER['email'];
If I run generate.php via my browser, everything works fine.. it picks up the logged in user details and sends the link.
However, when a paypal payment is made it won't. I thought this might be something wrong with paypal validation. But its not, if I set
$usermail = 'me#mydomain.com';
and then make a test payment, everything works fine. So basically, why won't my script pick up on the users email when paypal sends the request?
Maybe you need to put an absolute path on the include file. If that file contents some data like $DBPrefix, the query couldn't be completed. You can call PHP's function error_log to see the query.
Related
I have very weird problem:
I've created simple Wordpress based store. I sell e-books and send them via email. I use online payments and have plugin to work with them. It have build-in gateway in php file. I want to inject my code to this script to automatize selling. It looks like this:
<?php
//1. Get payment info from payment service via $_POST
//2. Chceck all hashes etc.
//3. Get status to variable e.g. $status
if ($status == 99)//everything is ok
{
$order_id = $_POST["no_of_transaction"];
log_to_file("Yeah i am workig. id =".$order_id."with status ".$status);
include $_SERVER["DOCUMENT_ROOT"]."/sell_stuff.php";
log_to_file("Yeah i am still workig");
}
?>
sell_stuff.php:
<?php
log_to_file("Hello i am in sending script!");
//i assume that $order_id is still visible
$order = mysql_fetch_assoc(mysql_query("SELECT * FROM order where id=".$order_id));
$mail->to = $order['email'];
$mail->attachment = "/upload/pdf/".$order['book'].'.pdf';
$mail->send();
?>
And this method not working at all :( I've tried to change include to require and use ABSPATH instead of $_SERVER["DOCUMENT_ROOT"] but it still fails. Last thing logged in log file is ""Yeah i am workig. id= xxx with status = 99".
I've created test.php file like this:
<?php
echo "Yeah i am workig";
$oder_id = 100; //my own order
include $_SERVER["DOCUMENT_ROOT"]."/sell_stuff.php";
echo "Yeah i am still workig";
?>
... and when I run this via www.mystore.com/test.php it's work perfectly. It logging to file "Hello i am in sending script!" and all other stuff.
I dont know where i make mistake :(
Try to drop "/", and use it like:
$_SERVER["DOCUMENT_ROOT"]."sell_stuff.php";
Also $_SERVER["DOCUMENT_ROOT"] is genereating path to you www root folder, like
www.serwer.com/www/
If u have your site in:
www.serwer.com/www/www2/
it will not get included. If u will use:
__DIR__."/sell_stuff.php";
it will get the path to place where your file is.
www.serwer.com/www/www2/
You can always:
var_dump($_SERVER["DOCUMENT_ROOT"]);
var_dump(__DIR__);
to see the difference and the path that you are getting.
I am trying to retrieve user inputs from a previous page using the URL. I have the following code on the previous page which sends the username and account status via the URL.
header("location: pagename.php?user=$username&status=$status");
On 'pagename.php' I have the following code which stores the values in local variables and echos them for my benefit.
if(isset($_GET['user'], $_GET['status'])){
$user = mysqli_real_escape_string($con, $_GET['user']);
$status = mysqli_real_escape_string($con, $_GET['status']);
echo $user.' - '. $status;
}
While, elswhere, this method works perfectly for retrieving 5 values form the URL, on this occasion I am failing to retrieve the status and it echoes the following 'username - ' You can see an image of the output for better understanding. I would much appreciate your assistance in helping me retrieve the status from the URL using PHP.
http://www.awesomescreenshot.com/image/378892/c50c452d8597f2ac29970a6a21bfcc62
Having tried var_dump($_GET) I get the following result:
I just realised that the issue lied with the naming of the variable $status, which incidentally happened to be the same name used in my login session and because I was not logged in it did not get the account status. I fixed the issue by simply renaming the variable.
I want people to request invites to use my app, they fill in their email address, but how can generate an url for them to go to register? Presumably only to be used once! I was thinking some sort of md6 code using php!
P.S. If there is a tutorial for this, please give a the link. Thanks.
In the email you use a random code, for example (a part of) the session-id of the user
<?php
$code = session_id();
You save this code somewhere in your database and when the user hits your register page (for example, http://mydomain.tld/register?code=here-register-code), you do something like this:
<?php
$code = $_GET['code'];
if (my_code_is_valid($code) {
echo 'Hey, you are able to register now!';
} else {
echo 'Sorry friend, you need an invite first!';
}
You need to define your my_code_is_valid() function, but that's depending on your own code (framework, database system etc).
Need some help with how to handle sessions. I am using ajax techniques to implement a group discussion platform and alot of its success depends on whether or not i can handle sessions properly, be able to see who is online etc. How can i do this efficiently. Remember, this is a typical single url ajax application where the server only responds to request. All of the form validation is done on the client side as the user enters his data. I need help with this. Below what have written so far.
<?php
include_once "../database/dbconnect.php";
session_start();
$username = isset($_POST["userNameLogin"]) ? $_POST["userNameLogin"] : $_SESSION["userNameLogin"];
$pwd = isset($_POST["passwordLogin"]) ? $_POST["passwordLogin"] : $_SESSION["passwordLogin"];
// Sending these messages to my client side validation code json-style.
if(!isset($username)){
echo("{message : 'NoName'}");
}
elseif(!isset($pwd)){
echo("{message : 'NoPW'}");
}
// creating the session variables to hold username and pwd
$_SESSION['userNameLogin'] = $username;
$_SESSION['passwordLogin'] = $pwd;
// calling the function incuded above to make connection to mysql db
dbConnection();
//query retrieves username and pwd from db and counts the result. if it is one, then they //certianly exist and if not unset the variables created above. The varibles were created
//above so i do not have to check if they exist before unsetting them.
$sQuery = "SELECT * FROM users WHERE
username = '$username' AND password = '$pwd'";
$result = mysql_query($sQuery) or die(mysql_error());
$intFound = mysql_num_rows($result);
if ($intFound == 0) {
unset($_SESSION['userNameLogin']);
unset($_SESSION['passwordLogin']);
// AD - Access Denied
echo("{message : 'AD'}");
}
else{
//a flag to set in the database who is currently online. value of 1 for users who are //online and zero for users who are not. If i want a list of those online, i check the //column called online and then check to see if the $_SESSION['username'] exist. If it //does then i know the user is online. That is what the second script is for. New to this //stuff, and do not know a better way of doing it
mysql_query("UPDATE users SET online = '1' WHERE username = '$username'") or die(mysql_error);
}
The above script should let the user login or deny access by sending messages to the validation code on client side.
As you can see, i am new to this stuff i having my share of problems. What can i do to make sure that sessions are set and unset properly i.e when user logs out.
secondly how can i monitor who is online and who is not using sessions. This is how i am trying to check who is currently online and then building a json file with the user names and sending it to the client. Json is easier to parse.
The script below tries to determine who is online
<?php
// this script determines which sessions are currently active by
// 1.) checking to see which online fields in the users table are set to 1
// 2.) by determining if a session variable has been set for these users.
// If it is not set, it means user is no longer active and script sets its online field in the users table to zero.
// After doing this, the script, then queries the users table for online fields with values one, writes them to an
// array and passes them to the client.
include_once "../database/dbconnect.php";
//include "../validation/accessControl.php";
$tempActiveUsers = array();
$activeUsers = array();
$nonActiveUsers = array();
dbConnection();
$sql = "SELECT username from users WHERE online = '1' ";
$active_result = mysql_query($sql) or die(mysql_error);
if($active_result){
while($aValues = mysql_fetch_array($active_result)){
array_push($tempActiveUsers, $aValues['username']);
}
}
forEach($tempActiveUsers as $value){
/*if($_SESSION['$value'] == $value){
$activeUsers += $value;
} */
if(isset($_SESSION['userNameLogin']) == $value){
array_push($activeUsers, $value);
}else{
array_push($nonActiveUsers, $value);
}
}
forEach($nonActiveUsers as $value1){
$sql1 = "UPDATE users SET online='0' WHERE username = '$value1'";
$set_result = mysql_query($sql1) or die(mysql_error);
}
$length = sizeof($activeUsers);
$len = 1;
$json ='{"users" : {';
$json .= '"user":[';
forEach($activeUsers as $value2){
$json .= '{';
$json .= '"username" : "' .$value2.'" }';
if($len != $length){
$json .= ',';
}
$len++;
}
$json .= ']';
$json .= '}}';
echo $json;
Please look through and give some advice. Will appreciate that very much. My project framework is up and good, but i can implement much user functionality yet because i cann't track who is online and how to manage thier sessions. If you need more background info let me know. Thanks in advance
Add 'Log out' button and click event handler on it which makes an ajax request to server to stop session by unsetting session vars or destroying session completely, and on ajax completion callback put a function to update user interface to show user is logged out.
Log in procedure can be done as follows: user clicks 'Log in' button and some form asking for user name and password appears. Then submit this form with ajax to a server script like your first one. Server script checks whether user name and password are valid and returns authentication information to a client via callback: failure notice upon failed login or some information about user currently logged in, e.g. user name, fullname and anything you might need about this user on client side in js. Then your client script proceeds according to login status returned from server-side script.
You should always remember about security.
Before sending any sensitive data to a client side with json, you shoud always check if session is valid and started. Client-side scripts could be easily modified and executed without your control and you should prevent undesired activity only on server side.
You should apply some escaping on user-POSTed fields before using them in sql queries to avoid sql injection attacks, e.g. by using mysql_escape_string().
And instead of building json strings, you can use json_encode() which works good for primitives, objects and arrays, you'll save some time.
I have a problem with the following implementation of hook_cron in Drupal 6.1.3.
The script below runs exactly as expected: it sends a welcome letter to new members, and updates a hidden field in their profile to designate that the letter has been sent. There are no errors in the letter, all new members are accounted for, etc.
The problem is that the last line -- updating the profile -- doesn't seem to work when Drupal cron is invoked by the 'real' cron on the server.
When I run cron manually (such as via /admin/reports/status/run-cron) the profile fields get updated as expected.
Any suggestions as to what might be causing this?
(Note, since someone will suggest it: members join by means outside of Drupal, and are uploaded to Drupal nightly, so Drupal's built-in welcome letters won't work (I think).)
<?php
function foo_cron() {
// Find users who have not received the new member letter,
// and send them a welcome email
// Get users who have not recd a message, as per the profile value setting
$pending_count_sql = "SELECT COUNT(*) FROM {profile_values} v
WHERE (v.value = 0) AND (v.fid = 7)"; //fid 7 is the profile field for profile_intro_email_sent
if (db_result(db_query($pending_count_sql))) {
// Load the message template, since we
// know we have users to feed into it.
$email_template_file = "/home/foo/public_html/drupal/" .
drupal_get_path('module', 'foo') .
"/emails/foo-new-member-email-template.txt";
$email_template_data = file_get_contents($email_template_file);
fclose($email_template_fh);
//We'll just pull the uid, since we have to run user_load anyway
$query = "SELECT v.uid FROM {profile_values} v
WHERE (v.value = 0) AND (v.fid = 7)";
$result = db_query(($query));
// Loop through the uids, loading profiles so as to access string replacement variables
while ($item = db_fetch_object($result)) {
$new_member = user_load($item->uid);
$translation_key = array(
// ... code that generates the string replacement array ...
);
// Compose the email component of the message, and send to user
$email_text = t($email_template_data, $translation_key);
$language = user_preferred_language($new_member); // use member's language preference
$params['subject'] = 'New Member Benefits - Welcome to FOO!';
$params['content-type'] = 'text/plain; charset=UTF-8; format=flowed;';
$params['content'] = $email_text;
drupal_mail('foo', 'welcome_letter', $new_member->mail, $language, $params, 'webmaster#foo.org');
// Mark the user's profile to indicate that the message was sent
$change = array(
// Rebuild all of the profile fields in this category,
// since they'll be deleted otherwise
'profile_first_name' => $new_member->profile_first_name,
'profile_last_name' => $new_member->profile_last_name,
'profile_intro_email_sent' => 1);
profile_save_profile($change, $new_member, "Membership Data");
}
}
}
To safely switch users
http://api.drupal.org/api/function/session_save_session/6
<?php
global $user;
$original_user = $user;
session_save_session(FALSE); // D7: use drupal_save_session(FALSE);
$user = user_load(array('uid' => 1)); // D7: use user_load(1);
// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
session_save_session(TRUE); // // D7: use drupal_save_session(TRUE);
// From here on the $user is back to normal so it's OK for the session to be saved
?>
Taken from here:
drupal dot org/node/218104
yes i confirm drupal cron user profile is "anonymous" so you have to add the permission de manager user for the "anonymous" user which is not very good in term of security ..
Not quite a random guess ... but close ...
When "real" cron runs code, it runs it as a particular user.
Similarly, when you run the Drupal cron code manually, the code will also be running as a particular user.
My suspicion is that the two users are different, with different permissions, and that's causing the failure.
Does the cron job's user have access to write the database, or read only?
Are there any log files generated by the cron job?
Update: By 'user' above, I'm referring to the user accounts on the host server, not Drupal accounts. For example, on a sandbox system I use for testing Drupal changes, Apache runs under the noone account.
profile_save_profile dosn't check for permissions or as far as I can see do 'global $user' so I don't know if this is the real issue.
$new_member = user_load($item->uid);
This looks wrong user_load should take an array not a uid (unless you are using Drupal7), but if that didn't work the rest of the code would fail too.