PHP How to use variable from one if statement in another? - php

I have a little problem.
I'm making form that submits simple article to database and then displays it on admin.php page.
Everything works fine, except image.
First i upload it to my server and then I try to add string(path of this image) to database.
However I can't use variable $filepath in second if statement.
I can echo it after image upload but can't use in other if.
Could u help me?
Thanks in advance.
Here's code:
<?php session_start();
if (!isset($_SESSION['logged-in']))
{
header('Location: index.php');
exit();
}
?>
<?php
include('db_connect.php');
if(isset($_POST['btn_upload'])) {
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filepath = "photo/".$filename;
move_uploaded_file($filetmp,$filepath);
$result = mysqli_query($mysqli, "INSERT INTO upload_img (img_name,img_path,img_type) VALUES ('$filename','$filepath','$filetype')");
echo '<img src="' . $filepath . '" alt="">';
echo $filepath;
}
if ( isset($_POST['add']) ) {
$title = strip_tags($_POST['title']);
$content = strip_tags($_POST['content']);
$image = strip_tags($filepath);
$statement = $mysqli->prepare("INSERT bikes (title,image,content) VALUES (?,?,?)");
$statement->bind_param("sss",$title,$image,$content);
$statement->execute();
$statement->close();
header('Location: admin.php');
}
?>
<form method="post" action="" class="ui form">
<div class="required field">
<label>Title</label>
<input type="text" name="title" id="title">
</div>
<div class="required field">
<label>Content</label>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
</div>
<div class="required field">
<label>Image</label>
<input type="text" name="image" id="image">
</div>
<input type="submit" class="ui primary button" id="add" name="add" value="Add article"></input>
</form>
<form action="addbike.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img" />
<input type="submit" name="btn_upload" value="Upload">
</form>

Since both of your forms work independently(with co-relation with each other whatsoever), $filepath variable won't be accessible in the second if block. However, what you can do is, merge both of your forms together so that all of your form's textual data and image would be accessible in a single submit button.
HTML:
<form method="post" action="" class="ui form" enctype="multipart/form-data">
<div class="required field">
<label>Title</label>
<input type="text" name="title" id="title">
</div>
<div class="required field">
<label>Content</label>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
</div>
<div class="required field">
<label>Image</label>
<input type="text" name="image" id="image">
</div>
<input type="file" name="file_img" />
<input type="submit" class="ui primary button" id="add" name="add" value="Add article"></input>
</form>
PHP:
if (isset($_POST['add']) && is_uploaded_file($_FILES["file_img"]["tmp_name"])) {
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filepath = "photo/".$filename;
if(move_uploaded_file($filetmp, $filepath)){
$result = mysqli_query($mysqli, "INSERT INTO upload_img (img_name,img_path,img_type) VALUES ('$filename','$filepath','$filetype')");
if($result){
$title = strip_tags($_POST['title']);
$content = strip_tags($_POST['content']);
$image = strip_tags($filepath);
$statement = $mysqli->prepare("INSERT bikes (title,image,content) VALUES (?,?,?)");
$statement->bind_param("sss",$title,$image,$content);
$statement->execute();
$statement->close();
header('Location: admin.php');
exit();
}else{
// error handling
}
}else{
// error handling
}
}

btn_upload is mutually exclusive to add, so the if statement which executes for btn_upload doesn't also run for add.
If you want it to be a two-phase process (upload image, then add) then you have to set a hidden input whose value is the filepath.
However, ideally the user would fill in name and provide an image and then submit them together. In order to do that, place all inputs inside the same form element and remote the "Add" button.

Related

Creating file name for creating a file does not seem to work

