Create a condition between SAVE and SAVE&PUBLISH - publish

I seem to get a tangled mind these past few days with my project. I'm trying to build a custom cms and I am up to the point of creating posts for website pages.
I have two(2) buttons -> 'SAVE' and 'SAVE & PUBLISH' The SAVE button will submit my form fields to the database but not putting number 1 in the publish field so it wouldn't be processed as published while the SAVE&PUBLISH will do the same but will put number 1 to the publish field so it will be processed as published.
How do I build a condition with this without probably messing up my code? I know this comes with a little tweaking. Please see my current code.
// CHECK IF THE FORM WAS SUBMITTED
if( isset( $_POST['submit'] ) ){
$title = $_POST['title'];
$editor_data = $_POST[ 'editor1' ];
$format = $_POST[ 'format' ];
$page = $_POST['page'];
//IF FORM WAS SUBMITTED, CHECK IF THERE ARE ERRORS
if(empty($title) === true){
$errors[] = "You forgot to add a Title";
}
if(empty($editor_data) === true){
$errors[] = "You forgot to add a Content";
}
if(empty($format) === true){
$errors[] = "Please choose a title format";
}
if(empty($page) === true){
$errors[] = "Please choose a Page";
}
//IF THE ERROR ARRAY IS EMPTY THEN PROCESS THE FORM
if (empty($errors) === true){
switch ($format)
{
case "1":
$post_title = "<h1>".$title."</h1>";
break;
case "2":
$post_title = "<h2>".$title."</h2>";
break;
case "3":
$post_title = "<h3>".$title."</h3>";
break;
case "4":
$post_title = "<h4>".$title."</h4>";
break;
case "5":
$post_title = "<h5>".$title."</h5>";
break;
case "6":
$post_title = "<h6>".$title."</h6>";
break;
default:
$post_title = $title;
}//>end of switch
//current time zone
date_default_timezone_set('Asia/Manila');
$date = date('Y-m-d');
$date_time = date('Y-m-d H:i:s');
//INSERT VALUES FROM FORM TO THE DATABASE TABLE
mysql_query("INSERT INTO posts (`post_title`, `post_content`, `post_page`, `date_posted`) VALUES('$post_title', '$editor_data', '$page', '$date_time')");
// IF ERROR ARRAY IS NOT EMPTY, OUTPUT ERRORS!
} else if(empty($errors) === false){
//output errors
echo output_errors($errors);
}//> end of else if errors
}//>end of isset submit

Solved my own question. My only concern now is how do I make this block of code shorter. Is there a workaround for this?
// CHECK IF THE FORM WAS SUBMITTED AS SAVED
if( isset( $_POST['save'] ) ){
$title = $_POST['title'];
$editor_data = $_POST[ 'editor1' ];
$format = $_POST[ 'format' ];
$page = $_POST['page'];
//IF FORM WAS SUBMITTED, CHECK IF THERE ARE ERRORS
if(empty($title) === true){
$errors[] = "You forgot to add a Title";
}
if(empty($editor_data) === true){
$errors[] = "You forgot to add a Content";
}
if(empty($format) === true){
$errors[] = "Please choose a title format";
}
if(empty($page) === true){
$errors[] = "Please choose a Page";
}
//IF THE ERROR ARRAY IS EMPTY THEN PROCESS THE FORM
if (empty($errors) === true){
switch ($format)
{
case "1":
$post_title = "<h1>".$title."</h1>";
break;
case "2":
$post_title = "<h2>".$title."</h2>";
break;
case "3":
$post_title = "<h3>".$title."</h3>";
break;
case "4":
$post_title = "<h4>".$title."</h4>";
break;
case "5":
$post_title = "<h5>".$title."</h5>";
break;
case "6":
$post_title = "<h6>".$title."</h6>";
break;
default:
$post_title = $title;
}//>end of switch
//current time zone
date_default_timezone_set('Asia/Manila');
$date = date('Y-m-d');
$date_time = date('Y-m-d H:i:s');
//insert values from form to server
mysql_query("INSERT INTO posts (`post_title`, `post_content`, `post_page`, `date_posted`) VALUES('$post_title', '$editor_data', '$page', '$date_time')");
// IF ARRAY ERROR IS NOT EMPTY, OUTPUT ERRORS!
} else if(empty($errors) === false){
//output errors
echo output_errors($errors);
}//> end of else if errors
}else if(isset( $_POST['publish'] )){
$title = $_POST['title'];
$editor_data = $_POST[ 'editor1' ];
$format = $_POST[ 'format' ];
$page = $_POST['page'];
//IF FORM WAS SUBMITTED, CHECK IF THERE ARE ERRORS
if(empty($title) === true){
$errors[] = "You forgot to add a Title";
}
if(empty($editor_data) === true){
$errors[] = "You forgot to add a Content";
}
if(empty($format) === true){
$errors[] = "Please choose a title format";
}
if(empty($page) === true){
$errors[] = "Please choose a Page";
}
//IF THE ERROR ARRAY IS EMPTY THEN PROCESS THE FORM
if (empty($errors) === true){
switch ($format)
{
case "1":
$post_title = "<h1>".$title."</h1>";
break;
case "2":
$post_title = "<h2>".$title."</h2>";
break;
case "3":
$post_title = "<h3>".$title."</h3>";
break;
case "4":
$post_title = "<h4>".$title."</h4>";
break;
case "5":
$post_title = "<h5>".$title."</h5>";
break;
case "6":
$post_title = "<h6>".$title."</h6>";
break;
default:
$post_title = $title;
}//>end of switch
//current time zone
date_default_timezone_set('Asia/Manila');
$date = date('Y-m-d');
$date_time = date('Y-m-d H:i:s');
//insert values from form to server
mysql_query("INSERT INTO posts (`post_title`, `post_content`, `post_page`, `date_posted`, `publish`) VALUES('$post_title', '$editor_data', '$page', '$date_time', '1')");
// IF ARRAY ERROR IS NOT EMPTY, OUTPUT ERRORS!
} else if(empty($errors) === false){
//output errors
echo output_errors($errors);
}//> end of else if errors
}//>end of isset publish

