Here's what the situation is: I am trying to use PHP to call scanimage on a Linux host, then save the resulting file to a web directory for future use.
The below code produces no errors, but when I check out the /tmp directory, file.pnm is blank, and the scanner never starts.
<?php
require('/var/www/olin/includes/functions.php');
$con = connect_db();
//setup the POST variables
if (isset($_POST['submit'])) {
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$license_no = mysqli_real_escape_string($con, $_POST['license_no']);
$comments = mysqli_real_escape_string($con, $_POST['comments']);
}
if ($license_no == '') {
$license_no = "None on File";
}
if ($fname == '' || $lname == '') {
echo '<h1 class="message">Can\'t submit visitor: you are missing information!</h1>';
} else {
//setup the query and prepare it for exection
$query= "insert into visitors (fname, lname, license_no, redsheet, comments)" .
" values (?, ?, ?, 'Allow', ?) on duplicate key update fname = values(fname)," .
"lname = values(lname), license_no = values(license_no), redsheet = values(redsheet)," .
"comments = values(comments)";
$stmnt= mysqli_prepare($con, $query);
//bind the statement parameters to variables
mysqli_stmt_bind_param($stmnt, "ssss", $fname, $lname, $license_no, $comments );
//execute, then close the statment
if (!mysqli_stmt_execute($stmnt)) {
echo "Failed to ececute the query: " . mysqli_error($con);
header('Refresh: 10; url=http://localhost/olin/visitor.php');
}
}
// we'll `try` to scan the license if the checkbox is selected
if (isset($_POST['pic_id'])) {
// get the info from the db
$query = 'select id from visitors where license_no = "'.$license_no.'"';
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
// set up the path to save the id to (and put path into db for further look up
// and display)
$dir = ( $id % 30 );
$path = '/var/www/olin/images/licenses/'.$dir.'/'.$id.'-license.png';
$path = addslashes(mysqli_real_escape_string($con, $path));
$path1 = '/images/licenses/'.$dir.'/'.$id.'-license.png';
// start the scan, and save image
$command = '/home/jmd9qs/bin/scan.sh "'.$path.'"';
$update = 'update visitors set id_pic = "'.$path1.'" where id="'.$id.'"';
mysqli_query($con, $update) or die ('Error: ' . mysqli_error($con));
exec($command);
header('Location: http://localhost/olin/visitor.php');
}
}
?>
Can anybody provide any hints?
UPDATE:
I have the server running the command now (I know it's failing because of the Apache2 error log).
Here's the error I get:
scanimage: open of device brother3:bus2;dev1 failed: Invalid argument
I've tried adding the www-data user to the scanner and lp groups, but it seems to have no effect... The scanimage command I'm using works under my normal user and as root, so I'm now positive the command I'm using should work. I am still at a loss...
UPDATE (again):
I've fixed some errors in my code... now the server will scan and successfully save images! However, it only works once and then for some odd reason I have to run the scan.sh (which I put the scanimage command into) through my shell for it to run again... otherwise I get the same error message!
Very weird, I have NO clue why, suggestions wanted!
Related
Can someone point the fault in this code? I'm unable to update data to the database. We are sending a text message to the server, and this file here decodes and sets it in the database. But this case over here is not working for some reason. I checked and tried to troubleshoot, but couldn't find a problem.
case 23:
// Gather Variables
$Message = preg_replace("/\s+/","%20", $Message);
$UnixTime = time();
$cycle = explode(":", $Message);
$machine_press = $cycle[0];
$machine_pct_full = $machine_press/20;
$machine_cycles_return = $cycle[1];
$machine_cycles_total = $cycle[2];
// Build SQL Statement to update static values in the machine table
$sql = "UPDATE `machines` SET `machine_last_run`=".$UnixTime.",`machine_press`=".$machine_press.",`machine_pct_full`=".$machine_pct_full.",`machine_cycles_return`=".$machine_cycles_return.",`machine_cycles_total`=".$machine_cycles_total." WHERE `machine_serial`='$MachSerial'";
// Performs the $sql query on the server to update the values
if ($conn->query($sql) === TRUE) {
// echo 'Entry saved successfully<br>';
} else {
echo 'Error: '. $conn->error;
}
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . "VALUES ($SeqNum,$UnixTime,'$siteDID','$MachSerial',$machine_press,$machine_cycles_total,$machine_cycles_return,$machine_pct_full)";
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
// echo 'Entry saved successfully<br>';
} else {
echo 'Error: '. $conn->error;
}
break;
More information is required to help you out with your issue.
First, to display errors, edit the index.php file in your Codeigniter
project, update where it says
define('ENVIRONMENT', 'production');
to
define('ENVIRONMENT', 'development');
Then you'll see exactly what the problem is. That way you can provide the information needed to help you.
I just saw that you are inserting strings when not wrapping them in apostrophe '. So you queries should be:
$sql = "UPDATE `machines` SET `machine_last_run`='".$UnixTime."',`machine_press`='".$machine_press."',`machine_pct_full`='".$machine_pct_full."',`machine_cycles_return`='".$machine_cycles_return."',`machine_cycles_total`='".$machine_cycles_total."' WHERE `machine_serial`='$MachSerial'";
and
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . " VALUES ('$SeqNum','$UnixTime','$siteDID','$MachSerial','$machine_press','$machine_cycles_total','$machine_cycles_return','$machine_pct_full')";
For any type of unknown problems I can recommend turning on PHP and SQL errors and use a tool called postman that i use to test my apis. You can mimic requests with any method, headers and parameters and send an "sms" just like your provider or whatever does to your API. You can then see the errors your application throws.
EDIT
I tested your script using a fixed version with ' and db.
$Message = "value1:value2:value3";
$MachSerial = "someSerial";
$SeqNum = "someSeqNo";
$siteDID = "someDID";
$pdo = new PDO('mysql:host=someHost;dbname=someDb', 'someUser', 'somePass');
// Gather Variables
$Message = preg_replace("/\s+/","%20", $Message);
$UnixTime = time();
$cycle = explode(":", $Message);
$machine_press = $cycle[0];
$machine_pct_full = (int)$machine_press/20; // <----- Note the casting to int. Else a warning is thrown.
$machine_cycles_return = $cycle[1];
$machine_cycles_total = $cycle[2];
// Build SQL Statement to update static values in the machine table
$sql = "UPDATE `machines` SET `machine_last_run`='$UnixTime',`machine_press`='$machine_press',`machine_pct_full`='$machine_pct_full',`machine_cycles_return`='$machine_cycles_return',`machine_cycles_total`='$machine_cycles_total' WHERE `machine_serial`='$MachSerial'";
try {
$pdo->query($sql);
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . "VALUES ('$SeqNum','$UnixTime','$siteDID','$MachSerial','$machine_press','$machine_cycles_total','$machine_cycles_return','$machine_pct_full')";
try {
$pdo->query($sql);
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
It totally works. Got every cycle inserted and machines updated. Before i fixed it by adding wrapping ' i got plenty of errors.
Alright so this is the solution:
i replaced the line:
$Message = preg_replace("/\s+/","%20", $Message);
with:
$Message = preg_replace("/\s+/","", $Message);
This removes all blank spaces in my text message and makes it a single string before breaking and assigning it to different tables in the database.
I understand this wasnt really a problem with the script and no one around would have known the actual problem before answering. and thats why i am posting the solution just to update the team involved here.
I've hired Cloudatcost, and I've configured an Ubuntu server, installed LAMP and uploaded my web page.
I have a section where I upload some text fields and an an image, the problem is that the image is not being uploaded, but when I run my page locally it works.
My insert code goes like this:
function insert($title, $intro, $body, $data ,$date, $someid, $Myimage, $somesection){
$ID = null;
$mysqli = openConnection(); <- starts connection
$query = "INSERT INTO columnsa (title, intro, body, data, date, someid) VALUES (?, ?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($query))
{
$stmt->bind_param(
'sssssi', $title, $intro, $body, $data, $date, $someid);
/* Execution*/
$stmt->execute();
$ID = $mysqli->insert_id;
/* Close query */
$stmt->close();
}
if($ID)
{
if ($image != null) {
insertImg($image, $ID, $section);
closeConnection($mysqli);
return true;
}
}
else
{
closeConnection($mysqli);
return false;
}
}
And my Insert image is:
function insertImg($image, $ID, $section)
{
switch ($seccion) {
case "journey":
move_uploaded_file($imagen['tmp_name'], "../../img/journeys/".$ID.".jpg");
break;
case "column":
move_uploaded_file($imagen['tmp_name'], "../../img/bolumns/".$ID.".jpg");
break;
case "blog":
move_uploaded_file($imagen['tmp_name'], "../../img/blogs/".$ID.".jpg");
break;
}
}
I'm guessing that maybe I forget to install an php5 module, because the lines
$ID = $mysqli->insert_id;
/* Close query */
$stmt->close();
}
if($ID)
{
if ($image != null) {
insertImg($image, $ID, $section);
closeConnection($mysqli);
return true;
}
}
else
{
closeConnection($mysqli);
return false;
}
Don't seem to work. Any Idea which php5 module includes insert_id?
Thanks!
1.Check if the row inserted to the database. if it didn't insert, you did something wrong. like wrong query (for example field name or,...) or connecting problem. if you have not database problem go to #2.
2.check if your folder that you are trying to upload has proper permission by:
ls -l
if it has not proper permission. read this:
https://help.ubuntu.com/community/FilePermissions
3.If it has no problem with database and permission, it means you are trying to insert to the wrong folder. try it with dirname(__FILE__). it will get your current file directory. for example, change this line:
move_uploaded_file($imagen['tmp_name'], "../../img/journeys/".$ID.".jpg");
to the
move_uploaded_file($imagen['tmp_name'], dirname(__FILE__)."/../../img/journeys/".$ID.".jpg");
For Checking Log
go to this file
sudo nano /var/log/apache2/error.log
if you couldn't find log file there, go to this file to find where is your log file:
sudo nano /etc/php_version/apache2/php.ini
*replace php_version with proper folder
In order to retrieve the Last inserted ID as per the Question you have made you have made is is compulsory that you have run the
Executed Statement
Queried Statement
after Insertion in-order to get the last inserted ID in mysqli.* or in PDO top.
In your code you have to change of how to get the last inserted ID since you have not run the query after Execution.
Replace:
$ID = $mysqli->insert_id;
With:
$ID = $stmt->insert_id;
Note: Since you have executed the query using $stmt alone and not with the $mysqli you need to change it to as i have mentioned.
Below are the Example of how to get the last inserted ID based on Mysqli and PDO
Scenario 1: (Mysqli)
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
Here you have run the query after the query is being executed.
Scenario 2: (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I've solved it by assigning the proper permissions.
As this questions says
Make sure all files are owned by the Apache group and user. In Ubuntu it is the www-data group and user
chown -R www-data:www-data /path/to/webserver/www
Next enabled all members of the www-data group to read and write files
chmod -R g+rw /path/to/webserver/www
I gave read and write permissions to my Images folder outside my web page's folder (due to good security practices).
Here's the PHP code:
<?php
$servername = "***";
$username = "*****";
$password = "*****";
$database = "*****";
try {
$conn = new PDO('mysql:host='.$servername.';dbname='.$database, $username, $password);
console.log('yes!');
}
catch(PDOException $e) {
print "Error!:" . $e->getMessage(). "<br/>";
die();
}
if (isset($_POST['submit']))
{
//$name = $_POST['name'];
//$day = $_POST['day'];
//$acctName = $_POST['acctName'];
//$acctType = $_POST['acctType'];
//$location = $_POST['location'];
//$prospect = $_POST['prospect'];
//$notes = $_POST['notes'];
$name = 'sally sue';
$day = 'monday';
$acctName = 'Account Uno';
$acctType = 'Cold Call';
$location = 'Location';
$prospect = 'Prospect';
$notes = 'These are notes! Notey notey notes';
$order = "INSERT INTO `schedule`(`id`, `name`, `day`, `acctName`, `acctType`, `location`, `prospect`, `notes`) VALUES ('$name', '$day', '$acctName', '$acctType', '$location', '$prospect', '$notes')";
$stmt = $conn->prepare($order);
$stmt->execute();
}
?>
Here's the deal. I have an HTML form that I use jQuery to grab the variables, and AJAX to post the form to this PHP file. I feel confident that everything is fine up to the point where it gets to the PHP file.
I commented out the POST variables and hard-coded my own to make it a little simpler. I'm not getting a 500 Internal Server Error. I've ran my code through a PHP syntax validator (and fixed a billion errors haha). Obviously I'm still doing something wrong, but I cannot find it for the life of me. I'm hoping that someone here has some insight?
EDIT: Also, the username, password, database, and table name are ALL correct. I've double checked them several times. The only thing I'm not sure of is the server name, which is 'localhost' since the DB is on the same server as this web page.
EDIT 2: I've changed the MySql insert statement back to the original, which had the back ticks. I copied it straight from phpMyAdmin console on the server which it resides. It was that way originally, but I changed it due to desperation. It still is not updating my database. Any further ideas?
Thanks in advance!
I'm very new to MySQL. I'm trying to create a php script which reads data from a html form and stores it into the database. I'm also uploading an image whose path is saved in database and the image itself is stored in c:wamp/www/uploads. Now when I'm running the script on my wamp server after submission of my form I'm getting a blank page. When i check my uploads folder, it's still empty. So image isn't put into the folder. Can anyone debug it?
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'userdatadelta');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$table= "CREATE TABLE `users`
( `rollno` int(15) NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`imageid` varchar(50) NOT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `username` (`email`))";
mysqli_query($db,$table);
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$roll_number = $_POST["rollno"];
$department = $_POST["department"];
$year = $_POST["year"];
$email = $_POST["email"];
$password = $_POST["password"];
$filename=$_FILES['userpic']['name'];
$filetype=$_FILES['userpic']['type'];
$name = mysqli_real_escape_string($db, $name);
$roll_number = mysqli_real_escape_string($db, $roll_number);
$department = mysqli_real_escape_string($db, $department);
$year = mysqli_real_escape_string($db, $year);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$newfilename= $roll_number;
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
move_uploaded_file($_FILES['file']['tmp_name'],'upload/'.$newfilename);
$filepath="upload/".$newfilename;
}
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
echo "An account has been created with this email ID already. We regret the inconvenience";
}
else
{
$query = mysqli_query($db, "INSERT INTO users (name, rollno, department, year, email, password, imagepath)VALUES ( '$name','$roll_number', $department, $year,'$email', '$password', '$filepath')");
if($query)
{
echo "Thank You! You have completed registration and are now registered.";
}
}
}
?>
Edited code which works for the most part but for the insertion of data :(. The 2 comments "An account has been created with this email ID already. We regret the inconvenience" and "Thank You! You have completed registration and are now registered." don't seem to work.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$DB_SERVER="localhost";
$DB_USERNAME="root";
$DB_PASSWORD="";
$DB_DATABASE="userdatadelta";
$db = mysqli_connect( "$DB_SERVER" ,"$DB_USERNAME","$DB_PASSWORD","$DB_DATABASE")or die("Cannot connect");
echo "Got connected?";
if(isset($_POST["submit"]))
{
echo "Got inside isset!";
$name = $_POST["name"];
$roll_number = $_POST["rollno"];
$department = $_POST["department"];
$year = $_POST["year"];
$email = $_POST["email"];
$password = $_POST["password"];
$filename=$_FILES['userpic']['name'];
$filetype=$_FILES['userpic']['type'];
$name = mysqli_real_escape_string($db, $name);
$roll_number = mysqli_real_escape_string($db, $roll_number);
$department = mysqli_real_escape_string($db, $department);
$year = mysqli_real_escape_string($db, $year);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$newfilename= $roll_number;
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
echo "Got inside file type checking!";
move_uploaded_file($_FILES['userpic']['tmp_name'],'upload/'.$newfilename);
$filepath="upload/".$newfilename;
}
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
echo "An account has been created with this email ID already. We regret the inconvenience";
}
else
{
$query = mysqli_query($db, "INSERT INTO users (name, rollno, department, year, email, password, imagepath)VALUES ( '$name','$roll_number', $department, $year,'$email', '$password', '$filepath')");
echo "Got inside else!";
if($query)
{
echo "Thank You! You have completed registration and are now registered.";
}
}
}
echo "Comment!";
?>
With such a long code snippet its hard to determine possible errors, as the blank page can be caused from many reasons.
Some of the typical problems that could be related to your code:
a PHP syntax error like an extra or missing brace ( { or } ), for example. The piece you posted seems to be ok, but you dont't tell which PHP version are you using.
a denied write permission to upload path. Either because permissions are wrong, or the path is incorrect. You don't specify your operating system, but it's assumed to be Windows. Some systems use case insensitive paths, other case sensitive, check that for the version and configuration of your current system.
for blank page issue, even when no errors would be raised, there is a sequence of execution in which neither one of the two echo calls are being triggered.
Tipically, PHP will not output any errors to the users as in a production environment it may represent a security risk.
In your development environment you can enable error output to quickly address what is going wrong.
Add the following lines just right after the first opening <?php clause:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Now all the errors for what PHP is complaining should be outputted to the browser.
Be aware, this is not considered a good practice specially in production environments. Errors should be looked up on log files. Use it for helping yourself debugging and solving your current problem in develpment time. If you are working on a large project consider getting the help of a PHP framework to enhance your coding experience.
I'm trying to use unlink to delete pictures from deleted comments but it's simply not working. The comment from the database gets deleted but the actual picture doesn't. What am I doing wrong? The folder permissions are 755 and the image permissions are 644.
if (loggedin()) {
$dblink = mysqli_connect($DBhostname, $DBusername, $DBpassword, $DBname);
if (!$dblink) {die("Connection error (".mysqli_connect_errno.") " . mysqli_connect_error());}
$commentid = mysqli_real_escape_string($dblink, $_GET['c']);
$qry = "SELECT * FROM comments WHERE id='$commentid' LIMIT 1";
$result = mysqli_query($dblink, $qry) or die(mysqli_error($dblink));
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$commenter = $row["commenter"];
$thereisimg = $row["thereisimg"];
$imgtype = $row["imgtype"];
// if logged in email = email of commenter
if ($_SESSION["logged-in"] == $commenter) {
// delete comment
$qry = "DELETE FROM comments WHERE id=$commentid";
$result = mysqli_query($dblink, $qry) or die(mysqli_error($dblink));
// if image, delete image
if ($thereisimg) {
// delete image
$imglink = "/imgs/commentpics/".$commentid.".".$imgtype;
echo $imglink;
unlink($imglink);
}
}
}
}
To diagnose, try one of the following:
Add an error handler to the PHP code to capture the error
Use strace to trace the process and get the exact result of the unlink() system call
Here's a document for (1): http://www.w3schools.com/php/php_error.asp.
To do 2:
strace -e unlink php myScript.php
That assumes the script can be run directly from the command line.
Setting an Error Handler
<?php
function my_error_handler($error_level,$error_message,
$error_file,$error_line,$error_context)
{
echo $error_message;
}
set_error_handler("my_error_handler");