When creating and posting just the user note data, I had no issues. Yet when I attempt to allow the user to specify the file name, the code refuses to run.
Is there another method of approaching this problem or is my syntax off?
HTML:
<form method="post">
<div>
<div style="margin-right 5px">
<input type="text" name="noteData" id="notes" size="250">
<input type="Submit" name="Submit" class="txtNote_But" value="Save Text
Note">
</div>
<input type="text" class="fileName" name="fileName" id="fileName"
size="35">
<input type="Submit" name="Submit2" class="filName_But" value="Save
File Name">
</div>
</form>
PHP WRITE:
$noteName = $_POST['fileName'];
$noteData = $_POST['notes'];
$notes = fopen('' + $noteName,"wb");
fwrite($notes,$noteData);
fclose($notes);
It seems like you have two submit buttons on one page which causes only one input field to get posted.
Restructure your form to something like this:
<form method="post">
<div>
<div style="margin-right:5px;">
<input type="text" class="fileName" name="fileName" id="fileName" size="35" value="untitled">
<input type="text" name="noteData" id="notes" size="250">
<input type="Submit" name="Submit" value="Save">
</div>
</div>
</form>
Get the POST data in your php script:
$noteName = $_POST['fileName'];
$noteData = $_POST['notes'];
$notes = fopen('' + $noteName,"wb");
fwrite($notes,$noteData);
fclose($notes);
By the way using the textarea tag would be more suitable for the note input:
<form method="post">
<div>
<div style="margin-right:5px;">
<input type="text" class="fileName" name="fileName" id="fileName" size="35" value="untitled"><br>
<textarea type="text" name="noteData" id="notes"></textarea><br>
<input type="Submit" name="Submit" value="Save">
</div>
</div>
</form>
Try using file_put_contents() instead of fwrite()
Example
// Create a unique prefix to prevent duplicate file names
$noteNamePrefix = $prefix = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1);
$noteName = $_POST['fileName'];
$noteData = $_POST['notes'];
// Write File To Disk (Replace _PATH_TO_DIR With the destination path Eg /public_html/uploads/)
file_put_contents(_PATH_TO_DIR_.$noteNamePrefix.$noteName, $noteData);

Get value from $_GET and use it as a ID

I have problem with reciving $_GET value, I need it as a ID to update my table.
Im using <a href='includes/edit_section.php?id=$id'>Change</a>. Variable $id is properly fetched and it is working, when I click on this link (because it is in table) it shows right value.
But problem is in next part, when I recive it with $_GET. I tryed to make variable ($id = $_GET['id']) but there is no any change.
When I execute this, nothing updates, when I replace $_GET with number it works perfectly.
My table looks like this Table(ID,Title,Paragraph,Image)
This is my code:
<?php
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$paragraph = $_POST['paragraph'];
$query = "UPDATE table SET title = '{$title}', paragraph = '{$paragraph}' WHERE id = '{$_GET['id']}' ";
$c= mysqli_query($connection, $query);
}
This is my form
<form action="edit_section.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
<label for="paragraph">Paragraph</label>
<input type="text" class="form-control" name="paragraph">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="cHANGE">
</div>
</form>
The problem is that you need to send the id when you submit the form, a traditional way of doing it is using a hidden type input, for example <input type="hidden" name="id" value="<?= $id ?>"> And of course it is necessary to pass the id to the view where the form is rendered
So you could try this
<form action="edit_section.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?= $id ?>">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="paragraph">Paragraph</label>
<input type="text" class="form-control" name="paragraph">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="cHANGE">
</div>
</form>
And when processing the form
<?php
if(isset($_POST['submit'])) {
$id = $_POST['id'];
$title = $_POST['title'];
$paragraph = $_POST['paragraph'];
$query = "UPDATE table SET title = '{$title}', paragraph = '{$paragraph}' WHERE id = '{$id}' ";
$c= mysqli_query($connection, $query);
}
I separated in its respective form-group the inputs of title and paragraph
At top add
$id = $_GET['id'];
then
basically problem is in
<form action="edit_section.php"
it should be
<form action="edit_section.php?id=<?php echo $id;?>"
plus in your update query id should be ID (capital).. also check for other column names for case-sensitivity
change the action for form at HMTL like tihs
<form action="edit_section.php?<?=$_GET['id']?>" method="post" enctype="multipart/form-data">
Add "id" as a hidden variable in your form.
Edited - Missed out an enclosing double quote for the hidden 'id' value in the form.
<form action="edit_section.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
<label for="paragraph">Paragraph</label>
<input type="text" class="form-control" name="paragraph">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="cHANGE">
</div>
</form>
Make the following changes to your PHP script
<?php
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$id = $_POST['id'];
$paragraph = $_POST['paragraph'];
$query = "UPDATE table SET title = '{$title}', paragraph = '{$paragraph}' WHERE id = '{$id}' ";
$c= mysqli_query($connection, $query);
}
?>

