i want help to build my logic? - php

hey i guys i want help from you.
i am working on website project, in that i want to create "if user upload some data then it will be stored in his folder" for this i want currently login username.Because the folder name=username.
when user register to my website it will create folder in webspace which name=username.
now i want to take currently login username for defining path to uploaded image.
i give you example:
if (isset($_SESSION['username']))
{
$username=($_SESSION['username']);
$CHECK=mysql_query("Select `status` from `user_reg` where `username`=$username");
if ($check="Admin") {
$userimage="/Place4Info/Data/Admin_data/".$username."/";
} else {
$userimage="/Place4Info/Data/User_data/".$username."/";
}
i save path in $userimage & then use it everywhere.
above code is not running

Use double =:
if ($check == "Admin") {
$userimage="/Place4Info/Data/Admin_data/".$username."/";

First, $CHECK is not the same as $check. Second, $CHECK is a mysql resource, not a string containing a value from the database. Third, you can print mysql_error() after mysql_query() to determine wheter the query failed and why.
Something like:
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$res = mysql_query("Select status from user_reg where username='$username'");
$row = mysql_fetch_assoc($res);
$check = $row['status'];
if ($check == "Admin") {
$userimage = "/Place4Info/Data/Admin_data/".$username."/";
}
else {
$userimage = "/Place4Info/Data/User_data/".$username."/";
}
}

you need to use mysql_fetch_array on the result of your query:
$res = mysql_query("Selectstatusfromuser_regwhereusername=$username");
$check = mysql_fetch_array($res);
Also I noticed you are switching between UPPERCASE check and lowercase, you can't mix them up in PHP.

Related

whitelist user using file_put_contents forms

<?php
$filename = 'whitelist.txt';
if (isset($_POST['uname'])) {
$uname = $_POST['uname'];
file_put_contents($filename, '{"'.$uname.'"}');
if (empty($uname)) {
header("Location: generator.php?error=No Empty Username");
exit();
}
}else{
header("Location: generator.php");
exit();
}
The expected output should be:
{"User1", "User2"}
But it is:
{"User1"}
I just wanna make a whitelist user by using a form so he can get whitelisted, I hope someone can help! Thank you!
To make a user blacklist you'll need to use some database and authentication otherwise you'll end up with problems in a case where like user1 and user2 have the same data
But for your question.
One way is to replace the last character every time here is how...
replace the file_put_con... line with this
$existing = file_get_contents($filename);
if(strpos($existing,"}")){ //check if at least one username exists
$newcontent = str_replace('}',',"'.$uname.'"}',$existing); //replace old data with new
file_put_contents($filename,$newcontent);
} else { // incase there is no username at all
$newcontent = '{"'.$uname.'"}';
file_put_contents($filename,$newcontent);
}
You'll obviously corrupt the data if you enter } in the uname
So prevent that by using entities or prevent the } character from being accepted

Cant delete files from folder using unlink function in php

Unable to delete file from folder otherwise code work perfectly.
same code i used for replacing or updating image where it works fine but here dosent able to delete data from folder by their id or name
if(isset($_POST['8maths_delete'])) //post method button name
{
$id = $_POST['delete_id']; //data fetch by id
$files_query = "DELETE FROM 8maths WHERE id='$id'"; //deleting data from sever
$files_query_run = mysqli_query($connection, $files_query); //query run
if($files_query_run) // query run
{
unlink("upload/".$row['files']); //unlink where upload folder where all the files held. but dosent able to delete file from folder
$_SESSION['success'] = "Your Data is Deleted"; //session for echo
header('Location: 8thmaths.php');
}
else
{
$_SESSION['status'] = "Your Data is not Deleted";
header('Location: 8thmaths.php'); //redirecting location
}
}
There are two issues I can see:
1 - You reference $row['files'] but I don't see $row defined anywhere in your code.
2 - Using the word 'files' I assume there could be multiple, if that's the case you need to loop over all the files and unlink them either with something like:
A foreach loop:
$result = mysqli_fetch_all($files_query_run, MYSQLI_ASSOC);
foreach($result as $row) {
unlink("upload/".$row['files']);
}
Or using a while loop.
while ($row = mysqli_fetch_assoc($files_query_run)){
unlink("upload/".$row['files']);
}
I hope this helps get you off to the right start.

php - Login redirecting to same page, static but different roles

