Where request comes from (php) - php

I have 3 php pages. These are related to my message system.
1st file is inbox.php
2nd file is sent.php
3rd file is delete_message.php
My questions is about redirecting with header('Location:xxx'); I want to redirect user to where from he/she request delete query.
For example if he/she delete a message from inbox I want to redirect him to inbox.php, else he/she must redirected to sent.php
What I should add to my delete script?
<?php
include '../config/db.connect.php';
$m_id = $_GET['message_id'];
$delete = $db->exec("DELETE FROM message WHERE message_id ='$m_id'");
if ( $delete ) {
header("Location:../message_sent.php");
}
else {
echo "delete error..";
echo "An error message...");
}
?>

Use $_SERVER['HTTP_REFERER'] to get the previous page url.

Related

PHP sessions and session destroy

I have created a page where 'Job's' stored on a database are deleted.
On a page called
delete.php
the job to be deleted is selected.
The user is then directed to deleteaction.php where the job is deleted.
The user is then auto redirected back to
delete.php
This all works fine however once the user is returned to delte.php I would like a pop-up/ alert saying 'Job deleted'.
However if the user enters the page not from
deleteaction.php
then I dont want this pop-up to appear. I have tried to use sessions where a variable
$status
indicates if the user has just been directed to
deleteaction.php
and a job has been deleted.
Code on deleteaction.php:
session_start();
$id=$_GET['id'];
$sql= "DELETE FROM `Job` WHERE `Job`.`Job_Customer_id`='". $id."';";
$stmt=$dbh->query($sql);
$status = "deleted";
$_SESSION['delstat'] = $status;
header("Location:delete.php");
Code from delete.php:
session_start();
$status = $_SESSION['delstat'];
if ($status = "deleted"){
echo '<script language="javascript">';
echo 'alert("Job Deleted")';
echo '</script>';
}
else {
echo "No";
}
session_destroy();
........
The problem is the page delete.php always displays the alert that a job has been deleted every time the page is visited.
Not sure if its something wrong with my loop or the session use?
Thanks in advance!
You're presently assigning = instead of comparing == in
if ($status = "deleted")
being always TRUE
change that to
if ($status == "deleted")

Delete entire mysql row by grabbing link?

I have a list of users with names and emails displayed for admins and users ON THE SAME PAGE....
If an admin views it it shows an extra column called "Action"
Which shows three links
Edit | Delete | Make Admin
--------------------------
I have the delete button grab information from that table row and move it into a link
Here is the setup
echo "
<td>
<a href='admin.php?action=deleteuser&username={$row['username']}'>Delete</a>
</td>";
Here it is in action:
admin.php?action=deleteuser&username=bob
I spaced it out for viewing purposes.....
Anyways
I want the site to somehow grab the information FROM the url and somehow delete the row where username is equal to "bob" or something like that
Any ways to do this? Please help out.
Also how would I make it secure since the page is accessible to anyone so if someone was to manually type that link they would delete it wouldn't they?
Maybe check if the user is admin before the link runs
Here is my check admin code
if (has_access($session_user_id, 1) === true) {
echo 'The user is an admin!';
}
Something like this in admin.php ?
function getLoginUserByCookie()
{
return isset($_COOKIE["loginusername"]) ? $_COOKIE["loginusername"] : "";
}
if(getLoginUserByCookie() != "admin")
{
header("Location: /login.php");
exit;
}
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "dbuser", "dbpass");
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$strSQL = "DELETE FROM users WHERE (username=:username);";
$stmt = $pdo->prepare($strSQL);
$stmt->execute(array(
":username" => $_GET["username"]
));
/login.php is a big job, you might find some example to check login. And save loginusername in cookie.

php mysql + create a friend request system

i am creating a friend request system that allow user to send request to each other to add as friends like facebook
and i have 2 conditions that if :
the user is the profile owner he can not add him self i will echo an
error msg
the user is not the owner of the profile it will echo a message that
say wait then the request is send
if the user has already send the request i will echo a message to infor the user that a request had been send.
but the error is that i am in the first condition because the system display that the user is the owner profile but this is wrong
can anyone help me ??
this is a chunk of code
function addAsFriend(a,b){
//alert("Member with id:" + a + "request friendship with the memeber with id:" + b);
var url = "script_for_profile/request_as_friend.php";
$("#add_friend").text("please wait...").show();
$.post(url,{request:"requestFreindship",mem1:a,mem2:b},function(data){
$("#add_friend").html(data).show().fadeOut(12000);
});
}
<div class="interactContainers" id="add_friend">
<div align="right">Cancel</div>
Add <?php echo $username ?> as Friend?
Yes
request_as_friend.php
<?php
//var we need for both members
$mem1=preg_replace('#[^0-9]#i','',$_POST['mem1']);
$mem2=preg_replace('#[^0-9]#i','',$_POST['mem2']);
if(!$mem1||!$mem2)
{
echo "Error .missing data";
exit();
}
if($mem1==$mem2)
{
echo "Error you can not add yourself as friend";
exit();
}
require_once('../include/connect.php');
if($_POST['request']=="requestFriendship")
{
//check that there is not a request pending where this viewer is requesting this profile owner
$sql = mysql_query("SELECT id FROM friend_requests WHERE mem1='$mem1' AND mem2='$mem2'limit1")or die(mysql_error());
$numRows = mysql_num_rows($sql);
if($numRows > 0)
{
echo "You have a friend request pending already for this member. they must approve it when they view their request list";
exit();
}
//check that there is not a request pending where this profile owner is not already requesting this viewer
$sql = mysql_query("SELECT id FROM friend_requests WHERE mem1='$mem2' AND mem2='$mem1'limit1")or die(mysql_error());
$numRows = mysql_num_rows($sql);
if($numRows > 0)
{
echo "This user has requested you as friend already! Check your friend Request on your profile";
exit();
}
$sql = mysql_query("INSERT INTO friend_requests(mem1,mem2,timedate) VALUES('$mem1','$mem2',now())") or die (mysql_error("friend request insertionn error"));
//$sql = mysql_query("INSERT INTO pms(to,from,time,sub,msg) VALUES('$mem2','XXXXX',now(),'New Friend Request','YOU Have a New friend request waiting for approval.<br /><br />Navigate to your profile and check your friend request.<br /><br />Thank you.')") or die (mysql_error("friend request PM insertionn error"));
echo "Friend Request sent succesfully. this member must approve the request";
exit();
}
?>
I was totally wrong, you don't need to create any extra flag, just store the user_id -which you retrieve from the database when the user logs in - store it in the session then when he/she clicks on the add friend button check the $_SESSION['user_id'] with the id of the other user before completing the friendship function, if they're both the same, means it's the same person, otherwise add friends.
What the post array returns for mem1 and mem2?
However, you shouldn't compare the post data. Or not both.
For example you have logged in, your id is stored in session. You are opening a user profile i.e.: http://yoursite.com/viewprofile.php?id=1001 . Then after passing from the jquery you should check in PHP smth like:
if ($_GET['id'] = $_SESSIOM['id']) {
//you cannot add yourself
}

