I have very critical requirements from client. He wants to upload multiple choice questions. The questions to be uploaded may be text contents or it may be images. So there is One input field for question which can be textual or image and the same thing with other 4 options of the questions i. e. textual OR image. Means he may either type a question or simply upload an image file and at the same time; the answers of the same question are options which may be either text or images. Here is very critical issue that multiple file uploads with text data. I do program for the same in core php and it is working fine. I achieved this using base64 encoding. But I want the same code in CodeIgniter format. That is MVC architecture format.
Here is my code in core php.
<?php
$message = "Enter question ";
$this->load->database();
if (isset($_POST['no']) ){
$target_path = "./uploadIMG/";
$target_path = $target_path . basename( $_FILES['que']['name']);
if(move_uploaded_file($_FILES['que']['tmp_name'], $target_path)) {
// echo "The file ". basename( $_FILES['que']['name']).
// $img_file = $target_path.$_FILES["que"]["name"];
$imgData = base64_encode(file_get_contents($target_path));
//$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;
$que = $imgData;
$a = "0";
} else{
$que = $_POST['que'];
$a = "1";
}
$target_path = $target_path . basename( $_FILES['opt1']['name']);
if(move_uploaded_file($_FILES['opt1']['tmp_name'], $target_path)) {
// echo "The file ". basename( $_FILES['opt1']['name']).
$img_file1 = $_FILES["opt1"]["name"];
$imgData1 = base64_encode(file_get_contents($target_path));
//$src1 = 'data: '.mime_content_type($img_file1).';base64,'.$imgData;
$opt1 = $imgData1;
$b = $a . "|"."0";
} else{
$opt1 = $_POST['opt1'];
$b = $a . "|"."1";
}
$target_path = $target_path . basename( $_FILES['opt2']['name']);
if(move_uploaded_file($_FILES['opt2']['tmp_name'], $target_path)) {
//echo "The file ". basename( $_FILES['opt2']['name']).
$img_file2 = $_FILES["opt2"]["name"];
$imgData2 = base64_encode(file_get_contents($target_path));
//$src2 = 'data: '.mime_content_type($img_file2).';base64,'.$imgData;
$opt2 = $imgData2;
$c = $b . "|"."0";
} else{
$opt2 = $_POST['opt2'];
$c = $b . "|"."1";
}
$target_path = $target_path . basename( $_FILES['opt3']['name']);
if(move_uploaded_file($_FILES['opt3']['tmp_name'], $target_path)) {
//echo "The file ". basename( $_FILES['opt3']['name']).
$img_file3 = $_FILES["opt3"]["name"];
$imgData3 = base64_encode(file_get_contents($target_path));
//$src3 = 'data: '.mime_content_type($img_file3).';base64,'.$imgData;
$opt3 = $imgData3;
$d = $c . "|"."0";
} else{
$opt3 = $_POST['opt3'];
$d = $c . "|"."1";
}
$target_path = $target_path . basename( $_FILES['opt4']['name']);
if(move_uploaded_file($_FILES['opt4']['tmp_name'], $target_path)) {
//echo "The file ". basename( $_FILES['opt4']['name']).
$img_file4 = $_FILES["opt4"]["name"];
$imgData4 = base64_encode(file_get_contents($target_path));
//$src4 = 'data: '.mime_content_type($img_file4).';base64,'.$imgData;
$opt4 = $imgData4;
$e = $d . "|"."0";
} else{
$opt4 = $_POST['opt4'];
$e = $d . "|"."1";
}
$no = $_POST['no'];
$ans= $_POST['ans'];
$expl=$_POST['expl'];
//echo " QUESTION DATA " .$que. "<br>";//getcwd()
//echo " Answer DATA " .$opt1. "<br>";//getcwd()
//echo " Answer Format " .$e. "<br>";//getcwd()
$target_path = "/uploads/";
//$target_path = $target_path . basename( $_FILES['file']['name']);
$q_code=$this->session->userdata('question_code');
//echo "No1 " . $no . "";
$query = "INSERT INTO question (question_no, question, option1, option2, option3, option4, answer, explaination, layout,question_code) VALUES ('$no', '$que', '$opt1','$opt2','$opt3','$opt4','$ans','$expl','$e','$q_code')";
$result = mysql_query($query);
//echo "No1 " . $query . "";
//echo "No2 " . $$result . "";
//$msg = "question created Successfully.";
if($result){
//echo "No1 " . $$result . "";
$message = "question created Successfully.";
echo " Question created Successfully. " . $result . "";
}
else
{
$message = "question not created please enter valid question no. ";
echo " Question not created please enter valid question no. " . $result . "";
}
}
}?>
Related
I duplicated a folder full of scripts and edited the contents.
ex: /scripts -> /script-new
When I run a php script from this new file I seem to be having some weird issues.
php -f /scripts-new/pulldata.php
When I do this it seems to be using some variables from the old script that I have changed in the code.
/scripts/pulldata.php
$dbtable = "validclickvc";
/scripts-new/pulldata.php
$dbtable = "valid_click_ads";
Here is the mysql command that I am running
$sql = "INSERT INTO " . $dbtable . " ( COLUMN_NAMES ) " . " VALUES ( COLUMN_VALUES )";
And in my error log:
Error: INSERT IGNORE INTO validclickvc VALUES ( '--' )
What might be causing this?
EDIT:
Here is the whole script if it helps!
<?php
// Set some variables to connect to the FTP
$yesterday = date("Ymd", strtotime( '-1 days' ));
$filename = "vc_report_" . $yesterday . ".csv";
$sourcefile = "/***/" . $filename;
$localfile = "php://output";
$ftpserver = "***";
$ftpusername = "***";
$ftppassword = "***";
// Set some variabled to connect to rhe database
$dbhost = "***";
$dbname = "***";
$dbtable = "valid_click_ads";
$dbusername ="***";
$dbpassword = "***";
$fielddelimiter = ",";
$linedelimiter = "\r\n";
// Try to connect to the ftp server
$conn = ftp_connect($ftpserver) or die("Could not connect");
echo "Connected to FTP. \n";
// Try to login to the ftp server
if (ftp_login($conn, $ftpusername, $ftppassword)) {
echo "Logged in to FTP. \n";
} else {
echo "FTP login unsuccessful. \n";
}
ob_start();
// Try to open download today's report
$file = ftp_get($conn, $localfile, $sourcefile, FTP_BINARY);
if ($file) {
$csvcontent = ob_get_contents();
echo "File read successfully. \n";
} else {
echo "File was not read successfully. \n";
}
// Close the file and the connection to the FTP
ftp_close($conn);
echo "File and connection to the FTP closed. \n";
// Connect to the database
$con = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname);
if (!$con) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
} else {
echo "Connected to database. \n";
}
// Set row counter
$rows = 0;
// Set first
$first = true;
// Separate data by line
$lines = explode(PHP_EOL, $csvcontent);
// Insert lines of data
foreach ($lines as $line) {
if (!$first) {
$linearray = explode($fielddelimiter, $line);
print_r ($linearray);
$source_tag = $linearray[1];
if ( strpos( $source_tag, 'phone' ) !== false ) {
$source = "Smart Phone";
} else if ( strpos( $source_tag, 'desktop' ) !== false ) {
$source = "Desktop";
} else {
$source = "";
}
if ( $linearray[14] == "N/A" ) {
$tq = -1;
} else {
$tq = $linearray[14];
}
$sql = "SELECT affiliate_id, id, campaign_id, group_id, user_id, website_id FROM keywords WHERE affiliate_id = " . $linearray[7];
$result = $con->query($sql);
if ( $row = $result->fetch_assoc() ) {
$keyword_id = $row[ 'id' ];
$group_id = $row[ 'group_id' ];
$campaign_id = $row[ 'campaign_id' ];
$user_id = $row[ 'user_id' ];
$website_id = $row[ 'website_id' ];
} else {
$keyword_id = "";
$group_id = "";
$campaign_id = "";
$user_id = "";
$website_id = "";
}
$sql = "INSERT IGNORE INTO " . $dbtable . " ( market, source, device, searches, impressions, clicks, revenue, tq, website_id, user_id, campaign_id, group_id, affiliate_id, keyword_id ) " . " VALUES ( '" . $linearray[5] . "', " . $source . "', " . $linearray[4] . "', " . $linearray[8] . "', " . $linearray[9] . "', " . $linearray[10] . "', " . $linearray[12] . "', " . $tq . "', " . $website_id . "', " . $user_id . "', " . $campaign_id . "', " . $group_id . "', " . $affiliate_id . "', " . $keyword_id . "' )";
echo $sql;
if ($con->query($sql) === TRUE) {
$rows++;
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
} else {
$first = false;
}
}
$con->close();
echo "Inserted a total of " . $rows . " records.\n"
?>
This is my code
<?php
include "../../../config/config.php";
session_start();
if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
die("Not found");
}
if (isset($_POST['submit-edit'])) {
$title = mysqli_real_escape_string($con, $_POST['title']);
$description = mysqli_real_escape_string($con, $_POST['description']);
$category = mysqli_real_escape_string($con, $_POST['category']);
/* ----------------------- MAIN IMAGE -------------------------- */
$target_dir = "../../../img/find/thumbs-categorii/";
$target_file2 = "" . basename($_FILES["img-edit"]["name"]);
$target_file = $target_dir . basename($_FILES["img-edit"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check file size
if ($_FILES["img-edit"]["size"] > 100000) {
$_SESSION['image-size'] = 1;
exit();
}
//
//Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != NULL) {
$_SESSION['image-format'] = 1;
exit();
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
// exit();
}
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
var_dump($query);
exit();
$result = mysqli_query($con, $query);
// var_dump($query);
// exit();
if ($result) {
$_SESSION['edit_slider'] = 1;
header("Location: /dashboard/");
} else {
//
header("Location: /dashboard/");
}
}
}
?>
I want to keep the current path in database if the input with the image is empty. I don't know why, but my code currently stops at echo "Sorry, there was an error uploading your file."; and changes the path for the image, in my database. If the input is empty I want to keep the current path, because I just want to edit.
You define $uploadOk = 1, but that value never changes. So the following code, will always execute the else part of your condition.
if ($uploadOk == 0) {
} else {
/* Everything in here will be executed */
}
Now look at all of the code that inside of that one conditional block.
The first thing is another condition.
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
// exit();
}
Where you say your code is stopping means that move_uploaded_file failed. This would be expected if the user did not supply a file upload in the request. Because $target_file will be empty, and an empty string is probably not going to be a valid path on your filesystem, plus there's the fact that there was no file upload in the first place even if it were.
Everything else that happens inside that first conditional block then continues to happen anyway, unconditionally (i.e. updating your database even though there was no file uploaded).
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
Try using var_dump to inspect the value of $target_file2 when this happens. It won't be what you expected. We know this because you initialize it as $target_file2 = "" . basename($_FILES["img-edit"]["name"]); above, and there was no file upload. So $_FILES is empty.
var_dump($target_file2);
So the better way to do this is to check if a valid file upload occurs first before attempting to update this value in your database. You probably meant to do this with your $uploadOk variable at the top.
if (isset($_FILES["img-edit"]["tmp_name"])) {
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
} else {
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "'," .
", fk_descopera_first='" . $category .
"' WHERE id=" . $id;
}
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_dir)) {
I have a form where users have the option to upload up to 4 files. They do not have to upload all 4.
If they upload 4 files my script works fine. If they upload less than this I get an error "Notice: Undefined index: extension" on the lines in the filenamefetch section that start
$fileName2 = uniqid() . '.' . $fileData2["extension"]; for each of the empty files.
How can I hide this error message? The rest of the script operates as I would expect.
<?php
require_once("connect_db.php");
$ajax_result = "error";
$employeeid=$_POST['employeeid'];
$file1type=$_POST['file1type'];
$file1date=$_POST['file1date'];
$file2type=$_POST['file2type'];
$file2date=$_POST['file2date'];
$file3type=$_POST['file3type'];
$file3date=$_POST['file3date'];
$file4type=$_POST['file4type'];
$file4date=$_POST['file4date'];
//file data fetch
$fileData1 = pathinfo(basename($_FILES["file1"]["name"]));
$fileName1 = uniqid() . '.' . $fileData1["extension"];
$target_path1 = ("uploads/" . $fileName1);
$fileData2 = pathinfo(basename($_FILES["file2"]["name"]));
$fileName2 = uniqid() . '.' . $fileData2["extension"];
$target_path2 = ("uploads/" . $fileName2);
$fileData3 = pathinfo(basename($_FILES["file3"]["name"]));
$fileName3 = uniqid() . '.' . $fileData3['extension'];
$target_path3 = ("uploads/" . $fileName3);
$fileData4 = pathinfo(basename($_FILES["file4"]["name"]));
$fileName4 = uniqid() . '.' . $fileData4['extension'];
$target_path4 = ("uploads/" . $fileName4);
//image 1
while(file_exists($target_path1))
{
$fileName1 = uniqid() . '.' . $fileData1['extension'];
$target_path1 = ("uploads/" . $fileName1);
}
if (move_uploaded_file($_FILES['file1']['tmp_name'], $target_path1))
{ // The file is in the images/gallery folder. Insert record into database by
$q5="INSERT INTO uploadedfiles (filetype, employeeid, filename, filedate) VALUES('$file1type', '$employeeid','$fileName1', '$file1date')";
$r5 = mysqli_query($dbc, $q5) or die(mysqli_error($dbc));
echo "file 1 uploaded";} else {echo "";}
//image 2
while(file_exists($target_path2))
{
$fileName2 = uniqid() . '.' . $fileData2['extension'];
$target_path2 = ("uploads/" . $fileName2);
}
if (move_uploaded_file($_FILES['file2']['tmp_name'], $target_path3))
{ // The file is in the images/gallery folder. Insert record into database by
$q6="INSERT INTO uploadedfiles (filetype, employeeid, filename, filedate) VALUES('$file2type', '$employeeid','$fileName2', '$file2date')";
$r6 = mysqli_query($dbc, $q6);
echo "";} else {echo "";}
//image 3
while(file_exists($target_path3))
{
$fileName3 = uniqid() . '.' . $fileData3['extension'];
$target_path3 = ("uploads/" . $fileName3);
}
if (move_uploaded_file($_FILES['file3']['tmp_name'], $target_path3))
{ // The file is in the images/gallery folder. Insert record into database by
$q7="INSERT INTO uploadedfiles (filetype, employeeid, filename, filedate) VALUES('$file3type', '$employeeid','$fileName3', '$file3date')";
$r7 = mysqli_query($dbc, $q7);
echo "";} else {echo "";}
//image 4
while(file_exists($target_path4))
{
$fileName4 = uniqid() . '.' . $fileData4['extension'];
$target_path4 = ("uploads/" . $fileName4);
}
if (move_uploaded_file($_FILES['file4']['tmp_name'], $target_path4))
{ // The file is in the images/gallery folder. Insert record into database by
$q8="INSERT INTO uploadedfiles (filetype, employeeid, filename, filedate) VALUES('$file4type', '$employeeid','$fileName4', '$file4date')";
$r8 = mysqli_query($dbc, $q8);
echo "";} else {echo "";}
i have this code for uploading image and storing in database
i want to rename it to a random name first,then upload it and store in database
how should i change my code?
please help me!
here is my PHP code :
$imageFile=$_FILES['image'];
$file_name = $imageFile['name'];
$target_path = "images/news/".$file_name;
if(move_uploaded_file($imageFile['tmp_name'], $target_path)) {
echo "<div id=\"news\">";
echo "Image : "."<br>".$file_name;
echo "<br>";
echo "Successfuly Uploaded!";
echo "<br>";
$newstitle = $_POST['title'];
$newscontent = $_POST['content'];
$newsimage = "images/news/".$file_name;
$sql="insert into news (news_title,news_content,news_image,news_date) values ('$newstitle', '$newscontent','$newsimage',' $newsdate')";
if ($conn->query($sql) === TRUE)
{
echo "Image Stored in DB!</div>";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Try this
Random file name created using $random = md5(uniqid("") . time());
Here is working code that renames your file
$imageFile = $_FILES['image'];
$file_name = $imageFile['name'];
$random = md5(uniqid("") . time());
$target_path = "images/news/" . $random.$file_name;
if (move_uploaded_file($imageFile['tmp_name'], $target_path)) {
echo "<div id=\"news\">";
echo "Image : " . "<br>". $random . $file_name;
echo "<br>";
echo "Successfuly Uploaded!";
echo "<br>";
$newstitle = $_POST['title'];
$newscontent = $_POST['content'];
$newsimage = "images/news/" . $random. $file_name;
$sql = "insert into news (news_title,news_content,news_image,news_date) values ('$newstitle', '$newscontent','$newsimage',' $newsdate')";
if ($conn->query($sql) === TRUE) {
echo "Image Stored in DB!</div>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
feel free to ask ready to help you
I have a PHP script that generates an HTML form for users to upload a file. I save that file on the server using move_uploaded_file then read it using fgets() and perform database inserts based on certain check. Here's a simplified version of the code:
$cart_id = 18566;
if (empty($_POST))
{
echo "<form name=\"upload\" action=\"myscan.php\" id=\"myScan\" method=\"POST\" enctype=\"multipart/form-data\">";
echo "Choose the file to upload:<br>\r\n";
echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"300000\" form=\"myScan\" />";
echo "<input type=\"file\" name=\"file\" form=\"myScan\" id=\"fileUp\" /><br>";
echo "<input type=\"submit\" value=\"Upload\" name=\"sub\" form=\"myScan\" />";
echo "<input type=\"hidden\" name=\"ck\" form=\"myScan\" value=\"".$cart_id."\" />";
echo "</form><br>";
}
else
{
// link to cart goes here
}
$fname = "1SCAN20131031123456";
if (!empty($_POST))
{
$allowedExts = array("txt", "csv");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ( ($_FILES["file"]["type"] == "text/plain"
|| $_FILES["file"]["type"] == "application/vnd.ms-excel")
&& array_search(strtolower($extension), array_map('strtolower', $allowedExts)) !== FALSE )
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"]."<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], $fname);
echo "Moved to: " . $fname . "<br>";
}
}
}
else
{
echo "Invalid file<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Extension: " . $extension . "<br>\n";
}
At this point the file $fname is ok, no duplicated lines. The next part is called as a function declared in the same PHP file. $link, $fname, and $cart_id are declared as globals
$bn = basename($fname);
$sfd = fopen($fname, "r");
$store_number = "$bn[0]";
if(is_numeric($bn[1]))
$store_number .= $bn[1];
$a = stripos($bn, "SCAN");
$a += 4;
$dt = substr($bn, $a);
// echo "Date = $dt \n";
$fy = substr($dt, 0, 4);
$fM = substr($dt, 4, 2);
$fd = substr($dt, 6, 2);
$fh = substr($dt, 8, 2);
$fm = substr($dt, 10, 2);
$fs = substr($dt, 12, 2);
$fdate = "$fy-$fM-$fd $fh:$fm:$fs";
// echo $fname . ",";
// echo $store_number . ",";
while ($line = fgets($sfd))
{
$li = explode(",", $line);
if (sizeof($li) == 5)
{
$scan = $li[0];
$poQty = $li[1];
$cntQty = $li[2];
$limd = $li[3];
$lihms = $li[4];
$query = "INSERT INTO upload_datalog (file_name, store, filedate, scan, po_qty, cnt_qty, scan_md, scan_hms, cart_id)\n"
. "VALUES (\"$bn\", $store_number, \"$fdate\", \"$scan\", $poQty, $cntQty, \"$limd\", \"$lihms\", $cart_id)";
mysqli_query($link, $query);
}
else if ($fM < 8 || ($fM == 8 && $fd < 16 ))
{
$scan = $li[0];
$poQty = $li[2];
$cntQty = $li[1];
$limd = $li[3];
$lihms = $li[4];
$query = "INSERT INTO upload_datalog (file_name, store, filedate, scan, po_qty, cnt_qty, scan_md, scan_hms, cart_id)\n"
. "VALUES (\"$bn\", $store_number, \"$fdate\", \"$scan\", $poQty, $cntQty, \"$limd\", \"$lihms\", $cart_id)";
mysqli_query($link, $query);
}
else if (sizeof($li) == 3 && $li[0] != "" && $li[1] != "" &&$li[2] != "" )
{
$scan = $li[0];
$poQty = $li[2];
$cntQty = $li[1];
$query = "INSERT INTO upload_datalog (file_name, store, filedate, scan, po_qty, cnt_qty)\n"
. "VALUES (\"$bn\", $store_number, \"$fdate\", \"$scan\", $poQty, $cntQty)";
mysqli_query($link, $query);
}
}
fclose($sfd);
The file contains this information:
This all works more than 99 percent of the time, but twice in the past 2 weeks, the entries in the upload_datalog table have been duplicated. There is another function after this that also reads the file and performs inserts based on different checks, and those are duplicated as well.
I know this is an edge case, but I couldn't find any information as to why this would happen on php.net or through google, and I have not been able to reproduce it mysqlf. But I know it occurs in the wild.
Is there a race condition I'm not seeing here?
You do your inserts in a while loop, so you run twice through that loop?
For debugging, add a counter in your loop and create a small debug function, and a debug table. Insert the counter and data in your debug table. Compare these values with your expectations