After doing my SQL Schema (Different types of users redirected to same page (index.php) with different content), I'm starting to make my login system.
I now have this:
function login($email,$password){
$mysqli = $this ->dbConnect();
if($mysqli){
$strQuery = "SELECT USERS.ID, USERS.EMAIL, TYPES.NAME FROM `USERS` LEFT JOIN `TYPES` ON USERS.TYPEID = TYPES.ID WHERE `EMAIL` = '$email' AND `PASSWORD` = '$password'";
$recordSet = $mysqli->query($strQuery);
$row = $recordset->fetch_assoc();
if($recordset->num_rows>0){
$_SESSION['auth'] = $row['ID'];
$_SESSION['username'] = $row['EMAIL'];
$_SESSION['type'] = $row['NAME'];
header ("location:"index.php");
return true;
}
//....
}
}
Does this look good? Is the query right? Any suggestions for improvement?
UPDATE
I have my login working now. And it's redirecting to index.php. But in index php I don't have acess to the $_SESSIONS variables i have stored on my function login. Is there any problem with the attribuitions? Placing the header inside the function not good?
Thanks :)
I summarized the previous comments.
1. Issue: you didn't used the same variables
function login($email,$password){ and $strQuery = " ... WHERE EMAIL = '$email' AND PASSWORD = '$password'";
2. Recomendation: use the same namming convention
On your SQL request you used two way to use fields: USERS.EMAIL and EMAIL = (with ` arround).
Use the same. This will be easier for later & debugging.
i.e.: of course, you should not use table.field each time. Not mandatory for example if you have only one table OR if the fields are not shared between them. For my perosnnal usage, I always use this table.field. This will prevent any future issue :)
3. Protect your data from any injection
Example:
$post_email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : null;
Alter call
$this->login($post_email, ...)
And finally use something like this to protect your data:
$email = $mysqli->real_escape_string($email);
and you are ready for your request:
" SELECT [..] FROM users as u [...] WHERE u.email = '$email' "
4. Or use specific functions
Example (real_escape_string not needed anymore):
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE email = ? AND password = ?');
$stmt->bind_param('s', $email);
$stmt->bind_param('s', $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
http://php.net/manual/fr/class.mysqli.php
5. Sessions
If you want to activate sessions on a spacific page, the first code (at the first line) should be session_start().
Calling this method will activate the sessions and load the $_SESSION variable with content.
<?php // index.php
session_start(); // first line
// ... code
var_dump($_SESSION);
?>
&
<?php // page.php
session_start(); // first line
// ... code
$_SESSION['test'] = time();
Header('Location: index.php');
?>
Visit index.php -> nothing on the debug
Visit page.php -> you will be redirected on index.php
On index.php -> you will have data
Enjoy session :p
6. Handle specific data
To begin with, you should coose a way to store the credential access (ACL) for each user. For example, store on the database some values as 100001, and each number is a yes/no access for a specific action (binary access mode) ; another system is to store the level '1,2,3,4,5' ... or 'member,customer,admin, ...'. So many ways :)
I will choose the USER.ACCESS = member|customer|admin solution
On the login page
// is user successfully logged
$_SESSION['access'] = $row['access']; // member|customer|admin
// Header('Location: index.php');
On any page of your site:
if( in_array($_SESSION['access'], ['member', 'admin']) ) {
echo 'You are a member, you can see this part';
}
if( in_array($_SESSION['access'], ['customer', 'admin']) ) {
echo 'You are a customer, you can see this part';
}
Or
if( checkAccess() ) {
echo 'Welcome user !';
if( checkAccess(['member', 'customer']) ) {
echo 'This is a section for member, customer or admin :)';
}
if( checkAccess('member') ) {
echo 'You are a member, you can see this part';
}
if( checkAccess('customer') ) {
echo 'You are a customer, you can see this part';
}
}
function checkAccess($types = null) {
if( !isset($_SESSION['access']) )
return false; // not logged
if( is_null($types) )
retun true; // if empty, provide info about loggin.
// admin has always access to all sections of the website
$hasAccess = in_array($_SESSION['access'], ((array) $types) + ['admin']);
return $hasAccess; // user is logged + has accessor not ?
}
Of course, you can also use includes
if( checkAccess('member') ) {
include 'secret_page_for_member.php';
}
Or, at the begening of the included page:
<?php
if( !checkAccess('admin') ) {
return '403 - Not authorized';
// die('403');
// throw new Exception('403');
}
// your code
?>

mysql insert success but nothing is added

look at this code
<?
require_once("conn.php");
require_once("includes.php");
require_once("access.php");
if(isset($_POST[s1]))
{
//manage files
if(!empty($_FILES[images]))
{
while(list($key,$value) = each($_FILES[images][name]))
{
if(!empty($value))
{
$NewImageName = $t."_".$value;
copy($_FILES[images][tmp_name][$key], "images/".$NewImageName);
$MyImages[] = $NewImageName;
}
}
if(!empty($MyImages))
{
$ImageStr = implode("|", $MyImages);
}
}
$q1 = "insert into class_catalog set
MemberID = '$_SESSION[MemberID]',
CategoryID = '$_POST[CategoryID]',
Description = '$_POST[Description]',
images = '$ImageStr',
DatePosted = '$t',
DateExp = '$_SESSION[AccountExpDate]',
FeaturedStatus = '$_POST[sp]' ";
//echo $q1;
mysql_query($q1) or die(mysql_error());
}
//get the posted offers
$q1 = "select count(*) from class_catalog where MemberID = '$_SESSION[MemberID]' ";
$r1 = mysql_query($q1) or die(mysql_error());
$a1 = mysql_fetch_array($r1);
header("location:AddAsset.php");
exit();
?>
The mySql insert function isn't adding anything also it return success to me , I've tried using INSERT ... Values but what it done was overwtiting existing value ( i.e make 1 entry and overwties it everytime).
I am using PHP 4.4.9 and MySql 4
I tried to add from Phpmyadmin and it is working also it was working after installation but after i quit the browser and made a new account to test it it is not working but the old ones is working ! you can see it here http://bemidjiclassifieds.com/
try to login with usr:openbook pass:mohamed24 and you can see it will be working but any new account won't work!
Maybe $_POST[s1] is not set or you are inserting into a different database than you are watching.
if(isset($_POST[s1]))
should probably be
if(isset($_POST['s1']))
(note the quotes). Also, it's best to NOT depend on a field being present in the submitted data to check if you're doing a POSt. the 100% reliable method is
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
As well, you're not checking if the file uploads succeeded. Each file should be checked like this:
foreach($_FILES['images']['name'] as $key => $name) {
if ($_FILES['images']['error'][$key] !== UPLOAD_ERR_OK) {
echo "File #$key failed to upload, error code {$_FILES['images']['error'][$key]}";
}
...
}
Don't use copy() to move uploaded files. There's a move_uploaded_files() function for that, which does some extra sanity checking to make sure nothing's tampered with the file between the time the upload finished and your script tries to move it.

if statement on mysql query

i am trying to use the !isset on the '$class' variable to see if it has a value or not, and then base the mysql_query function on that. but it's a no go. see anything wrong?
<?php session_start();
$heyyou = $_SESSION['usern'];
$points = $_SESSION['points'];
$school = $_SESSION['school'];
$class = $_POST['class'];
$prof = $_POST['prof'];
$date = $_POST['dater'];
$fname = $_FILES['fileToUpload']["name"];
?>
<div id='contenttext' class='contenttext'>
<?php
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO uploadedfiles (usename, filename, date, teacher, class) VALUES ('$heyyou', '$fname', '$date', '$prof', '$class')";
if (!isset($class)){
echo 'You need to pick a class for the content'; }
else{
mysql_query($query); }
mysql_close();
?>
<?php
if (($_FILES["fileToUpload"]["type"] == "image/gif" || $_FILES["fileToUpload"]["type"] == "image/jpeg" || $_FILES["fileToUpload"]["type"] == "image/png") && $_FILES["fileToUpload"]["size"] < 10000000)
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"upload/" . $_FILES["fileToUpload"]["name"]);
echo "Your file has successfully been uploaded, and is awaiting moderator approval for points." . "<html><br><a href='uploadfile.php'>Upload more.</a>";
}
else
{
echo "Files must be either JPEG, GIF, or PNG and less than 10,000 kb";
}
?>
</div>
</body>
</html>
Two major security problems with your code:
You're wide open to SQL injection attacks (see: http://bobby-tables.com/)
You're blindly trusting the user is not malicious for the file upload. The ['type'] and ['name'] fields are completely under user control, and it's trivial to hack the upload to say it's a gif while still uploading a PHP script. You then use the user-supplied filename, WHICH CAN CONTAIN PATH INFORMATION, and dump it directly to your server. This leaves the door wide open to a malicious user uploading any file they want, anywhere on the server.
Minor point #3:
You don't check if the database query succeeds. Never assume a query succeeds. Even if the SQL statement is perfectly valid, there's far too many other reasons that could make it fail anyways. Always check the query call with ... = mysql_query(...) or die(mysql_error()) as a bare minimum error handler.
Probably because $class is being set, by you. Try if (empty($class)){
I maybe wrong but class is a reserved word try another name and $class != ""
http://www.php.net/manual/en/reserved.keywords.php
BTW remove you DB Conect info please we me be nice but some of the people reading this may not be. ;-)
Try this, first initialize all your variables and then assign the POST values.
Eg:
$class='';
$class = $_POST['class'];
if (!isset($class)){
echo 'You need to pick a class for the content';
}
You can not use $class since class is a keyword reserved.
This may work too:
$query = "INSERT INTO uploadedfiles (usename, filename, date, teacher, class) VALUES ($heyyou, $fname, $date, $prof, $class)";
Since double quote can understand variables when they inside it.
Another think is date is a keyword too reserved by MySQL.
Finlly try to see what $_POST['class']; content like this:
echo $_POST['class'];
Because perhaps you forget to give a name to your html element.
The variable $class is always set because of $class = $_POST['class']. so isset($class) will always be true regardless of class posted value. notice the difference in below statements:
$class = '';
if (isset($class)) {
echo 'a';
}
if($class) {
echo 'b';
}
the output is: a
//replace this:
if (!isset($class)){
echo 'You need to pick a class for the content'; }
else{
mysql_query($query);
}
//with this:
if (isset($class) && $class){
mysql_query($query);
else{
echo 'You need to pick a class for the content'; }
}

Categories