Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I can't figure out what's causing this error:
Parse error: syntax error, unexpected T_PUBLIC
It says the error is occuring on the second line of this code (public function upload($uid = 'public').
//--> Uploads the file
public function upload($uid = 'public')
{
//Get file details
if(isset($_GET['ajax']))
{
if(!$_SERVER['HTTP_X_FILE_SIZE'] > 0) return false;
$filename = strip_tags($_SERVER['HTTP_X_FILE_NAME']);
$file_type = $_SERVER['HTTP_X_FILE_TYPE'];
$size = round($_SERVER['HTTP_X_FILE_SIZE']/1000, 3);
}
else
{
if($_FILES["files"]["error"] > 0 or empty($_FILES)) return false;
$filename = strip_tags($_FILES['files']['name']);
$file_type = $_FILES['files']['type'];
$size = round($_FILES['files']['size']/1000, 3);
}
//FF null type fix
if( $file_type == null || strlen($file_type) == 0 ) $file_type = "unknown";
//Reduce filename to < 255 char
if(strlen( $filename ) > 255 )
{
$filename = urldecode($filename);
$filename = substr($filename, 0, 36) . '--.' . pathinfo($filename, PATHINFO_EXTENSION);
$filename = urlencode($filename);
}
//Check file size
if($size > (maxFileSize/1000))
{
$this->errorMessage = "file too large";
return false;
}
//Check file type
if( limitFileTypes and !in_array($file_type, explode(',', allowedFileTypes)) )
{
$this->errorMessage = "file type not allowed";
return false;
}
$db = $this->connectDB();
$share = isset($_GET['ajax'])?$_SERVER['HTTP_BITDROPSHARE']:$_POST['bitdrop_share'];
$share = ($share == 'true' || $share == 'share' )? 1 : 0;
$password = isset($_GET['ajax'])?$_SERVER['HTTP_BITDROPPASS']:$_POST['bitdrop_password'];
//Find an available shortURL
$res = $db->prepare("select count(shortURL) from share where binary shortURL = ?;");
do
{
$shortURL = $this->shortURL();
$res->execute(array($shortURL));
$data = $res->fetchAll(PDO::FETCH_COLUMN, 0);
}
while($data[0] != 0);
$password = ( is_null($password) or strlen($password)==0 ) ? 0 : sha1($password . $shortURL) ;
$q = "insert into details (date, name, size, type, public, password) values (now(), ?, ?, ?, ?, ?)";
$data = array($filename, $size, $file_type, $share, $password);
$res = $db->prepare($q);
//exec command or print error
if(!$res->execute($data)) print_r($db->errorInfo());
$fid = $db->lastInsertId();
$q = "insert into share (shortURL, file_id) values (?, ?)";
$data = array($shortURL, $fid);
$res = $db->prepare($q);
$res->execute($data);
//Connect unique user to file
$tid = $this->addTag("_$uid");
$q = "insert into `fid-tid` (file_id, tag_id) values ('$fid', '$tid');";
$res = $db->prepare($q);
$res->execute();
$file = $_SERVER[DOCUMENT_ROOT] . "/uploads/$fid.temp";
$this->log('upload', '{ "uid" : "'.$uid.'", "fid" : "'.$fid.'", "shortURL" : "'.$shortURL.'" }');
$db = null;
//Upload file
if(isset($_GET['ajax']))
{
if(!isset($_SERVER['HTTP_X_FILE_NAME']) && !isset($_SERVER['CONTENT_LENGTH']))
{
$this->errorMessage = "no headers found";
return false;
}
$fileReader = fopen('php://input', "r");
$fileWriter = fopen($file, "w+");
while(true)
{
$buffer = fgets($fileReader, 4096);
if(strlen($buffer) == 0)
{
fclose($fileReader);
fclose($fileWriter);
$this->createThumb($fid, $shortURL);
$this->shortURL = $shortURL;
return true;
}
fwrite($fileWriter, $buffer);
}
}
else
{
move_uploaded_file($_FILES["files"]["tmp_name"], $file);
$this->createThumb($fid, $shortURL);
$this->shortURL = $shortURL;
return true;
}
}
You are defining function public.
The public is a keyword for Object Orieneted Programming.
But, as per your code, there is no class defined, therefore, there is no use public keyword.
Just remove the public keyword.
Corrected code:
function upload($uid = 'public')
Related
This question already has answers here:
How to use mysqli prepared statements?
(3 answers)
Closed 8 months ago.
I want to update existing records in a table using an excel csv import file.
the table name is aflossingen and has the columns: AflossingID, VoorschotID, Aflossingdatum, Aflossingsbedrag, Afgelost, Saldo.
This is the code PHPRad has generated, which can only do an INSERT:
function import_data(){
if(!empty($_FILES['file'])){
$finfo = pathinfo($_FILES['file']['name']);
$ext = strtolower($finfo['extension']);
if(!in_array($ext , array('csv'))){
$this->set_flash_msg("Document formaat niet ondersteund", "danger");
}
else{
$file_path = $_FILES['file']['tmp_name'];
if(!empty($file_path)){
$request = $this->request;
$db = $this->GetModel();
$tablename = $this->tablename;
$options = array('table' => $tablename, 'fields' => '', 'delimiter' => ',', 'quote' => '"');
$data = $db->loadCsvData( $file_path , $options , false );
if($db->getLastError()){
$this->set_flash_msg($db->getLastError(), "danger");
}
else{
$this->set_flash_msg("Data imported successfully", "success");
}
}
else{
$this->set_flash_msg("Error uploading file", "danger");
}
}
}
else{
$this->set_flash_msg("No file selected for upload", "warning");
}
$this->redirect("aflossingen");
}
This is my code. Nothing happens:
function import_data(){
if(isset($_POST["importcsv"])){
$file = $_FILES["csv_file"]["tmp_name"];
$handle = fopen($file,"r");
while ($row = fgetcsv($handle)) {
$id = $row[0];
$Aflossingdatum = $row[2];
$Aflossingsbedrag = $row[3];
$Afgelost = $row[4];
$Saldo = $row[5];
$sql = "UPDATE aflossingen SET Aflossingdatum = Aflossingdatum,Afgelost = Afgelost, Saldo = Saldo WHERE AflossingID = AflossingID";
$update_data_stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($update_data_stmt, $sql)){
die("Something went wrong with the upload. " . mysqli_error($connection));
} else {
mysqli_stmt_bind_param($update_data_stmt, "ss", $Aflossingdatum, $id, $Aflossingsbedrag, $Afgelost, $Saldo);
mysqli_stmt_execute($update_data_stmt);
if ($id == "AflossingID" && $Aflossingdatum == "Aflossingdatum"){
echo "";
} else {
echo "Lead <b>{$id}</b>'s response was updated to <b>{$Aflossingdatum}</b>.</p>";
}
}
}
}
$this->redirect("aflossingen");
}
You're not creating the prepared statement correctly. It needs to have ? placeholders where the variables will be substituted.
And you need to have as many characters in the type string argument to mysqli_stmt_bind_param() as you have variables. And the variables have to be in the same order as in the query, so $id must be last.
You don't need to prepare the statement and bind parameters each time through the loop. Just prepare it once, and bind the parameters to reference variables that will be updated during the loop.
You were missing Aflossingsbedrag from your UPDATE query, I added it back.
Instead of checking whether $id == 'AflossingID' to skip the header row, I simply read the first line of the file before going into the loop that calls fgetcsv(). If you prefer to do it by checking the column value (in case there's no header) you should do it before executing the query, and skip the update (you can use continue; to go to the next iteration of the loop)
function import_data(){
if(isset($_POST["importcsv"])){
$file = $_FILES["csv_file"]["tmp_name"];
$handle = fopen($file,"r");
$sql = "UPDATE aflossingen SET Aflossingdatum = ?, Aflossingsbedrag = ?, Afgelost = ?, Saldo = ? WHERE AflossingID = ?";
$update_data_stmt = mysqli_stmt_init($connection);
mysqli_stmt_bind_param($update_data_stmt, "sssss", $Aflossingdatum, $Aflossingsbedrag, $Afgelost, $Saldo, $id);
if (!mysqli_stmt_prepare($update_data_stmt, $sql)){
die("Something went wrong with the upload. " . mysqli_error($connection));
}
fgets($handle); // Skip header row
while ($row = fgetcsv($handle)) {
$id = $row[0];
$Aflossingdatum = $row[2];
$Aflossingsbedrag = $row[3];
$Afgelost = $row[4];
$Saldo = $row[5];
if (mysqli_stmt_execute($update_data_stmt)) {
echo "Lead <b>{$id}</b>'s response was updated to <b>{$Aflossingdatum}</b>.</p>";
} else {
echo "Something went wrong when updating $id. " . mysqli_stmt_error($update_data_stmt);
}
}
}
}
problem is in my excel 369 rows are there. when I echo/print that data it showing correct but when I am inserting same data in DB table in inserted only 18 - 30 records.
if (isset($_POST['Submit'])) {
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
if ($file == NULL) {
error(_('Please select a file to import'));
redirect(page_link_to('excel_data_upload'));
}else {
$conn = connect();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$num3 = $filesop[3];
$num8 = $filesop[8];
$num9 = $filesop[9];
$num20 = $filesop[20];
if($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO'){
$insertAgent = mysqli_query($conn, "INSERT INTO `upload_billing_data`
(`vc_number`,`stb_number`,`operator_id`,`expiry_date`,`monthly_bill_amount`)
VALUES ('$num8','$num9',140,'$num3','$num20')");
if($insertAgent)
{
echo 'succss';
}else{
echo 'error';
}
}
}
close($conn);
}
}
I am fetching from the excel data. I want to insert all records
Change the code as below and you might get to save all data using one query to the database:
$query_insert = array();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false) {
$num3 = filterString($filesop[3]);
$num8 = filterString($filesop[8]);
$num9 = filterString($filesop[9]);
$num20 = filterString($filesop[20]);
if ($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO') {
$query_insert[] = "('{$num8}', '{$num9}', 140, '{$num3}', '{$num20}')";
}
}
// If no row matched your if, then there will be no row to add to the database
if (count($query_insert)>0) {
$conn = connect();
$query_insert_string = implode(', ', $query_insert);
$query = "INSERT INTO `upload_billing_data` (`vc_number`, `stb_number`, `operator_id`, `expiry_date`, `monthly_bill_amount`) VALUES {$query_insert_string};";
$insertAgent = mysqli_query($query);
// The rest of you code
...
close($conn);
}
// This function makes sure that you string doesn't contain characters that might damage the query
function filterString($string) {
$string = str_replace(array("\'", '"'), array('', ''), $string);
$string = filter_var($string, FILTER_SANITIZE_STRING);
return $string;
}
Please check this modified code
if (isset($_POST['Submit'])) {
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
if ($file == NULL) {
error(_('Please select a file to import'));
redirect(page_link_to('excel_data_upload'));
}else {
$conn = connect();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$num3 = $filesop[3];
$num8 = $filesop[8];
$num9 = $filesop[9];
$num20 = $filesop[20];
if($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO'){
$insertAgent = mysqli_query($conn, "INSERT INTO `upload_billing_data`
(`vc_number`,`stb_number`,`operator_id`,`expiry_date`,`monthly_bill_amount`)
VALUES ('".mysqli_real_escape_string($num8)."','".mysqli_real_escape_string($num9)."',140,'".mysqli_real_escape_string($num3)."','".mysqli_real_escape_string($num20)."')");
if($insertAgent)
{
echo 'succss';
}else{
echo 'error';
}
}
}
close($conn);
}
}
BY using mysqli_real_escape_string() you will be able to avoid sqlinjection issues and you will be able to handle issue of quotes which might be causing an issue.
in your else block where you are echo "error". you can use mysqli_error($conn); to get exact what error is occurring while performing an insert
So I am wanting to allow my members to view a profile via a url such as: mywebsite.com/account/Username
however, at the moment my members can view via the url: mywebsite.com/account?username=username.
This doesn't look profesional and I've tried nearly everything to get it to the url I'm looking to get.
(Please be aware; I'm very new to this website and cannot use it properly, If I have done anything wrong, please notify me and I will justify it.)
The code:
//get config
$config = $base->loadConfig();
full code:
https://pastebin.com/UmAmF9Rt
<?php
require('../includes/config.php');
require('../structure/base.php');
require('../structure/forum.php');
require('../structure/forum.index.php');
require('../structure/forum.thread.php');
require('../structure/forum.post.php');
require('../structure/database.php');
require('../structure/user.php');
$database = new database($db_host, $db_name, $db_user, $db_password);
$base = new base($database);
$user = new user($database);
$forum = new forum($database);
$forum_index = new forum_index($database);
$thread = new thread($database);
$post = new post($database);
$user->updateLastActive();
//get config
$config = $base->loadConfig();
//set some variables that are used a lot throughout the page
if (!empty($_GET['username'])) {
$profile_name = htmlspecialchars($_GET["username"]);
}
else{
$profile_name = $user->getUsername($_COOKIE['user'], 2);
}
$username = $user->getUsername($_COOKIE['user'], 2);
$rank = $user->getRank($username);
$f = $_GET['forum'];
$i = $_GET['id'];
//assign data to details[] array
$details['lock'] = $detail_query[0]['lock'];
$details['sticky'] = $detail_query[0]['sticky'];
$details['title'] = stripslashes(htmlentities($detail_query[0]['title']));
$details['username'] = $detail_query[0]['username'];
$details['status'] = $detail_query[0]['status'];
$details['content'] = $detail_query[0]['content'];
$details['date'] = $detail_query[0]['date'];
$details['lastedit'] = $detail_query[0]['lastedit'];
$details['qfc'] = $detail_query[0]['qfc'];
$details['moved'] = $detail_query[0]['moved'];
$details['hidden'] = $detail_query[0]['hidden'];
$details['autohiding'] = $detail_query[0]['autohiding'];
//get forum details
$forum_details = $database->processQuery("SELECT `title` FROM `forums` WHERE `id` = ?", array($f), true);
if(isset($_GET['username'])){
if($user->doesExist($_GET['username'])){;
}
}else{
if(!$user->isLoggedIn()){
$base->redirect('../login.php');
}else{
$user_s = $username;
}
}
$messages = array();
$avatar = $user->getAvatar($profile_user);
$usr = $user->getUsername($profile_user);
if($username == $profile_user && $user->isLoggedIn() && isset($_REQUEST['cust_title'])) {
$user->setTitle($username, htmlentities($_REQUEST['cust_title']));
}
if($user_s == $username && $user->isLoggedIn() && isset($_FILES['uploaded'])) {
if(isset($_REQUEST['delete'])) {
$user->setAvatar($username, '');
$messages[] = "Your avatar has been removed.";
} else {
$ok = false;
$info = getimagesize($_FILES['uploaded']['tmp_name']);
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
$messages[] = ("Upload failed with error code " . $_FILES['uploaded']['error']);
} else if($info === FALSE) {
$messages[] = ("Unable to determine image type of uploaded file");
} else if(($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
$messages[] = ("Not a gif/jpeg/png");
} else if($_FILES['uploaded']['size'] > 350000) {
$messages[] = "Your file is too large.";
} else if($_FILES['uploaded']['type'] == "text/php") {
$messages[] = "No PHP files";
} else {
$ok = true;
}
$target = md5(strtolower(trim($username))) .'.'. pathinfo($_FILES['uploaded']['name'])['extension'];
if($ok) {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], "../images/avatar/" . $target)){
$messages[] = "Your avatar has been uploaded. Please allow atleast 10 minutes for it to update.";
$user->setAvatar($username, $target);
} else {
$messages[] = "Sorry, there was a problem uploading your file.";
}
}
}
}
//retrieve posts/threads
$posts = $database->processQuery("SELECT `id`,`thread`,`username`,`timestamp`,`content` FROM `posts` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
$threads = $database->processQuery("SELECT `id`,`parent`,`title`,`username`,`timestamp`,`content` FROM `threads` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
//type:id:forum:timestamp:(if post)thread
$list = array();
foreach($posts as $post){
//get the thread's forum/parent
$t = $database->processQuery("SELECT `parent` FROM `threads` WHERE `id` = ? LIMIT 1", array($post['thread']), true);
$list[$post['timestamp']] = 'p:'.$post['id'].':'. $t[0]['parent'] .':'.$post['timestamp'].':'.$post['thread'].':'.$post['content'];
}
//add threads
foreach($threads as $thread){
$list[$thread['timestamp']] = 't:'.$thread['id'].':'.$thread['parent'].':'.$thread['timestamp'].':'.$thread['content'];
}
//now sort them
krsort($list, SORT_NUMERIC);
$r = $database->processQuery("SELECT * FROM `users` WHERE `username` = ?", array($profile_name), true);
?>
Your best bet is to use:
.htaccess route with mod_rewrite
Try Adding a file called .htaccess in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /account.php?username=$username
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want:
Refer to this answer by Niels Keurentjes: https://stackoverflow.com/a/16389034/3367509
If you are new to .htaccess look up this question: What is .htaccess file?
I try to read every word after this word #EXTINF:-1
and the next line from the local file and subsequently add the result to MySQL if it does not exist.
The contents of the file looks like this:
#EXTM3U
#EXTINF:-1,name1
http://www.name1
#EXTINF:-1,name2
http://www.name2
#EXTINF:-1,name3
http://www.name3
#EXTINF:-1,name4
http://www.name4
And my code:
$file = file("file.m3u);
array_shift($file);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$getname[] = substr($row, $pos + 1);
} else {
$geturl[] = $row;
} } }
$count = count($getname);
for($i=0; $i < $count; $i++){
$name = $getname[$i];
$url = $geturl[$i];
if (empty($name)) { exit; };
if (empty($url)) { exit; }
$get_user = mysql_query("select * from users where (name = '$name')");
$show_user = mysql_fetch_array($get_user);
$userid = $show_user['userid'];
$get_url = mysql_query("select * from urls where url = '$url'");
$show_url = mysql_fetch_array($get_url);
$urlid = $show_url['urlid'];
if (empty($userid) && empty($urlid)) {
$add_user = "INSERT INTO users(name)
VALUES('$name')";
mysql_query($add_user);
$userid = mysql_insert_id();
$add_url = "INSERT INTO urls(userid, url)
VALUES('$userid', '$url')";
mysql_query($add_url);
$urlid = mysql_insert_id();
}
}
My code cannot read file correctly, because when I try check the line that I had read from file, it does not work.
The info that I try to read:
name = name1
url = http://www.name1
is for every user.
This might have something to do with it
$file = file("file.m3u);
It should be
$file = file("file.m3u");
This is my edit page update script. I have a problem. On each update, script updates image name and inserts into MySQL. I would like that system doesn't inserts or updates file name if it is NULL (isset). Here is my code about that:
<?php
require 'aed-config.php';
require 'class.upload.php';
function gen_random_string($length=16)
{
$chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";//length:36
$final_rand='';
for($i=0;$i<$length; $i++)
{
$final_rand .= $chars[ rand(0,strlen($chars)-1)];
}
return $final_rand;
}
$pic_name = gen_random_string();
$image = new Upload( $_FILES[ 'image' ] );
if ( $image->uploaded ) {
$image->file_new_name_body = $pic_name;
$image->image_convert = 'jpg';
$image->image_resize = true;
$image->image_ratio_crop = true;
$image->image_x = 460;
$image->image_y = 300;
$image->Process( '../img' );
$image->allowed = array ( 'image/*' );
}
$pic = $pic_name.'.jpg';
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['memids'];
$sql = "UPDATE about_us
SET title=?, content=?, pic=?
WHERE id=?";
$q = $db->prepare($sql);
$q->execute(array($title,$content,$pic,$id));
header("location: about.php");
?>
You can do that like using an simple if condition
if($pic_name != null AND isset($_FILES['image'])){
$q->execute(array($title,$content,$pic,$id));
}
First dont generate a filename and create an Upload object if you dont need it.
if ($_FILES['image'])
{
// Generate filename and create your Upload object as well as the $pic variable
}
And then the query section..
$executeArray = array($title, $content);
$sql = "UPDATE about_us
SET title = ?, content = ?, ";
if (isset($pic)
{
$executeArray[] = $pic;
$sql .= "pic = ?, ";
}
$sql .= "WHERE id = ?";
$executeArray[] = $id;
$q->execute($executeArray);