My php header("Location: example.com") seems to redirect before the database query is inserted (on one computer). Which imo is weird, because I check if the database returns true before header runs.
This works fine for me, but on my friends system it seems to redirect too early. If I remove the header() function and die(). It inserts fine.
This is coded as an Extension to mediawiki. I dont know if the problem lies here. Mediawiki has its own database query class and functions.
if ($_GET['action'] == 'postReply') {
$threadid = $_POST['t_id'];
$content = $_POST['content'];
$postReply = postThreadReply($threadid, $username, $userid,
$content);
if ($postReply == 1) {
header("Location: ?title=" . $title . "&t=" . $threadid . '#last');
die();
}
This code is adapted to be read easier.
This is the main function which the header redirects too early.
postThreadReply() do some checks and inserts into the correct tables. postThreadReply() returns 1 if each query returns true.
I don't think more code is necessary, but let me know if it is. :)
So I'm wondering if there is something wrong with my code, or within Mediawiki? Or is this a known issue with the header() function? Is there any alternative method I can try?
This is my first question here, so I'm sorry if my question is unclear or I dont provide enough code.
EDIT:
postThreadReply()
function postThreadReply($threadid, $username, $userid, $t_post) {
if (postExistDuplicate($threadid, $username, $userid, $t_post)) return 3;
if (!threadExist($threadid)) return 4;
$inpost = insertPost($threadid, $username, $userid, $t_post);
if (!$inpost) return 2;
return 1;
}
insertPost()
function insertPost($threadid, $username, $userid, $t_post) {
$datetime = date_create()->format('Y-m-d H:i:s');
$dbw = wfGetDB( DB_MASTER );
$res = $dbw->insert(
'disc_posts',
array(
'id' => null,
'thread_id' => $threadid,
'author' => $username,
'author_id' => $userid,
'content' => $t_post,
'posted' => $datetime,
'deleted' => 0
)
);
return $res;
}
^ Mediawikis way of doing queries.
Related
I'm trying to get started with Cassandra with PHP for the first time using the PHP Driver https://github.com/datastax/php-driver/ whose documentation is available here: https://github.com/datastax/php-driver/tree/master/features.
For this purpose, here is what we produced for the configuration file (conf.php):
<?php
ob_start();
session_start();
$username = "toto";
$password = "totoPass";
define( 'BASE_PATH', __DIR__ . '/' );
try {
$cluster = Cassandra::cluster()
->withContactPoints('245.555.121.1', 'example.com', 'localhost', "192.168.1.1", "192.168.1.2")
->withPort(9042)
->withCredentials($username, $password)
->build();
$con = $cluster->connect();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$con->execute("CREATE KEYSPACE IF NOT EXISTS urlfetch");
$con->execute("USE urlfetch");
}
catch(PDOExeption $e) {
echo "Connection failed: " . $e->getMessage();
}
And here we are trying to insert data into the images Table with the caching system (the link of which was found at: Is there any side effect of increasing row_cache_size_in_mb in Cassandra?):
function insertImage($url, $src, $alt, $title, $description) {
global $con;
//création de la column Image
$con->execute("CREATE TABLE IF NOT EXISTS images(siteUrl varchar PRIMARY KEY, imageUrl varchar, alt varchar, title varchar,
description varchar) WITH caching = { 'keys': 'ALL', 'rows_per_partition': 'NONE' };");
$query = $con->prepare("INSERT INTO images(siteUrl, imageUrl, alt, title, description)
VALUES(:siteUrl, :imageUrl, :alt, :title, :description)");
$query->bindValue(array(
":siteUrl" => $url,
":imageUrl" => $src,
":alt" => $alt,
":title" => $title,
":description" => $description
));
return $query->execute();
}
And finally, according to the Cassandra PHP Driver documentation (here: https://github.com/datastax/php-driver/tree/master/features), it is possible to perform Asynchronous requests or to perform requests in parallel like this:
<?php
$data = array(
array(41, 'Sam'),
array(35, 'Bob')
);
$statement = $session->prepare("UPDATE users SET age = ? WHERE user_name = ?");
$futures = array();
// execute all statements in background
foreach ($data as $arguments) {
$futures[] = $session->executeAsync($statement, array(
'arguments' => $arguments
));
}
// wait for all statements to complete
foreach ($futures as $future) {
// we will not wait for each result for more than 5 seconds
$future->get(5);
}
So we would like to know:
1 - If we omitted something in the Cassandra configuration file (1st code above) ??? If so, how do we make our Cassandra setup code perfect for PHP ???
2 - Do you think what we tried to do in the insertImage function above ($con->execute("CREATE TABLE IF NOT EXISTS images... ) WITH caching = { 'keys': 'ALL', 'rows_per_partition': 'NONE' };") is correct ???
If not, how to create a table in Cassandra for PHP with a CACHE system ???
3 - How to apply Asynchronous processing to our insertImage function by modifying it and following the logic of the 3rd code above from the Cassandra DataStax Driver documentation example ???
Please help us.
During my create user process I make a few queries to various database's to get the new user setup. This script has been working fine for about a year and a half, but now something is off.
So the first thing I do is I check to see if a user exists with the credentials being submitted. I've thoroughly tested the check and I'm confident my issue isn't there.
If that check comes back false then the script continues to create the user.
public function registerUser() {
parse_str($_SERVER['QUERY_STRING'], $data);
$data = (object) $data;
$check = json_decode($this->checkUserExists($data->email));
if ($check->res) {
$res = new \stdClass();
$res->res = false;
$res->user_status = $check->user_status;
$res->msg = 'User exists.';
echo json_encode($res);
}
if (!$check->res) {
$this->createUser($data);
}
}
The problem arises after all the queries have been completed, the script does not seem to want to run the if statement at the bottom. I marked it with comment characters so it's easier to find, but I included the entire function for clarity, maybe I'm doing something that is causing the issue.
I tried invoking an error manually at various points during the script. And I am able to trigger an error all the way down to the bottom of the script.
private function createUser($data) {
$Crypt = new CryptController();
$AuthSelect = new AuthController();
$Time = new TimeController();
$remote_address = new RemoteAddressController();
$Session = new SessionController();
$AuthInsert = new AuthModel_Insert();
$hashed_password = $Crypt->create_hash($data->password);
$data->password = '';
$AuthData = json_decode($AuthSelect->getAuth());
$system_auth_id = $AuthData->system_auth_id;
$user_id = $Crypt->get_uuid();
$user_auth_id = $Crypt->get_uuid();
$user_createddate = $Time->time();
$user_updateddate = $Time->time();
$user_lastupdateddate = $Time->time();
$agent_ip = $remote_address->getIpAddress();
$userData = $this->createUserObject(
$user_id,
$user_auth_id,
$system_auth_id,
$hashed_password,
$user_createddate,
$user_updateddate,
$user_lastupdateddate,
$data
);
$agentData = $this->createAgentObject(
$user_id,
$agent_ip,
$data
);
//////////////////////////////////////////
$create_user = $AuthInsert->createNewUser(
$userData
);
$create_user_agent = $this->setUserAgent(
$agentData
);
$sessionKeyData = new \stdClass();
$sessionKeyData->user_id = $user_id;
$sessionKeyData->user_auth_id = $user_auth_id;
$sessionKeyData->system_auth_id = $system_auth_id;
$sessionKeyData->agent_id = $create_user_agent->agent->agent_id;
$set_session_key = $Session->setSessionKey(
$sessionKeyData
);
$send_activation_email = $this->createUserActivation(
$userData
);
if (
$create_user &&
$create_user_agent->res &&
$set_session_key->res &&
$send_activation_email->res) {
$res = new \stdClass();
$res->res = true;
$res->msg = 'New user successfully created.';
echo json_encode($res);
} else {
$res = new \stdClass();
$res->res = false;
$res->msg = 'Error: User creation process incomplete.';
echo json_encode($res);
}
//////////////////////////////////////////
trigger_error("Invoked Error: ",E_USER_ERROR);
}
The queries themselves go through just fine, all the tables are populated just fine. The issue is that after that happens the script doesn't finish. It seems to end the createUser() function and return to the registerUser() function at which point the user will exist so it will return false and echo that back to the client.
In my testing it seems my issue might be at the bottom with that if statement. But I've tested each of those queries individually and they do return the desired booleans to get the true condition. But, even the false condition doesn't go through which should return 'Error: User creation process incomplete.'. That doesn't happen either.
I'm hoping someone sees something I'm missing because I've been stuck on this problem for too long. I appreciate any guidance that might lead me to an answer. Thanks in advance.
Just for clarification the message I'm getting back is $res->msg = 'User exists.'; which comes from registeruser(). The message I'm expecting back is $res->msg = 'New user successfully created.'; which should come from createUser().
I am debugging a php system installed on my shared-host (linux, cpanel, php 5.2). I found that the problem I am experience is within one function in a php file. I want to see what are the values of all the variables in that file when it is executed.
I tried mail() to mail the variable values to myself but it did not work.
I also tried error function so that I can read the error log file, but no file was created in my host, or no message was in the error files. I tried following error functions.
error_log("Err!", 0);
error_log("Err", 1,"operator#example.com");
error_log("Err", 3, "/my-errors.log");
I am using a shared host from namecheap, which does not provide all the functionalities, nor access to all logs.
any idea how I can inspect what is going on in that specific function, and what are the values of the variable in it in the execution time?
many thanks
The function in question is as follows, if it helps:
/**
* Reset a user's password
* #param $args array first param contains the username of the user whose password is to be reset
*/
function resetPassword($args, &$request) {
$this->validate();
$this->setupTemplate($request);
$site =& $request->getSite();
$oneStepReset = $site->getSetting('oneStepReset') ? true : false;
$username = isset($args[0]) ? $args[0] : null;
$userDao =& DAORegistry::getDAO('UserDAO');
$confirmHash = $request->getUserVar('confirm');
if ($username == null || ($user =& $userDao->getByUsername($username)) == null) {
$request->redirect(null, null, 'lostPassword');
}
$templateMgr =& TemplateManager::getManager();
$hash = Validation::generatePasswordResetHash($user->getId());
if ($hash == false || $confirmHash != $hash) {
$templateMgr->assign('errorMsg', 'user.login.lostPassword.invalidHash');
$templateMgr->assign('backLink', $request->url(null, null, 'lostPassword'));
$templateMgr->assign('backLinkLabel', 'user.login.resetPassword');
$templateMgr->display('common/error.tpl');
} else if (!$oneStepReset) {
// Reset password
$newPassword = Validation::generatePassword();
if ($user->getAuthId()) {
$authDao =& DAORegistry::getDAO('AuthSourceDAO');
$auth =& $authDao->getPlugin($user->getAuthId());
}
if (isset($auth)) {
$auth->doSetUserPassword($user->getUsername(), $newPassword);
$user->setPassword(Validation::encryptCredentials($user->getId(), Validation::generatePassword())); // Used for PW reset hash only
} else {
$user->setPassword(Validation::encryptCredentials($user->getUsername(), $newPassword));
}
$user->setMustChangePassword(1);
$userDao->updateObject($user);
// Send email with new password
import('classes.mail.MailTemplate');
$mail = new MailTemplate('PASSWORD_RESET');
$this->_setMailFrom($request, $mail, $site);
$mail->assignParams(array(
'username' => $user->getUsername(),
'password' => $newPassword,
'siteTitle' => $site->getLocalizedTitle()
));
$mail->addRecipient($user->getEmail(), $user->getFullName());
$mail->send();
$templateMgr->assign('pageTitle', 'user.login.resetPassword');
$templateMgr->assign('message', 'user.login.lostPassword.passwordSent');
$templateMgr->assign('backLink', $request->url(null, $request->getRequestedPage()));
$templateMgr->assign('backLinkLabel', 'user.login');
$templateMgr->display('common/message.tpl');
} else {
import('classes.user.form.LoginChangePasswordForm');
$passwordForm = new LoginChangePasswordForm($confirmHash);
$passwordForm->initData();
if (isset($args[0])) {
$passwordForm->setData('username', $username);
}
$passwordForm->display();
}
}
I would just use a var_dump at the end of the function like this. Will give you all of the data, if you wrap it in tags it looks nicer.
echo "<pre>";
var_dump(get_defined_vars());
echo "</pre>";
Or do it to your $this var.
i have a file on the disk that i retrieve, and store its contents into an array for display as json.
function getCurrentPic($username, $password){
$con = connectToPDO();
$valid = validateUser($username, $password);
if($valid == 1){
$sth = $con->prepare('
SELECT current_pic
FROM user
WHERE
username = :username');
$sth->execute(array(':username' => $username));
$sth->bindColumn(1, $imagePath, PDO::PARAM_STR);
$sth->fetch(PDO::FETCH_BOUND);
echo spitImageJSON($imagePath);
}
}
function spitImageJSON($imagePath){
if(strlen($imagePath) > 1){
$IDPath = $imagePath.'d';
$id = getContentsAtPath($IDPath);
$image = getContentsAtPath($imagePath);
//echo "$imagePath";
$arrayData = array(array(
'image' => $image,
'id' => $id
));
return json_encode($arrayData);
}
}
that code doesn't work unless i uncomment the echo "$imagePath", at which point it prints the path AND the json.. when i re-comment it, nothing is echoed. I'm losing my mind. please help.
btw the file is just a base64 encoded string.. id is just a numerical string
by placing
header("Content-type: application/json");
before returning the json, it worked like it was supposed to without the echo $imagePath
In case anyone else has this problem, I had to add the following on top over the correct answer:
header("Access-Control-Allow-Origin: *");
I have a simple form that inserts data into my sqlite database. It works just fine on my localhost, however, I am not getting the insert to work on my remote server. How do I get error messages if my execute() never happens or === false?
Here is my code:
if (isset($_POST["submit"])) {
$email = $_POST["Email"];
$name = $_POST["txt_Name"];
$agency = $_POST["sel_Agency"];
$subagency = $_POST["txt_SubAgency"];
$location = $_POST["txt_Location"];
$params = array(
':email' => $email,
':name' => $name,
':agency' => $agency,
':subagency' => $subagency,
':location' => $location
);
$stmt = $db->prepare($sql);
if ($stmt->execute($params) === FALSE) {
//HOW TO SHOW ERROR CODE HERE
}
}
I tried a try-catch, but didn't get anything. However, if I echo "ERROR" for example, I get the echo ERROR on screen.... I know it isn't working also, since the db has no new rows.
Any help would be appreciated. Thanks!
If you are using PDO, to get the last error use $db->errorCode() to get erro code and $db->errorInfo() get error info