Here is some code I am working on. I want to keep track of some data like my password to my online connections and want to be able to get the correct password back if I forget.
Here is my code that does not work.
if(isset($_GET['addform']))
{
include $_SERVER['DOCUMENT_ROOT'].'../rcadb/db.inc.php';
try
{
$sql='INSERT INTO rcainfo
SET
coname = :coname,
coemail = :coemail,
copassword = AES_ENCRYPT(:copassword, $passwordHelper) ';
$s = $pdo->prepare($sql);
$s->bindValue(':coname', $_POST['coname']);
$s->bindValue(':coemail', $_POST['coemail']);
$s->bindValue(':copassword', $_POST['copassword']);
$s->execute();
}
catch(PDOException $e)
{
$error = 'Error adding submitted Company Data';
include 'error.html.php';
exit();
}
header('Location:.');
exit();
}
I have a form that I enter the data into etc.
any help will be apreciated
Looks like you have an issue with your include:
include $_SERVER['DOCUMENT_ROOT'].'../rcadb/db.inc.php';
Try using require instead of include becuase it will throw an error. Include doesn not throw an error.
My guess is that you probably just want to do this
$include = '../rcadb/db.inc.php';
require $include;
Related
I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D
I am trying to create a profile editing setup. It seems as though the information is edited only when an image is being uploaded. I found out that allowing the error message to be a condition allows for some more manipulation so I attempted it now my condition statement is not working as it should.
if($_FILES['files']['error']==0) {
print_r($_FILES['files']['error']);
echo "if";
foreach($_FILES['files']['name'] as $file => $name) {
$filename = $name;
try{
if(move_uploaded_file($_FILES['files']['tmp_name'][$file],'uploads/'.$filename)) {
$updateInfo = $db->prepare("UPDATE users SET image = :image, aboutme = :aboutme WHERE id = :id");
$updateInfo->bindParam(":image", $filename);
$updateInfo->bindParam(":id", $_SESSION['user']['id']);
$updateInfo->bindParam(':aboutme', $aboutme);
$updateInfo->execute();
}
} catch(Exception $e) {
echo $e;
}
}
} elseif($_FILES['files']['error'] == 4) {
print_r($_FILES['files']['error']);
echo "Elseif";
try{
$updateInfo = $db->prepare("
UPDATE users
SET
aboutme = :aboutme
WHERE id = :id
");
$updateInfo->bindParam(':id', $_SESSION['user']['id']);
$updateInfo->bindParam(':aboutme', $aboutme);
$updateInfo->execute();
} catch(Exception $e) {
echo $e;
}
} else{
print_r($_FILES['files']['error']);
echo "else";
}
}
When I check what array is being sent, its the correct one but the wrong condition, ie: it would run the else statement no matter the file check.
My question:
Is there something wrong with my code, with the exception of any security or efficiency flaws?
$_FILES['files']['error'] returns error code along with the file array. There are different type of error codes, all codes are mentioned in following link with details:
Please check by
print_r($_FILES['files'])
and see what are you getting in response.
As you posted your array response, you can get error code by $_FILES['files']['error'][0] or use switch case as mentioned in following link.
See here for more details:
http://php.net/manual/en/features.file-upload.errors.php
Also regarding debugging, always debug code step by step from top to bottom. Check $_POST, $_FILES, $_SERVER etc details if you get some problem particular related to data process.
What's wrong with this preg_match() usage? I want to check steam lobby link and if it's matching then write to database. If not, just echo the error. I am doing this through ajax. Is it better to do this with ajax or $_SERVER["REQUEST_METHOD"] == "POST"?
<?php
require("../includes/config.php");
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^((steam?:)+(/joinlobby\/730\/)+([0-9]{17,25}\/.?)+([0-9]{17,25})/$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
else {
$rank = "Golden";
$mic = "No";
try {
$stmt=$db->prepare("INSERT INTO created_lobby (lobby_link, current_rank, have_mic) VALUES (:lobby_link, '$rank', '$mic')");
$stmt->execute(array(
':input_link' => $_POST['lobbyLink']
));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
My Problem:
When I execute this code, it will give me false.
Thank you for help.
This works:
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^(steam?:)+(//joinlobby/730/)+([0-9]{17,25}/.?)+([0-9]{17,25}$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
I changed /joinlobby to //joinlobby, and remove the / at the end. I also removed the unnecessary () around everything.
I suspect you also shouldn't have (...)+ around steam?: and //joinlobby/730/. They'll cause repeated uses of those prefixes to be accepted as correct, e.g. steam:steam:...
I have edited some code I found on 'ye old internet (http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls/). I have not gotten my variation of the code to work properly. My edited versions requests another input called "pages" from index.php. Pages is put into the database along with $url and $short. Pages goes into a pages field in the database which has a varchar value. Pages is later called in serve.php for a javascript purpose. In the code below I have noted where I think the problem occurs. If your interested in my faulty code, stay tuned; I have yet to edit the other files.
I am starting to think the error could be happening in MYSQL because I almost always receive the first $html error of "Error: invalid url"
<?php
require("./db_config.php");
$url = $_REQUEST['url'];
$pages = $_REQUEST['pages'];
//this seems to be where the errors are occuring
if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $url)) {
$html = "Error: invalid URL";
} else {
$db = mysql_connect($host, $username, $password);
$short = substr(md5(time().$url), 0, 5);
if(mysql_query("INSERT INTO `".$database."`.`url_redirects` (`short`, `url`, `pages`) VALUES ('".$short."', '".$url."', '".$pages."');", $db)) {
$html = "Your short URL is<br />www.srprsr.com/".$short;
} else {
$html = "Error: cannot find database";
}
mysql_close($db);
}
?>
Consider filter_var($url, FILTER_VALIDATE_URL) instead of a regular expression.
http://php.net/filter.examples.validation
http://php.net/filter.filters.validate
If you visit my script "page.php" in the URL. A 500 Error appears. If you submit through a form it works.
<?php
## send forgot pass
$a=$_REQUEST['email_address'];
include("template.funcs.php");
$yz = mysql_connect("","","");
mysql_select_db("", $yz);
$b=mysql_real_escape_string($a);
$d=mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".$b."'");
if (mysql_affected_rows()==0){
header("Location: cart.php?pass=notsent");
}else{
send_registration_email($b,'','','');
header("Location: cart.php?pass=sent");
}
mysql_close($yz);
?>
A 500 error is a server side error, and I've found the best way to fix this is to check the logs on your server.
On the other hand, looking at your code, you may not have defined $_REQUEST['email_address']. Try this:
<?php
if (isset($_REQUEST['email_address'])) {
## send forgot pass
$a=$_REQUEST['email_address'];
include("template.funcs.php");
$yz = mysql_connect("","","");
mysql_select_db("", $yz);
$b=mysql_real_escape_string($a);
$d=mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".$b."'");
if (mysql_affected_rows()==0){
header("Location: cart.php?pass=notsent");
}else{
send_registration_email($b,'','','');
header("Location: cart.php?pass=sent");
}
mysql_close($yz);
}
?>
I would assume this has something to do with $_REQUEST['email_address'] not being defined on normal page load...
Use useful variable names. Use indenting appropriately. Only escape input before inserting it into your database. Group often used functionality in functions. Don't use $_REQUEST. Fail fast. A few hints which massively increase your code quality.
Now have a look at this:
include("template.funcs.php");
function Redirect($to)
{
header("Location: " . $to);
exit();
}
if ($_SERVER['REQUEST_METHOD' != "POST" || !isset($_POST['email_address']))
{
Redirect("cart.php?pass=notsent");
// or redirect to your "forgot password" form
}
$mailAddress = $_POST['email_address'];
$dbconn = mysql_connect("","","");
mysql_select_db("", $dbconn);
mysql_query("SELECT * FROM `customers` WHERE `customers_email` = '".mysql_real_escape_string($mailAddress)."'");
if (mysql_affected_rows() == 0)
{
Redirect("cart.php?pass=notsent");
}
send_registration_email($mailAddress,'','','');
Redirect("cart.php?pass=sent");