Related

I can't seem to find a way to check if a email has been taken in my mysql db (php7)

I have created a php7 and mySQL website that lets users login and register to a site.
I have made sure that the user cannot use the same username as someone else that has signed up, but I cannot seem to do the same with the emails.
I made my website so when the signup button is pressed, the browser directs to a file called signup.inc.php. I don'tknow what to change or how to fix it,I have been searching for a solution and I am pretty stuck on this problem, so help would be nice :)
The part I am focusing on is:
if ($resultCheck > 0) {
header("Location: ../signup.php?error=emailtaken");
exit();
this also includes the working user checker:
else {
$sql = "SELECT uidUsers AND emailUsers FROM users WHERE uidUsers=? AND emailUsers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../signup.php?error=usertaken");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../signup.php?error=emailtaken");
exit();
}
I tried a few things to get it to work that is maybe why it is messy, but I cannot seem to get the check of the email in the database to work. It says on my website "signup success" but what it should say is "email taken". Any help?
Here is the full page for reference:
<?php
if (isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$username = $_POST['uid'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
if (empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../signup.php?error=emptyfields&uid=".$username."&mail=".$email);
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../signup.php?error=invalidmailuid");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidmail&uid=".$username);
exit();
}
else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../signup.php?error=invaliduid&mail=".$email);
exit();
}
else if($password !== $passwordRepeat){
header("Location: ../signup.php?error=passwordcheck&uid=".$username."&mail=".$email);
exit();
}
else {
$sql = "SELECT uidUsers AND emailUsers FROM users WHERE uidUsers=? AND emailUsers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../signup.php?error=usertaken");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../signup.php?error=emailtaken");
exit();
}
else {
//other
$sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?) ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success");
exit();
}
}
}
}
}
msqli_stmt_close($stmt);
msqli_close($conn);
}
else {
header("Location: ../signup.php");
exit();
}
I tried bug fixing, looking for a solution, and trying to do the same as the username but idk
I wanted emails to be not repeated, but on my website, it says 'login success' which is wrong.
It is happening because of an 'AND' condition in your SQL where clause. Validate only username Column to check for exists.
In your implementation, it is checking the combination of email and username for duplicates.
If you want to validate either of the columns, use an 'OR' In your where clause.

youtube video info json object gives error

