Delete image into directory and database (Small admin area) - php

I have a small script base where you can take shots from the computer's webcam, which are saved in a directory images / and in the database.
Everything works, but now I would like to create an admin area (of course I care for the moment only the functionality), with a hypothetical page admin.php and delete.php (containing the function). I therefore want to appear on the page admin.php list of all the images and the ability to delete them from a simple "delete" button.
Unfortunately I tried several times, but I'm not an expert.
What do you need to help me?
You paste a few pages:
INDEX.PHP
<style type="text/css">
body{
margin:0;
padding:0;
}
.img
{ background:#ffffff;
padding:12px;
border:1px solid #999999; }
.shiva{
-moz-user-select: none;
background: #2A49A5;
border: 1px solid #082783;
box-shadow: 0 1px #4C6BC7 inset;
color: white;
padding: 3px 5px;
text-decoration: none;
text-shadow: 0 -1px 0 #082783;
font: 12px Verdana, sans-serif;}
</style>
<html>
<body style="background-color:#dfe3ee;">
<div id="outer" style="margin:0px; width:100%; height:90px;background-color:#3B5998;">
</div>
<div id="main" style="height:800px; width:100%">
<div id="content" style="float:left; width:500px; margin-left:50px; margin-top:20px;" align="center">
<script type="text/javascript" src="webcam.js"></script>
<script language="JavaScript">
document.write( webcam.get_html(440, 240) );
</script>
<form>
<br />
<input type=button value="Configure settings" onClick="webcam.configure()" class="shiva">
<input type=button value="snap" onClick="take_snapshot()" class="shiva">
</form>
</div>
<script type="text/javascript">
webcam.set_api_url( 'handleimage.php' );
webcam.set_quality( 90 ); // JPEG quality (1 - 100)
webcam.set_shutter_sound( true ); // play shutter click sound
webcam.set_hook( 'onComplete', 'my_completion_handler' );
function take_snapshot(){
// take snapshot and upload to server
document.getElementById('img').innerHTML = '<h1>Uploading...</h1>';
webcam.snap();
}
function my_completion_handler(msg) {
// extract URL out of PHP output
if (msg.match(/(http\:\/\/\S+)/)) {
// show JPEG image in page
document.getElementById('img').innerHTML ='<h3>Upload Successfuly done</h3>'+msg;
document.getElementById('img').innerHTML ="<img src="+msg+" class=\"img\">";
// reset camera for another shot
webcam.reset();
}
else {alert("Error occured we are trying to fix now: " + msg); }
}
</script>
<div id="img" style=" height:500px; width:500px; float:left; margin-left:40px; margin-top:20px;">
</div>
</div>
</body>
</html>
HANDLEIMAGE.php
<?php
session_start();
$_SESSION['id']="1";
$id=$_SESSION['id'];
include 'config.php'; //assume you have connected to database already.
$name = date('YmdHis');
$newname="images/".$name.".jpg";
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "Error occured here";
exit();
}
else
{
$sql="INSERT INTO image VALUES ('','$name','$newname')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
These are the main pages, then there is no config.php file and webcam.js and webcam.swf

You have to write the mysql delete query for the remove the image path from database and the use unlink('file path') funcation to remove the image from the folder.
You want any other help replay on this.

Related

PHP MySQL - Images uploaded to mysql doesnt show up on php

Im trying to create a way to upload images to a page but when i load the page i get the following result: Result
Why arent the images showing up? im cofused.
I have been hours trying to find the solution but i end up in the same place.
Code:
<?php
// Create database connection
include ('config.php');
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['IMG_Link']['IMG_Name'];
// Get text
$image_text = mysqli_real_escape_string($link, $_POST['IMG_Name']);
// image file directory
$target = "GenFeed/".basename($image);
$sql = "INSERT INTO GenFeed (IMG_Link, IMG_Name) VALUES ('$image', '$image_text')";
// execute query
mysqli_query($link, $sql);
if (move_uploaded_file($_FILES['IMG_Link']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($link, "SELECT * FROM GenFeed");
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='GenFeed/".$row['IMG_Link']."' >";
echo "<p>".$row['IMG_Name']."</p>";
echo "</div>";
}
?>
<form method="POST" action="ImageUpload.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="IMG_Link">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="IMG_Name"
placeholder="Say something about this image..."></textarea>
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>
Hope you guys can help me out on this one
PD: im aware the im using superglobal variables

Webcam js integration on Codeigniter

I tried to research and read a lot of articles regarding this problem
I have red some but the discussion seems to end without the solution yet
So the problem is I cannot get to show the camera on my CI app, but when I just copy the exact codes and paste it in my localhost without using any frame work it works.
Here is my CI code
<script type="text/javascript" src="<?=base_url('assets/js/cam/webcam.js')?>"></script>
<script language="JavaScript">
document.write( webcam.get_html(440, 240) );
</script>
<form>
<br />
<input type=button value="Configure settings" onClick="webcam.configure()" class="shiva">
<input type=button value="snap" onClick="take_snapshot()" class="shiva">
</form>
<script type="text/javascript">
webcam.set_api_url( "<?=base_url('assets/js/cam/handleimage.php')?>");
webcam.set_quality( 90 ); // JPEG quality (1 - 100)
webcam.set_shutter_sound( true, "<?=base_url('assets/js/cam/shutter.mp3')?>" ); // play shutter click sound
webcam.set_hook( 'onComplete', 'my_completion_handler' );
function take_snapshot(){
// take snapshot and upload to server
document.getElementById('img').innerHTML = '<h1>Uploading...</h1>';
webcam.snap();
}
function my_completion_handler(msg) {
// extract URL out of PHP output
if (msg.match(/(http\:\/\/\S+)/)) {
// show JPEG image in page
document.getElementById('img').innerHTML ='<h3>Upload Successfuly done</h3>'+msg;
document.getElementById('img').innerHTML ="<img src="+msg+" class=\"img\">";
// reset camera for another shot
webcam.reset();
}
else {alert("Error occured we are trying to fix now: " + msg); }
}
</script>
I used this demo package and its working well if I just extract it to localhost. https://app.box.com/s/nkhgrj73fvutaj6dfspf
But when I tried to integrate it to CI the camera windows show blank . And when I tried to use webcam js function such as webcam.configure() .. It says the Movie is not loaded yet
Jhunnie
By simply copy paste you cannot implement it on codeigniter. Reason behind the error It says the Movie is not loaded yet is webcam.swf is not loaded. actually that flash file is the important thing behind the webcam functionality.
create new controller application\controllers\camera.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Camera extends CI_Controller {
public function index(){
$this->load->helper('url');
$this->load->view("camera");
}
public function saveImage(){
/*write your own code to save to your database*/
$newname = "some_name.png";
file_put_contents( $newname, file_get_contents('php://input') );
}
}
?>
create new view application\views\camera.php
<style type="text/css">
body {
margin: 0;
padding: 0;
}
.img {
background: #ffffff;
padding: 12px;
border: 1px solid #999999;
}
.shiva {
-moz-user-select: none;
background: #2A49A5;
border: 1px solid #082783;
box-shadow: 0 1px #4C6BC7 inset;
color: white;
padding: 3px 5px;
text-decoration: none;
text-shadow: 0 -1px 0 #082783;
font: 12px Verdana, sans-serif;
}
</style>
<html>
<body style="background-color:#dfe3ee;">
<div id="outer" style="margin:0px; width:100%; height:90px;background-color:#3B5998;">
</div>
<div id="main" style="height:800px; width:100%">
<div id="content" style="float:left; width:500px; margin-left:50px; margin-top:20px;" align="center">
<script type="text/javascript" src="<?php echo base_url();?>assets/js/cam/webcam.js"></script>
<script language="JavaScript">
document.write(webcam.get_html(440, 240));
</script>
<form>
<br />
<input type=button value="Configure settings" onClick="webcam.configure()" class="shiva">
<input type=button value="snap" onClick="take_snapshot()" class="shiva">
</form>
</div>
<script type="text/javascript">
webcam.set_api_url('<?php echo base_url();?>camera/saveImage');
webcam.set_quality(90);
webcam.set_shutter_sound(true);
webcam.set_hook('onComplete', 'my_completion_handler');
function take_snapshot() {
document.getElementById('img').innerHTML = '<h1>Uploading...</h1>';
webcam.snap();
}
function my_completion_handler(msg) {
if (msg.match(/(http\:\/\/\S+)/)) {
document.getElementById('img').innerHTML = '<h3>Upload Successfuly done</h3>' + msg;
document.getElementById('img').innerHTML = "<img src=" + msg + " class=\"img\">";
webcam.reset();
} else {
alert("Error occured we are trying to fix now: " + msg);
}
}
</script>
<div id="img" style=" height:800px; width:500px; float:left; margin-left:40px; margin-top:20px;">
</div>
</div>
</body>
</html>
Now copy webcam.js,shutter.mp3,webcam.swf to assets/js/cam. make 2 small changes in webcam.js
line number 27 : swf_url: 'webcam.swf'
line number 28 : shutter_url: 'shutter.mp3'
change to
line number 27 : swf_url: 'assets/js/cam/webcam.swf'
line number 28 : shutter_url: 'assets/js/cam/shutter.mp3'
From Mr Tintu Answer Added some revisions
By simply copy paste you cannot implement it on codeigniter. Reason behind the error It says the Movie is not loaded yet is webcam.swf is not loaded. actually that flash file is the important thing behind the webcam functionality.
create new controller application\controllers\camera.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Camera extends CI_Controller {
public function index(){
$this->load->helper('url');
$this->load->view("camera");
}
public function saveImage(){
/*write your own code to save to your database*/
$newname = "some_name.png";
file_put_contents( $newname, file_get_contents('php://input') );
}
}
?>
create new view application\views\camera.php
<style type="text/css">
body {
margin: 0;
padding: 0;
}
.img {
background: #ffffff;
padding: 12px;
border: 1px solid #999999;
}
.shiva {
-moz-user-select: none;
background: #2A49A5;
border: 1px solid #082783;
box-shadow: 0 1px #4C6BC7 inset;
color: white;
padding: 3px 5px;
text-decoration: none;
text-shadow: 0 -1px 0 #082783;
font: 12px Verdana, sans-serif;
}
</style>
<html>
<body style="background-color:#dfe3ee;">
<div id="outer" style="margin:0px; width:100%; height:90px;background-color:#3B5998;">
</div>
<div id="main" style="height:800px; width:100%">
<div id="content" style="float:left; width:500px; margin-left:50px; margin-top:20px;" align="center">
<script type="text/javascript" src="<?php echo base_url();?>assets/js/cam/webcam.js"></script>
<script language="JavaScript">
document.write(webcam.get_html(440, 240));
</script>
<form>
<br />
<input type=button value="Configure settings" onClick="webcam.configure()" class="shiva">
<input type=button value="snap" onClick="take_snapshot()" class="shiva">
</form>
</div>
<script type="text/javascript">
webcam.set_api_url('<?php echo base_url();?>camera/saveImage');
webcam.set_quality(90);
webcam.set_shutter_sound(true);
webcam.set_hook('onComplete', 'my_completion_handler');
function take_snapshot() {
document.getElementById('img').innerHTML = '<h1>Uploading...</h1>';
webcam.snap();
}
function my_completion_handler(msg) {
if (msg.match(/(http\:\/\/\S+)/)) {
document.getElementById('img').innerHTML = '<h3>Upload Successfuly done</h3>' + msg;
document.getElementById('img').innerHTML = "<img src=" + msg + " class=\"img\">";
webcam.reset();
} else {
alert("Error occured we are trying to fix now: " + msg);
}
}
</script>
<div id="img" style=" height:800px; width:500px; float:left; margin-left:40px; margin-top:20px;">
</div>
</div>
</body>
</html>
Now copy webcam.js,shutter.mp3,webcam.swf to assets/js/cam. make 2 small changes in webcam.js
line number 27 : swf_url: 'webcam.swf'
line number 28 : shutter_url: 'shutter.mp3'
change to
line number 27 : swf_url: '../assets/js/cam/webcam.swf'
line number 28 : shutter_url: '../assets/js/cam/shutter.mp3'
note: that this Url is important and will differ.. Its better checking the .swf url exstince via google chrome than firefox from my experience.. added '../' to go up one folder for you to be in the root app folder to access assets folder
Cheers
Credits to Mr. Tintu Raju

HTML/CSS Font size

i have a problem
i'm trying to edit a website
it has a scroller (behavior is like a inverted waterfall)
the website shows events (data) already recorded in the database...
i want to change the font size of the scroller, i tried to change all the labels there and nothing.
this is the CSS block
<style type="text/css">
body {
font-family: "Engravers MT", "Engravers MT",sans-serif;
line-height: 1em;
color: #f0edd9;
font-weight:bold;
font-size: 40px;
background-color:#8A0829;
}
pscroller1{
width: 500px;
height: 560px;
font-family: "old republic", "old republic";
font-size:50px;
border: 1px solid black;
padding: 5px;
background: red;
}
</style>
this is the scroller, i didn't do that, it was made by someone else.
<script type="text/javascript">
var pausecontent=new Array()
</script>
<script type="text/javascript">
function pausescroller(content, divId, divClass, delay){
this.content=content //message array content
this.tickerid=divId //ID of ticker div to display information
this.delay=delay //Delay between msg change, in miliseconds.
this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
this.hiddendivpointer=1 //index of message array for hidden div
document.write('<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>')
var scrollerinstance=this
if (window.addEventListener) //run onload in DOM2 browsers
window.addEventListener("load", function(){scrollerinstance.initialize()}, false)
else if (window.attachEvent) //run onload in IE5.5+
window.attachEvent("onload", function(){scrollerinstance.initialize()})
else if (document.getElementById) //if legacy DOM browsers, just start scroller after 0.5 sec
setTimeout(function(){scrollerinstance.initialize()}, 500)
}
here is how it set the message in the scroller
pausescroller.prototype.setmessage=function(){
var scrollerinstance=this
if (this.mouseoverBol==1) //if mouse is currently over scoller, do nothing (pause it)
setTimeout(function(){scrollerinstance.setmessage()}, 100)
else{
var i=this.hiddendivpointer
var ceiling=this.content.length
this.hiddendivpointer=(i+1>ceiling-1)? 0 : i+1
this.hiddendiv.innerHTML=this.content[this.hiddendivpointer]
this.animateup()
}
}
pausescroller.getCSSpadding=function(tickerobj){ //get CSS padding value, if any
if (tickerobj.currentStyle)
return tickerobj.currentStyle["paddingTop"]
else if (window.getComputedStyle) //if DOM2
return window.getComputedStyle(tickerobj, "").getPropertyValue("padding-top")
else
return 0
}
this is the body:
<body>
<!--<div align="center">
<img src="picture1.fw.png" align="absmiddle"/>
</div>
!-->
<div align="LEFT" style="width:1000px ">
<div style="height:570px; width:50%; float:right; background-color:#8A0829">
<?php
require_once('functions.php');
$phparray=events();
for($i=0; $i <count($phparray); $i++ )
{
echo '<script language="JavaScript"> pausecontent['.$i.'] = "'.$phparray[$i].'";</script>';
}
?>
<script type="text/javascript" >
document.writeln("EVENTS")
new pausescroller(pausecontent, "pscroller1", "", 5000)
document.write("<br />")
function refresh(time) {setTimeout("location.reload(true);",time);}
refresh(43200000); </script>
</div>
</div>
<div align="right"> EVENTS</div>
<div align="center" style="height:570px; width:300px; float:LEFT; background- color:#8A0829">
<embed src="video.vob" autostart="true" loop ="true" width="500" height="570" >
</div>
</div>
<div align="center">
<img src="background.jpg" align="absmiddle"/>
</div>
</body>
like you can see in the
new pausescroller(pausecontent, "pscroller1", "", 5000)
document.write("")
the pscroller1 should change the font color and size of the pausecontent but it does only change the style of the font of the data, although the return data of document.write (UNDEFINED) is working fine, it's size, style and color can be changed
pscroller1 is not an html entity. You cannot style it like that.
You can add an ID or a class to the 'pscroller' and style that
a{ <- html entity
.someClass{ <- styling a class
#someID{ <- styling an ID

How to order the options by number of votes

I have just "created" a script that orders the songs by number of votes (see here : http://radiowhisper.com/demo/demo.php), using a tutorial. And now, the problem: Everytime when i refresh the page i see the song names randomized. How can i order them by number of votes? (FOR ALL THE TIME -> NOT TO BE RANDOMIZED).
Info: The song names are writed in "sort-objects" table from PhpMyAdmin.
The tutorial: http://tutorialzine.com/2009/11/jquery-sort-vote/
Files:
demo.php
<?php
// Hiding notices:
error_reporting(E_ALL^E_NOTICE);
// Including file for the DB connection:
define("INCLUDE_CHECK",1);
require 'connect.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Radio Whisper - Top 40</title>
<link rel="stylesheet" type="text/css" href="demo.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="main">
<h1>Radio Whisper - Top 40</h1>
<h2>Ordonati melodiile in functie de preferinte.</h2>
<hr />
<?php
// Checking whether the user has voted today:
$voted=false;
$vcheck=mysql_query(" SELECT 1 FROM sort_votes
WHERE ip='".$_SERVER['REMOTE_ADDR']."'
AND date_submit=CURDATE()");
if(mysql_num_rows($vcheck)==1)
$voted=true;
// If we are not on the data.php?results page:
if(!array_key_exists('results',$_GET))
{
echo '<ul class="sort">';
// Showing the tutorials by random
$res = mysql_query("SELECT * FROM sort_objects ORDER BY RAND()");
while($row=mysql_fetch_assoc($res))
{?>
<li id="li<?php echo $row['id']?>">
<div class="tut">
<div class="tut-img">
<img src="<?php echo $row['img']?>" width="50" height="50" alt="<?php echo $row['title']?>" />
<div class="drag-label"></div>
</div>
<div class="tut-title">
<?php echo $row['title']?>
</div>
<div class="tut-description"><?php echo $row['description']?></div>
<div class="clear"></div>
</div>
</li>
<?php } ?>
</ul>
<div class="button-holder">
<?php if(!$voted):?>Trimite topul<span></span><?php endif;?>
Vezi rezultatele<span></span>
</div>
<?php
}
else require "results.php";
// The above require saves us from having to style another separate page
?>
<!-- The form below is not directly available to the user -->
<form action="?results" id="sform" method="post">
<input name="sortdata" id="sortdata" type="hidden" value="" />
</form>
</body>
</html>
demo.css
body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{
/* A simple page reset */
margin:0px;
padding:0px;
}
body{
color:white;
font-size:13px;
background: url(img/bg.jpg) repeat-x #003951;
font-family:Arial, Helvetica, sans-serif;
text-shadow:2px 2px 5px #333333;
}
.tut-title{
font-size:20px;
font-weight:bold;
}
.tut-description{
color:#DDDDDD;
font-family:Arial,Helvetica,sans-serif;
font-size:17px;
padding-top:5px;
}
.tut-img{
border:0px solid white;
float:right;
margin:0 110px 0 0;
width:50px;
height:50px;
overflow:hidden;
/* CSS3 Box Shadow */
-moz-box-shadow:2px 2px 3px #333333;
-webkit-box-shadow:2px 2px 3px #333333;
box-shadow:2px 2px 3px #333333;
cursor:n-resize;
position:relative;
}
.drag-label{
/* The DRAG label that scrolls into visibility on hover */
background:url(img/label_small.png) no-repeat;
width:71px;
height:25px;
position:relative;
margin-left:25px;
}
a.button{
/* The pretty buttons on the bottom are actually hyperlinks.. */
color:#434343 !important;
display:block;
float:left;
font-size:10px;
font-weight:bold;
height:23px;
margin:10px;
padding:12px 10px 0 12px;
position:relative;
text-shadow:none;
text-transform:uppercase;
/* This is the left part of the button background image */
background:transparent url(img/button_gray_bg.png) no-repeat;
}
a.button:hover{
text-decoration:none !important;
background-position:bottom left;
}
a.button:active{
/* Offsetting the text 1px to the bottom on mouse-click*/
padding-top:13px;
height:22px;
}
a.button span{
/* This span holds the right part of the button backgound */
background:transparent url(img/button_gray_bg.png) no-repeat right top;
height:35px;
position:absolute;
right:-2px;
top:0;
width:10px;
display:block;
}
a.button:hover span{
background-position:bottom right;
}
.button-holder{
padding-left:107px;
}
ul.sort{
/* This UL gets converted to a sortable by jQuery */
font-family:"Myriad Pro",Arial,Helvetica,sans-serif;
font-size:20px;
}
ul.sort li{
margin:25px 50px 25px 0;
height:102px;
list-style:none;
}
.chart{
/* Styling the chart container */
background:#002A3C;
border:1px solid #005A7F;
height:300px;
width:550px;
}
.bar{
/* Each bar in the chart is a div. Colors and width are assigned later */
height:17px;
margin:15px;
overflow:hidden;
padding:15px 10px 10px;
text-shadow:none;
white-space:nowrap;
}
.bar a, .bar a:visited{
color:white;
font-size:12px;
}
.tot-votes{
float:right;
font-size:10px;
font-weight:bold;
position:relative;
right:50px;
text-transform:uppercase;
top:18px;
}
/* General styles for the demo page */
h1{
/* The title of the page */
color:white;
font-family:"MyRiad Pro",Arial,Helvetica,sans-serif;
font-size:38px;
font-weight:normal;
}
h2{
/* The subtitle */
font-family:"MyRiad Pro","Arial Narrow",Arial,Helvetica,sans-serif;
font-size:16px;
font-weight:normal;
letter-spacing:1px;
padding-left:2px;
text-transform:uppercase;
white-space:nowrap;
margin:10px 0 25px;
}
#orig{
/* The link that is positioned above the title */
font-family:"MyRiad Pro",Arial;
font-size:10px;
letter-spacing:1px;
padding-bottom:15px;
text-transform:uppercase;
}
hr{
/* The horizontal ruler */
background-color:#BBBBBB;
border:medium none;
color:#BBBBBB;
height:1px;
margin:30px auto;
width:450px;
}
.clear{
/* The clearfix hack */
clear:both;
}
#main{
/* The main container */
width:600px;
margin:30px auto;
}
a img{
border:none;
}
a, a:visited {
color:#00BBFF;
text-decoration:none;
outline:none;
}
a:hover{
text-decoration:underline;
}
.tutorial-info{
text-align:center;
padding:10px;
}
connect.php
<?php
if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this file directly');
/* Database config */ (Edit: I don't want to see them)
$db_host = '*********';
$db_user = '***********';
$db_pass = '******';
$db_database = '***************';
/* End config */
$link = mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
mysql_select_db($db_database,$link);
mysql_query("SET names UTF8");
?>
results.php
<?php
if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this file directly');
// If the poll has been submitted:
if($_POST['sortdata'])
{
// The data arrives as a comma-separated string,
// so we extract each post ids:
$data=explode(',',str_replace('li','',$_POST['sortdata']));
// Getting the number of objects
list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));
if(count($data)!=$tot_objects) die("Wrong data!");
foreach($data as $k=>$v)
{
// Building the sql query:
$str[]='('.(int)$v.','.($tot_objects-$k).')';
}
$str = 'VALUES'.join(',',$str);
// This will limit voting to once a day per IP:
mysql_query(" INSERT INTO `sort_votes` (ip,date_submit,dt_submit)
VALUES ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW())");
// If the user has not voted before today:
if(mysql_affected_rows($link)==1)
{
mysql_query(' INSERT INTO `sort_objects` (id,votes) '.$str.'
ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
}
}
// Selecting the sample tutorials and ordering
// them by the votes each of them received:
$res = mysql_query("SELECT * FROM sort_objects ORDER BY votes DESC");
$maxVote=0;
$bars=array();
while($row=mysql_fetch_assoc($res))
{
$bars[]=$row;
// Storing the max vote, so we can scale the bars of the chart:
if($row['votes']>$maxVote) $maxVote = $row['votes'];
}
$barstr='';
// The colors of the bars:
$colors=array('#ff9900','#66cc00','#3399cc','#dd0000','#800080');
foreach($bars as $k=>$v)
{
// Buildling the bar string:
$barstr.='
<div class="bar" style="width:'.max((int)(($v['votes']/$maxVote)*450),100).'px;background:'.$colors[$k].'">
'.$v['short'].'
</div>';
}
// The total number of votes cast in the poll:
list($totVotes) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_votes"));
?>
<div class="chart">
<?php echo $barstr?>
</div>
Go Back<span></span>
<div class="tot-votes"><?php echo $totVotes?> votes</div>
script.js
$(document).ready(function(){
// Executed once all the page elements are loaded
// Convert the UL with all the tutorials into a sortable list:
$("ul.sort").sortable({
handle : '.tut-img',
axis:'y',
containment: 'document',
opacity: 0.6
});
// The hover method takes a mouseover and a mouseout function:
$(".tut").hover(
function(){
$(this).find('.drag-label').stop().animate({marginTop:'-25px'},'fast');
},
function(){
$(this).find('.drag-label').stop().animate({marginTop:'0'},'fast');
}
);
// Binding an action to the submitPoll button:
$('#submitPoll').click(function(e){
// We then turn the sortable into a comma-separated string
// and assign it to the sortdata hidden form field:
$('#sortdata').val($('ul.sort').sortable('toArray').join(','));
// After this we submit the form:
$('#sform').submit();
// Preventing the default action triggered by clicking on the link
e.preventDefault();
});
});
So, what's the problem ?!?
Don't want to be rude but instead of just copying and pasting code, you would actually read the code and try to understand it you might see these 2 lines
// Showing the tutorials by random
$res = mysql_query("SELECT * FROM sort_objects ORDER BY RAND()");
Seriously, one of them is a comment on what the next line of code does!
ORDER BY is the part of the query that tells it how to sort the results. ORDER BY RAND() will, not surprisingly, give you randomly sorted results. Instead, you should do ORDER BY votes or whatever the name of the column that contains votes is. ORDER BY votes asc will sort them in ascending order (fewest votes first) and ORDER BY votes desc will sort them in descending order (most votes first).
This assumes that you have votes stored in a single field in your table. If that's not the case (e.g., if you have a table with one record per vote), you'll need to tell us about your database schema.

Can't figure out what's wrong with my PHP code

I have an admin page (admin.php) that I am setting up right now.
When the page is accessed initially, a login box comes up correctly where the user can hit a "Sign In" button.
When they hit the "Sign In" button, the login form gets submitted to a PHP page with this code (I don't have any authenticating going on right now - just starting to get this setup):
<?php
session_start();
$_SESSION['login_success'] = true;
header('Location:http://localhost/mbc/admin');
exit();
?>
Then, I'm expecting that the admin.php page will display the admin form but the page just shows up blank after the redirect. Below is the applicable parts of the admin.php page. Can any of you see what I'm doing wrong here such that the admin form is not displaying after the authentication is done?
<html>
<head>
<title>Welcome Home!</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="layout.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.min.js"></script>
<style>
/* Mask for background, by default is not display */
#mask {
display: none;
background: #000;
position: fixed; left: 0; top: 0;
z-index: 10;
width: 100%; height: 100%;
opacity: 0.8;
z-index: 999;
}
/* You can customize to your needs */
.login-popup{
display:none;
background: #333;
padding: 10px;
border: 2px solid #ddd;
float: left;
font-size: 1.2em;
position: fixed;
top: 50%; left: 50%;
z-index: 99999;
box-shadow: 0px 0px 20px #999; /* CSS3 */
-moz-box-shadow: 0px 0px 20px #999; /* Firefox */
-webkit-box-shadow: 0px 0px 20px #999; /* Safari, Chrome */
border-radius:3px 3px 3px 3px;
-moz-border-radius: 3px; /* Firefox */
-webkit-border-radius: 3px; /* Safari, Chrome */
}
img.btn_close { Position the close button
float: right;
margin: -28px -28px 0 0;
}
fieldset {
border:none;
}
form.signin .textbox label {
display:block;
padding-bottom:7px;
}
form.signin .textbox span {
display:block;
}
form.signin p, form.signin span {
color:#999;
font-size:11px;
line-height:18px;
}
form.signin .textbox input {
background:#666666;
border-bottom:1px solid #333;
border-left:1px solid #000;
border-right:1px solid #333;
border-top:1px solid #000;
color:#fff;
border-radius: 3px 3px 3px 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
font:13px Arial, Helvetica, sans-serif;
padding:6px 6px 4px;
width:200px;
}
form.signin input:-moz-placeholder { color:#bbb; text-shadow:0 0 2px #000; }
form.signin input::-webkit-input-placeholder { color:#bbb; text-shadow:0 0 2px #000; }
.button {
background: -moz-linear-gradient(center top, #f3f3f3, #dddddd);
background: -webkit-gradient(linear, left top, left bottom, from(#f3f3f3), to(#dddddd));
background: -o-linear-gradient(top, #f3f3f3, #dddddd);
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#f3f3f3', EndColorStr='#dddddd');
border-color:#000;
border-width:1px;
border-radius:4px 4px 4px 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
color:#333;
cursor:pointer;
display:inline-block;
padding:6px 6px 4px;
margin-top:10px;
font:12px;
width:214px;
}
.button:hover { background:#ddd; }
</style>
</head>
<body id="page1">
<?php
session_start();
if (isset($_SESSION['login_success'])) {
?>
<!-- Some HTML content should show up here but it isn't... -->
<?php } else { ?>
<!-- Login Dialog -->
<div id="login-box" class="login-popup">
Cancel
<form method="post" class="signin" action="admin_process_login.php">
<fieldset class="textbox">
<label class="username">
<span>Username</span>
<input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
</label>
<label class="password">
<span>Password</span>
<input id="password" name="password" value="" type="password" placeholder="Password">
</label>
<button class="login" type="submit">Sign in</button>
</fieldset>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
//Getting the variable's value from a link
var loginBox = document.getElementById('login-box');
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
// When clicking on the button close or the mask layer the popup closed
$('button.login').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
</script>
<?php } ?>
</body>
</html>
EDIT 2012-02-25 16:54EST
For some strange reason, this (and only this as far as I've tested so far) series of events makes the admin form come up correctly...
* Go to admin.php and click on "Sign In" button
* Go to "test" php page in browser (http://localhost/mbc/test)
Code for the test page:
<html>
<head>
<title>Testing</title>
</head>
<body>
<?php
session_start();
if (isset($_SESSION['login_success'])) { ?>
<H1>Login was a success</H1>
<?php } else { ?>
<H1>Login was a failure - next time it should work</H1>
<?php
$_SESSION['login_success'] = true;
}
?>
</body>
</html>
Go to admin page (http://localhost/mbc/admin) and now the admin form comes up fine.
The problem was actually in the jQuery button click code, specifically the "return false" portion:
// When clicking on the button close or the mask layer the popup closed
$('button.login').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
When I removed that code, the "$_SESSION['login_success'] = true;" occurred fine and the admin form portion came back successfully.
Turns out "return false" has some nasty side effects and should be used carefully. See
http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ for more information on using "return false" correctly.
I don't have access to test it right now, but I think your problem is that it should be:
header('Location: http://localhost/mbc/admin');
Reference: http://php.net/manual/en/function.header.php
Both of the references show that a space after the ":" is needed before the URI.
There is nothing wrong with your code. You are simply expecting start_session() not to work and $_SESSION['login_success'] to be unset. I suggest you either use a php-framework or read a guide about sessions.
here, change like this and the form pops up:
<?php
//session_start(); // if you uncomment print_r will give you 1
if (isset($_SESSION['login_success'])) {
echo '<pre>';
print_r($_SESSION['login_success']);
?>
<!-- Some HTML content should show up here but it isn't... -->
empty statement</pre>

Categories