trying to add more than one picture onto webpage php

I am trying to add more than one picture to the webpage but it only allows me to add 1. Im trying to add more than 3 images onto the webpage, All ive done is add a button that allows you to select the file but i want more that 1 files and minimum of 4 pictures to be uploaded
heres the code:
<section class="left">
<ul>
<li>Manufacturers</li>
<li>Bikes</li>
</ul>
</section>
<section class="right">
<?php
if (isset($_POST['submit'])) {
$stmt = $pdo->prepare('INSERT INTO bikes (model, description, price, manufacturerId)
VALUES (:model, :description, :price, :manufacturerId)');
$criteria = [
'model' => $_POST['model'],
'description' => $_POST['description'],
'price' => $_POST['price'],
'manufacturerId' => $_POST['manufacturerId']
];
$stmt->execute($criteria);
if ($_FILES['image']['error'] == 0) {
$fileName = $pdo->lastInsertId() . '.jpg';
move_uploaded_file($_FILES['image']['tmp_name'], '../images/bikes/' . $fileName);
}
echo 'Bike added';
}
else {
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
?>
<h2>Add Product</h2>
<form action="addbike.php" method="POST" enctype="multipart/form-data">
<label>Bike Model</label>
<input type="text" name="model" />
<label>Description</label>
<textarea name="description"></textarea>
<label>Condition</label>
<input type="text" name="Condition" />
<label>Price</label>
<input type="text" name="price" />
<label>Category</label>
<select name="manufacturerId">
<?php
$stmt = $pdo->prepare('SELECT * FROM manufacturers');
$stmt->execute();
foreach ($stmt as $row) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
?>
</select>
<label>Bike image</label>
<input type="file" name="image" />
<input type="submit" name="submit" value="Add Product" />
</form>
<?php
}
else {
?>
<h2>Log in</h2>
<form action="index.php" method="post">
<label>Username</label>
<input type="text" name="username" />
<label>Password</label>
<input type="password" name="password" />
<input type="submit" name="submit" value="Log In" />
</form>
<?php
}
}
?>
To allow multiple file selection from input file will be like
<input type="file" name="image" multiple>
To fetch all the files selected
print_r($_FILES); // will return you detail of all files in array
The multiple attribute of the input tag is not supported in Internet
Explorer 9 and earlier versions.
You can select multiple files at a time but you need to add multiple then you can select files like this.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="upload.php" method="post" multipart="" enctype="multipart/form-data">
<input type="file" name="img[]" multiple>
<input type="submit">
</form>
</body>
</html>
<?php
echo '<pre>';
$img = $_FILES['img'];
if(!empty($img))
{
$img_desc = reArrayFiles($img);
print_r($img_desc);
foreach($img_desc as $val)
{
$newname = date('YmdHis',time()).mt_rand().'.jpg';
move_uploaded_file($val['tmp_name'],'./uploads/'.$newname);
}
}
function reArrayFiles($file)
{
$file_ary = array();
$file_count = count($file['name']);
$file_key = array_keys($file);
for($i=0;$i<$file_count;$i++)
{
foreach($file_key as $val)
{
$file_ary[$i][$val] = $file[$val][$i];
}
}
return $file_ary;
}

HTML Form with a PHP post to .txt