Redirect on logout and display "You have successfully logged out!"

I have a membership service on my website. Currently when someone logs out they are redirected to logout.php that has this code on it:
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//display success message
echo "<center>You have successfully logged out!<br><a href = '/review-pratt/index.php' class='icon-button star'>Return Home</button></center>";
}
?>
Instead of having the users be taken to "logout.php" and viewing a boring page that says they logged out. I want them to be redirected to index.php. That part is easy, I know.
I am wanting a notification bar across the top to appear notifying them that they successfully logged out. I have tried to do this before and never got anything to work. Any help or suggestions would be appreciated!
Update
I have changed the logout.php code to:
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//Redirect with success message
header('Location: /index.php?msg=' . urlencode("You have been successfully logged out!"));
}
?>
and added the following code to my index.php:
<?php
if ($_GET['msg'])
{
echo '<div class="success_message">' . base64_decode(urldecode($_GET['msg'])) . '</div>';
}
?>
And when I log out I receive this error:
Warning: Cannot modify header information - headers already sent by (output started at /home/content/38/10473938/html/review-pratt/business_profiles/logout.php:19) in /home/content/38/10473938/html/review-pratt/business_profiles/logout.php on line 35
you could do something like this:
header('location: index.php?status=loggedout');
and in your index.php file just look to see if status is not empty, and show a div with the status like this:
<?php
if(!empty($_GET['status'])){
echo '<div>You have been logged out!</div>';
}
?>
also inside that if statement you can clear user session aswell..
There are many solutions to this, but almost all of them require logout.php to pass the message, and index.php to have code to display the message.
My preferred method is to pass the message as a URL parameter. Use header to re-direct, use base64_encode to shorten the text in the url, and url_encode to make sure that the URL doesn't get junked up.
//Redirect with success message
header('Location: /index.php?msg=' . urlencode(base64_encode("You have been successfully logged out!")));
Then, on your index.php page
if ($_GET['msg'])
{
echo '<div class="success_message">' . base64_decode(urldecode($_GET['msg'])) . '</div>';
}
Edit: If your headers have already been sent out (have you echoed out some text on a line above these?), you can use Javascript to do the redirection.
Replace header('Location: ') with this: echo '<meta http-equiv="Refresh" content="0;url=http://example.com/index.php?msg=' . urlencode(base64_encode('You have been successfully logged out!')) . '">';
You could use "Noty" plugin to enable notifications on your web-app.
see here: http://needim.github.com/noty/
Implementation should look something like that:
Redirect the user to index.php?logout=1
Use the Query String parameter to populate a hidden field.
Use noty to display the hidden field value when page loads.
Here is a code example:
<?php
if(!empty($_GET['logout'])){
echo '<input id="logoutMsg" value="You have been logged out!" />';
}
?>
<script>
var logoutMsg = $('#logoutMsg').val();
var noty = noty({text: logoutMsg });
</script>
If you want to redirect right after the success message, then use the following code:-
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//display success message
echo "<center>You have successfully logged out!
echo '<meta http-equiv="Refresh" content="0;url=http://url.which.you.want.to.be.redirected.to">';
}
}
?>

Errors for changing variables content depending on session status

I am trying to write a script that changes a veriables content depending on there session status and what ID that was in the URL of the page (e.g www.example.com/profile.php?id=1) so it would display one set of content if they arnt logged in and viewing someone elses profile, another if there logged in and on there own profile, and another if there logged in and viewing someone elses profile.
Firstly the script gets the ID from the url:
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
Then it runs some other code i wont include, then this code:
// ------- DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If session is set and ID matches the profiles ID
$content = ""Your viewing your own profile";
} else if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION is set, but ID dosent match profiles ID
$follow_option = "Your viewing someone elses profile";
} else {
$content = "Your are not logged in";
}
// ------- END DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
print $content;
Now to my problem, all it does is display the option for being logged in and viewing someone elses profile "Your viewing someone elses profile". If you see any errors that would lead to this, please answer below. Thanks! :)
It seams your variables don't hold the expected values when the $logOptions_id != $id runs, or you either forget to start the session. I don't see reference where $logOptions_id gets assigned. Use your IDE tool to debug the code.

Categories