I am working on youtube api
and I want to get youtube video information using youtube video info JSON object
and I am using a code as given below but when I try to run this code it is showing error as "Video Is not cipher not needed to decode"
please help me to solve it out also tell me where is the problem in code
<?php
// Video with cipher signature
$video_id = "zDrNLZ1uJ2w";
// get_video_info url formation
// although for cipher signature we have to get the details from the video's webapge not from get_video_info object
$info_url = "http://www.youtube.com/get_video_info?el=detailpage&asv=3&video_id=".$video_id;
// youtube webpage url formation
$yt_url = 'http://www.youtube.com/watch?v='.$video_id.'&gl=US&persist_gl=1&hl=en&persist_hl=1';;
// get the contents from the url
$raw_data = file_get_contents($info_url);
// parse the data received and save it as an array
$output = array();
parse_str($raw_data,$output);
// check the status of the get_video_info object
if($output['status']=='ok'){
// check for the cipher signature
$cipher = (isset($output['use_cipher_signature']) && $output['use_cipher_signature']=='True') ? true : false;
// If cipher is true then we have to decode it
if($cipher == true){
// if cipher is true then we have to change the plan and get the details from the video's youtube wbe page
$yt_html = file_get_contents($yt_url);
// parse for the script containing the configuration
preg_match('/ytplayer.config = {(.*?)};/',$yt_html,$match);
$yt_object = #json_decode('{'.$match[1].'}') ;
/// check if we are able to parse data
if(!is_object($yt_object)){
echo 'Sorry! Unable to parse Data';
}else{
// parse available formats
$formats = $yt_object->args->url_encoded_fmt_stream_map;
// get the player id from assets section
$player_id = strbtwn($yt_object->assets->js,'html5player-','.js');
$player_id = explode("/", $player_id);
$player_id = $player_id[0];
echo 'Player ID: '.$player_id.'<br /><hr />';
// get the algo dictionary
// first check if the file exists
if(file_exists('./algo.json'))
$algos = json_decode(file_get_contents('algo.json'),true);
else{
// API call to fetch the algo dictionary
$algos_dict = file_get_contents("http://api.gitnol.com/getAlgo.php?playerID=".$player_id);
// saving the algo dictonary in local env for easy access
// Note: Developers should save the dictionary in their local env.
// Only make the API call for the new player ids which is not present in the algo dictionary.
// Repeated violation will results in IP ban.
file_put_contents('algo.json', $algos_dict);
$algos = json_decode($algos_dict,true);
}
/// check if the algo exist for the given player id
if(!array_key_exists($player_id, $algos)){
// if the algo dictionary is old then fetch a new one
$algos_dict = file_get_contents("http://api.gitnol.com/getAlgo.php?playerID=".$player_id);
file_put_contents('algo.json', $algos_dict);
$algos = json_decode($algos_dict,true);
$algo = $algos[$player_id][1];
}else{
$algo = $algos[$player_id][1];
}
echo 'Algo Used: '.$algo.'<br /><hr />';
// download links formation
$dlinks = array();
$links = explode(',',$formats);
echo 'Download links <br /><br />';
foreach ($links as $link) {
parse_str($link,$linkarr);
// parse link array one by one and decrypt the signature
$dlinks[$linkarr['itag']] = $linkarr['url'] . "&signature=" . decrypt($linkarr['s'],$algo);
echo $linkarr['itag'].'<br />';
echo $dlinks[$linkarr['itag']].'<br /><br />';
}
echo '<hr />';
}
}else{
echo 'Video Is not cipher not needed to decode';
}
}else{
echo 'Unable to get Video Info';
}
// string helper function
function strbtwn($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
// signature decoding
// parse the python string operation into php string operation
function decrypt($sig, $algo){
$funcarr = explode(' + ', $algo);
$decrypt = '';
foreach($funcarr as $singfunc){
$singfunc = substr($singfunc,2,-1);
$operators = explode(':', $singfunc);
if (sizeof($operators) == 1) {
$decrypt .= $sig[$operators[0]];
}
if (sizeof($operators) == 2) {
if($operators[0] == ''){
$decrypt .= substr($sig, 0 ,$operators[1]);
}
if($operators[1] == ''){
$decrypt .= substr($sig, $operators[0]);
}
if($operators[0] >= 0 && $operators[1] >= 0){
$decrypt .= substr($sig, $operators[0], $operators[1] - $operators[0]);
}
}
if (sizeof($operators) == 3) {
if($operators[0] == '' && $operators[1] == ''){
$decrypt .= strrev($sig);
}
if($operators[0] >=0 && $operators[1] == '' && $operators[0] != ''){
$decrypt .= strrev(substr($sig, 0, $operators[0] + 1));
}
if($operators[0] >=0 && $operators[1] >= 0 && $operators[0] != '' && $operators[1] != ''){
$decrypt .= strrev(substr($sig, $operators[1] + 1, $operators[0] - $operators[1]));
}
}
}
return $decrypt;
}
?>
According to your code $cipher is being set to false because 'use_cipher_signature' is not found in the $raw_data from file_get_contents($info_url).

Issue with 'if statement' in a php form with multiple recipients

My php form has a <select> option for multiple recipients with an email address associated to each of them:
<select name="sendto">
<option value="select">-- Select --</option>
<option value="general">General</option>
<option value="support">Support</option>
<option value="sales">Sales</option>
</select>
I'm able to send and receive successfully only the 'General' option, the rest fails. It's obvious the issue is with the 'if statement' but I can't figure out what the problem is exactly. Any help? Thanks.
This is the php code:
<?php
$to = $_REQUEST['sendto'] ;
$from = $_REQUEST['Email'] ;
$name = $_REQUEST['Name'] ;
$headers = "From: $from";
$subject = "Web Contact Data";
$fields = array();
$fields{"Name"} = "Name";
$fields{"Company"} = "Company";
$fields{"Email"} = "Email";
$fields{"Phone"} = "Phone";
$fields{"list"} = "Mailing List";
$fields{"Message"} = "Message";
$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$headers2 = "From: noreply#my-site.com";
$subject2 = "Thank you for contacting us";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.my-site.com";
if ($sendto == 'general') {
$to = 'alex#my-site.com';
}
else if ($sendto == 'support') {
$to = 'alabanino#my-site.com';
}
else if ($sendto == 'sales') {
$to = 'alabanino#my-site.com';
}
else { //other options
$to = 'alex#my-site.com';
}
if($from == '') { print "You have not entered an email, please go back and try again"; }
else {
if($name == '') { print "You have not entered a name, please go back and try again"; }
else {
$send = mail($to, $subject, $body, $headers, '-fnoreply#yourmailer.com');
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send){
header( "Location: http://www.my-site.com/thankyou.html" );}
else {
print "We encountered an error sending your mail, please notify webmaster#my-site.com";
}
}
}
?>
Where is $sento defined? This will be 'working' cos it will be defaulting to your final else condition as all others fail.
You need to add this and it should work
$sendto = $_REQUEST['sendto']
Or else use $to insetad