I know this is repetitive but i do not know PHP at all.. And trying to learn in a time crunch is not working how can i post to a text file? This is what i tried and i get an internal server error...
<div id="signupform" class="sb-search clearfix">
<form method="post" id="contact" class="clearfix" action="/comingsoon/php/formfix.php" name="email">
<input class="sb-search-input" placeholder="Enter email ..." type="text" value="" name="email">
<input class="sb-search-submit" value="" type="submit" name="email">
<button class="formbutton" type="submit"><span class="fa fa-envelope-o"></span></button>
</form>
</div>
this is the PHP formfix.php...
<?php
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$file = fopen("/comingsoon/json.txt",);
fwrite($file,$email);
fclose($file);
print_r(error_get_last());
}
?>
What am i doing wrong...
Here is the solution to fix your PHP post to TXT
HTML
<div id="signupform" class="sb-search clearfix">
<form method="post" id="contact" class="clearfix" action="comingsoon/php/formfix.php"> <!-- I remove name="email"-->
<input class="sb-search-input" placeholder="Enter email ..." type="text" value="" name="email">
<input class="sb-search-submit" value="" type="submit" name="email1">
<button class="formbutton" type="submit"><span class="fa fa-envelope-o"></span></button>
</form>
</div>
In your formfix.php should be like this.
<?php
if(isset($_POST['email']) && isset($_POST['email1'])) {
$data = $_POST['email'] . '-' . $_POST['email1'] . "\n";
$ret = file_put_contents('json.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
And you will get this result
I already do a test and it's work
Take a note please be aware on file location. And json.txt path must be at formfix.php .
Regards :)
Maybe my English is not good, but I will try to explain is to you as my best.
You should alter your HTML like this:
<div id="signupform" class="sb-search clearfix">
<form method="post" id="contact" class="clearfix" action="/comingsoon/php/formfix.php">
<input class="sb-search-input" placeholder="Enter email ..." type="text" name="email">
<input class="sb-search-submit" type="submit" >
</form>
A name of this "submit" isn't necessary。And so is the form。
Then,your PHP file should look like this:
<?php
if(isset($_POST['email']))
{
$email = $_POST['email'];
$file = fopen("/comingsoon/json.txt",);
fwrite($file,$email);
fclose($file);
print_r(error_get_last());
}
?>
Because the data that post to your server is only "email".
Good Luck to you!

post renamed filename from upload to database

I coule really use some help. I need to post the new name of the file to the database. Currently this code is posting the orginal name to the database? How can I post the new name to the database? Please see the code below.
<form action="" method="post" enctype="multipart/form-data">
<p>
<label for="file">Name:</label>
<input type="text" name="user_name" id="name" size="24"/>
</p>
<p>
<label for="file">Email Address:</label>
<input type="text" name="email" id="email" size="24"/>
</p>
<p>
<label for="file">Phone Number:</label>
<input type="text" name="phone" id="phoneNumber" size="24"/>
</p>
<p>
<label for="file">Comments:</label>
<textarea cols="80" rows="6" name="comments"></textarea>
</p>
<p>
<label for="file">Filename:</label>
<input type="file" name="fupload" id="fupload" size="24"/>
</p>
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<br>
<br>
<?php
require 'config.php';
require 'functions.php';
if(isset($_FILES['fupload'])) {
if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name'])) {
$old_filename = $_FILES['fupload']['name'];
$random_digit=rand(0000,9999);
$filename=$random_digit . $old_filename;
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
move_uploaded_file($source, $target);
createThumbnail($filename);
}
}
include "connect.php";
$db_database = new mysqli($db_host, $db_user, $db_pass, $db_database);
$user_name = stripslashes($_POST['user_name']);
$email = stripslashes($_POST['email']);
$phone = stripslashes($_POST['phone']);
$comments = stripslashes($_POST['comments']);
$filename = basename( $_FILES['fupload']['name']);
$query = "INSERT into upload
(user_name, email, phone, comments, fupload, date_added)
values ('$user_name', '$email', '$phone', '$comments', '$filename', NOW())";
$db_database->query($query);
?>
You need to tweak the line:
$filename = basename( $_FILES['fupload']['name']);
just before you create the SQL statement; you should set the value of $filename there to the new name of your file.
Oh, and I'm sure that someone will be along shortly to point out that your script is open to SQL injections.

Categories