Is this correct mysqli

Is this correct, I know you aren't supposed to use mysql anymore. So I just added i to the end, this was code I got from the internet, and I am new to mysql so I'm not quite sure what I am doing. I just want to make sure this is correct usage.
$sql = "SELECT lat, lon from zipcodes_2011 WHERE zipcode='$zip'";
$r = mysqli_query($con, $sql);
if (!$r) {
$this->last_error = mysqli_error();
return false;
} else {
$row = mysqli_fetch_array($r);
mysqli_free_result($r);
return $row;
}
That is incorrect.
Looking at the documentation for mysqli_error: it states that mysqli $link is not optional. You must pass the database link to it.
$this->last_error = mysqli_error($con);
I would also highly recommend preparing this.
$sql = "SELECT `lat`,`lon` FROM `zipcodes_2011` WHERE `zipcode` = ?";
$stmt = mysqli_stmt_init($link);
$error = mysqli_stmt_prepare($stmt, $sql);
if ($error === false) {
$this->last_error = mysqli_error($con);
return false;
}
$error = mysqli_stmt_bind_param($stmt, "s", $zip);
if ($error === false) {
$this->last_error = mysqli_error($con);
return false;
}
$error = mysqli_stmt_execute($stmt);
if ($error === false) {
$this->last_error = mysqli_error($con);
return false;
}
$error = mysqli_stmt_bind_result($stmt, $row);
if ($error === false) {
$this->last_error = mysqli_error($con);
return false;
}
$error = mysqli_stmt_fetch($stmt);
if ($error === false) {
$this->last_error = mysqli_error($con);
return false;
}
return $row;

Drupal db_insert is not saving more than 440 records at a time

I am working on the Drupal CMS, where i am parsing a file & storing the data in DB.
So if there are more than 440 records (rows) in the file, it does not save it further. It works for the rows less than 440. It is an strange issue.
$query = db_insert('table_name')->fields(array('field1', 'field2', 'field3'));
$row = 1;
while (($data = fgetcsv($handle, 0, ",")) !== FALSE)
{
$num = count($data);
if ($row > 1) {
$query->values(
array(
'fields1' => $data[0],
'fields2' => $data[2],
'fields3' => $data[4]
));
if($row == '440'){
break;
}
}
$row++;
}
$query->execute();
/////
if($row == '440'){
break;
}
Is added to check how many rows it saves.. If i increase the 440 to 460, it doesn't save records to DB.
if($row == '440'){
break;
}
Remove this block and it'll be just fine.