Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

can i use request to add text to my page from url

$
0
0

I currently have a mailing list that my boss uses, when he adds an email there is no 'sucess message' to let him know it has worked.

 

The mailing list just redirects back to the add subscribers page. I wondered if its possible to add a request so when he adds an email I can redirect the url to this:

 

?page=addemail&message=your email was added

 

and then echo $message where I want it to appear.

 

I have added $message = $_REQUEST['message']; to my page but nothing is happening. Can I not use request like this?


Increment value based on condition

$
0
0

Hi all.

In my database, i have a table where a client chose a service providers to make payments and each bill setup counts as a reward point for the client. Each bill counts as a single point even if the bill is edited after a services might have expired or renewed it should not be counted again as point.

 

to count the number of bill set up by a client i did

$stmt = $pdo->prepare("UPDATE reward_points SET num_bill = num_bill + 1 WHERE username = '$username' AND acct_num = '$acct_num'");
$stmt->execute();

 

Its okay if it counts for new bills but i want it not to count for the same service provide and so i did

 

$stmt=$pdo->query("SELECT company FROM payment WHERE username = '$username' AND trans_ref = '$trans_ref'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$coy = $row['company'];
}
//ps: note, $company is a variable from the form
if(strcmp($coy, $company) == 0){

$stmt = $pdo->prepare("UPDATE reward_points SET num_bill = num_bill + 0 WHERE username = '$username' AND acct_num = '$acct_num'");
$stmt->execute();
}elseif(strcmp($coy, $company) != 0){
    
$stmt = $pdo->prepare("UPDATE reward_points SET num_bill = num_bill + 1 WHERE username = '$username' AND acct_num = '$acct_num'");
$stmt->execute();    
}

 

it just wont add up

 

i also tried

 

$coy1 = $coy;
$coy2 = $company;
$point = 0;

if(strcmp($coy1, $coy2) == 0){
   
    $add_point = $point + 0;
}else{
   
    $add_point = $point + 1;
}

$stmt = $pdo->prepare("UPDATE reward_points SET num_bill = $add_point WHERE username = '$username' AND acct_num = '$acct_num'");
$stmt->execute();
 

 

still wont work. any idea?

 

Return Multiple Values from picklist using $_REQUEST

$
0
0

So I have an existing picklist that i am trying to tweak - I am making it into a multiselect and trying to return multiple values

I have been able to accomplish the first part by adding select 'multiple' but when i submit it only returns results for the last value selected.

 

Here is the code for the form (Left out the picklists that do not need to be multiple select)

 

<td align="center" valign="top">
<? // base64_encode(base64_encode( 'test1'))?>
<br />
<br />
<form id='report_form' action="driverreport_sd.php" method="post" name="report_form">
<!--<div class="criteria_div">-->
<table align="center" class="table_border" cellpadding="5" cellspacing="0" width="80%">
<tr>
<td align="right" class="first_td">
Status:
</td>
<td align="left">
<select multiple name='Status' id='Status'>

<? $statuslist=$ObjReport->ObjStatus->get_Status_List(); while($status=mysql_fetch_object($statuslist)) { if($status->Status=="Please Select") { ?>

<option value="<?=$status->Status?>" <?=($status->Status==$_REQUEST['Status']?"selected=selected":"")?>>
<?=$status->Status?></option>
<? } else { ?>
<option value="<?=$status->Status?>" <?=($status->Status==$_REQUEST['Status']?"selected=selected":"")?>>
<?=$status->Status?></option>
<? } } ?>
</select>
</td>
</tr>


<td align="center" colspan="2">
<input type="hidden" id='sort_by' name='sort_by' value="<?=$_REQUEST['sort_by']?>" />
<input type="hidden" name='search_val' id='search_val' value="
<?=$_REQUEST['search_val']?>" />
<input type="hidden" name='search_by' id='search_by' value="
<?=$_REQUEST['search_by']?>" />
<input type="hidden" name="report_submited" value='report_submited' />
<button type="submit" id="report_submited" name="" value='submit'>Submit</button>
</td>

 

and here is the return request

 

                <?    
                    if($_REQUEST['report_submited'])    
                    {
                        
                        
                    
                        
                    
                        $ReportData=$ObjReport->generate_report($_REQUEST['Status'],$_REQUEST['School'],$_REQUEST['Campaign'],$_REQUEST['State'],$_REQUEST['Stdtype'],$_REQUEST['Primbad'],$_REQUEST['Rep'],$_REQUEST['From_Date'],$_REQUEST['To_Date'],$_REQUEST['sort_by'],$_REQUEST['search_by'],$_REQUEST['search_val']);
                        $currentTotalRow=mysql_num_rows($ReportData);
                        if($currentTotalRow>0)
                        {
                        
                ?>

 

Any suggestions would be appreciated

Thanks!

 

Detect whether the page was refreshed

$
0
0

How can I detect if the page was refreshed?  I thought the following worked, however, after much head scratching, discovered it does not work for a POST request using the Chrome browser.  Thanks


<?php
$refresh=isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
echo(($refresh?'refresh':'not refresh').'<br>');
echo('$_GET<pre>'.print_r($_GET,1).'</pre>');
echo('$_POST<pre>'.print_r($_POST,1).'</pre>');
?>
<ul>
<li><a href="refresh.php?id=1">one</a></li>
<li><a href="refresh.php?id=2">two</a></li>
<li><a href="refresh.php?id=3">three</a></li>
</ul>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="text" value="hello">
<input type="submit" name="submit" value="submit">
</form>

array() construct

$
0
0

I am looking at the following code snippet:

 

               functioncall(array(),$variable)

 

I've looked everywhere, but cannot find what this is supposed to mean.

 

In the function that is called I see

 

            function functioncall($var = array(), $var1 = array())

 

Is this some kind of cast??

 

Thanks!

Simple XML: Delete node by id

$
0
0

XML file:

 

<?xml version="1.0" ... >
<database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <record>
        <id>1</id>
        <name></name>

    </record>
    <record>

        ...

    </record>
</database>

 

I want to delete the record where <id> equals $_GET['id']. I tried many suggested implementations based on xml or simplexml, without result.

Came across a very simple workaround (it should omit the record where id=$id), but can someone help me to taylor it to my xml scheme?

 

<?php
$file = "database.xml";

$id = $_GET['id'];
echo "DELETING: ".$id;
$xml = simplexml_load_file($file);

$str = "<?xml version=\"1.0\"?>
<database>";

foreach($xml->children() as $child){
if($child->getName() == "id") {
if($id == $child['name']) {
continue;
} else {
$str = $str.$child->asXML();
}
}
}
$str = $str."
</database>";
echo $str;

$xml->asXML("database_backup.xml");
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $str);
fclose($fh);
?>

Case Switch Array

$
0
0

Hello, I am having a small issue with a case switch array that uses a range of data. I am using it to set the background of table cells depending on the data. I.E. 0-0.9, 1-1.9 etc with each one being a different color. Issue I am having is it doesn't change. It sets it based on the first array entry. What might I be missing? This is the first time I have used a case switch with a range. 

 

-Thanks

$magScale = '';

           switch($magnitude)
{
              case myInterval >= 0 && myInterval <= 0.9: $magScale = 'rgb(195, 218, 236)';
                             break;
              case myInterval >= 1 && myInterval <= 1.9: $magScale = 'rgb(210, 238, 197)';
                             break;
              case myInterval >= 2 && myInterval <= 2.9: $magScale = 'rgb(244, 240, 202)';
                             break;
              case myInterval >= 3 && myInterval <= 3.9: $magScale = 'rgb(244, 223, 202)';
                             break;
              case myInterval >= 4 && myInterval <= 4.9: $magScale = 'rgb(240, 199, 205)';
                             break;
              case myInterval >= 5 && myInterval <= 10:  $magScale = 'rgb(212, 195, 236)';
                             break;

}

PHP isn't working with Apache webserver

$
0
0

First thing: I formatted my drive today and fresh installs of Apache2, PHP5 and MariaDB on Linux Mint 17.1. No files have been messed with. Not one. 

 

I created info.php and placed it in var/www dir. The file consists of one line:  <?php phpinfo(); ?>

 

When I run it our of my web editor (Bluefish), instead of showing me on my web browser the PHP info page that's suppose to show, I get:  <?php phpinfo(); ?>

 

I've been fighting this for two days! Done everything suggested by many others online...and that's why I had to scrub my drive; forgot all the files I augmented.

 

Does anyone know why my PHP files behave this way? I'd love to start working with PHP, but I can't until whatever's broken is fixed. Any ideas? Any suggestions? I'm at my wit's end with this.

 

Landslyde


URLs to long error in moz tools

$
0
0

Hi Professionals

 

I am currently going through the process of grading my website in MOZ tools and getting over 2000 URLs to crawl errors

 

The url I have is currently

www.myurl.com.au/hotel_details.php?hotel_id=358705&currency_code=AUD&q=%27%3A%2F%2Fwww.travelnow.com%2Ftemplates%2F451536%2Fhotels%2F358705%2Foverview%3Flang%3Den%26amp%3Bcurrency%3DAUD%26amp%3BstandardCheckin%3D12%2F17%2F2014%26amp%3BstandardCheckout%3D12%2F18%2F2014%26amp%3BroomsCount%3D1%26amp%3Brooms[0].adultsCount%3D2%27&price=149&totlday=1


How or where would I go about re-writing this I am not a professional with PHP and I have never done anything like this before

Thanks in advance

PHP mail issue

$
0
0
Hi All, I am using php mail function to send emails. But email sending 20 minutes late (i.e receiving 20 minutes after executing mail script) . The email body having URL "http://www.i-videos.in/test-event" . If i removed that URL from email body then email will receiving instantly. Is the email getting slow because of body email ? Could any one help regarding this issue asap? Thanks in advance...

Some problems with upload directory.

$
0
0

Heya all, as the title says, i meet some issues when uploading files to my server, here is the code;

$anime = $_POST['anime'];
$anime = $file = str_replace(' ', '\ ', $anime);
$anime = "Sous-titres/".$anime."/";
$target_dir = $anime;
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
if(isset($_POST["submit"])) {
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 50000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
var_dump ($target_dir);
echo "Sorry, there was an error uploading your file.";
}
}
}

So, i'm attempting to acces to a directory taking the name of the anime that the admin put in the input type="text", for upload the file selected in.

Error with the var_dump: string(28) "Sous-titres/Akame\ ga\ kill/" Sorry, there was an error uploading your file.

 

Hope you can help me ! :)

Insert calculated value to mysql table

$
0
0

Hi to All,

I am performing calculation which i echo it in the input form to insert it to DB table
The calculation works fine when i submit the form but the it does not correct calculation to the DB.
it seems that the isert to database is done before the calculation and I can't figure a way around it.

Because i'm submitting to the same page, the calculation populate in the input form correctly but it insert Zero to the database table instead of correct calculation populated in the input field to DB table

You could see from the line 114 to 116 that, i'm performing some calculations and echo it at line 128 and line 128 in the input form value field.

Please any help on how to do this...All the function in the code is in another file and it works fine...so the only program is that the calculated value is not inserted as expected

Here is the code

<?php
include 'core/initForMainLogPage.php';


if(isset($_GET['empId']) && !empty($_GET['empId'])){

//delete employee here
$empId=$_GET['empId'];
grabEmpId($empId);
}
?>

<?php
if(logged_in()){
$data=user_dataManager('username');
$usernameData=$data['username'];
}else{
header('Location: index.php');
}
?>
<?php include 'includes/adminHeadAll.php';?>

<header>
<?php include 'includes/managerMenu.php';?>  
</header>
<div class="container">
<br/>
<h3>Pay Employee</h3>
<?php
$error=array();
$errorAll='';
$leave="";
if(isset($_POST['empId']) && isset($_POST['name']) && isset($_POST['date']) && isset($_POST['basicSalary'])
&& isset($_POST['leave']) && isset($_POST['salaryPerDay']) && isset($_POST['leaveDeduct']) 
&& isset($_POST['netSalary'])){
$empId=htmlentities(mysql_real_escape_string($_POST['empId']));
$name=htmlentities(mysql_real_escape_string($_POST['name']));
$date=htmlentities(mysql_real_escape_string($_POST['date']));
$basicSalary=htmlentities(mysql_real_escape_string($_POST['basicSalary']));
$leave=htmlentities(mysql_real_escape_string($_POST['leave']));
$salaryPerDay=htmlentities(mysql_real_escape_string($_POST['salaryPerDay']));
$leaveDeduct=htmlentities(mysql_real_escape_string($_POST['leaveDeduct']));
$netSalary=htmlentities(mysql_real_escape_string($_POST['netSalary']));



//checking for the validity of data entered
if(empty($leave) || empty($date)){
$error[]='Pleave leave or date field is empty.';
}else{

if(preg_match('/[0-9]/',$leave)==false){
$error[]='Leave should only contain numbers'; 
}

if(empId($empId)===false){
$error[]="This employee is not recoganize by the system and can not be paid,he may need to register first.";
}

}

if(!empty($error)){
$errorAll= '<div class="error"><ul><li>'.implode('</li><li>',$error).'</li></ul></div>';


}else{
//this funciton insert into database
payrollData($name,$empId,$date,$basicSalary,$leave,$salaryPerDay,$leaveDeduct,$netSalary);
echo '<p class="pa">Payment made successfully.   <a href="employees-salary-report.php">See Payment Records</a></p>';
}


}//end isset


?>

<div class="tableWrap">
<form action="" method="post" >
<div class="styletable"><table cellpadding="" cellspacing="" border="0">
<?php
$query=mysql_query("SELECT 
			  empId,name,level,company.compId,company.levelOne,company.levelTwo,
			  company.levelThree,company.levelFour,company.levelFive
			   FROM employee JOIN company ON company.compId=1 WHERE empId='$empId' LIMIT 1");


while($row=mysql_fetch_array($query)){
  $empId=$row['empId'];
  $name=$row['name'];
  $levelEmp=$row['level'];
  $levelOne=$row['levelOne'];
  $levelTwo=$row['levelTwo'];
  $levelThree=$row['levelThree'];
  $levelFour=$row['levelFour'];
  $levelFive=$row['levelFive'];
  
  if($levelEmp==1){
	  $levelPay=$levelOne;
  }elseif($levelEmp==2){
	  $levelPay=$levelTwo;
  }elseif($levelEmp==3){
	  $levelPay=$levelThree;
  }elseif($levelEmp==4){
	  $levelPay=$levelFour;
  }elseif($levelEmp==5){
	  $levelPay=$levelFive;
  }
  


//making calculations here

$basicSalary=$levelPay * 30;
$leaveDeduct=$leave * $levelPay;
$netSalary=$basicSalary - $leaveDeduct;
}


?>
<tr><td>Employee ID: </td><td><input type="text" name="empId" readonly="readonly" value="<?php if(isset($empId)){echo $empId;}?>"></td></tr>
<tr><td>Employee: </td><td><input type="text" name="name" readonly="readonly" value="<?php if(isset($name)){ echo $name;}?>"></td></tr>
<tr><td>Date: </td><td><input type="text" id="Date" class="picker" name="date"></td></tr>

<tr><td> Basic Salary: </td><td><input type="text" name="basicSalary" readonly="readonly" value="<?php echo $basicSalary;?>"></td></tr>
<tr><td> No. Of Absent: </td><td><input type="text" name="leave" class="input" value=""></td></tr>
<tr><td> Salary Per Day:</td><td><input type="text" name="salaryPerDay" readonly="readonly" value="<?php echo $levelPay;?>"></td></tr>
<tr><td> Deduction For Absentee:</td><td><input type="text" name="leaveDeduct" readonly="readonly" value="<?php echo $leaveDeduct;?>"></td></tr>
<tr><td> Net Salary:</td><td><input type="text" name="netSalary" readonly="readonly" value="<?php echo $netSalary;?>"></td></tr>
<tr><td> </td><td><input type="submit" value="Submit Pay" class="submit" name="pay"></td></tr>
</table></div>

</form>
<?php



?>
</div>
<br />
<?php echo $errorAll; ?>
<p>Manage the monthly salary details of your employee along with the allowances, deductions, etc. by just entering their leave</p>
</div> 
<?php include 'includes/footerAll.php';?>  

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/ui.js"></script>
</body>
</html>

Need help with PHP header("Location

$
0
0

I was wondering if it's possible to retain loaded files and the current error setttings after a

header("Location: xxxx.php")

is issued, for example in this:

// Start up the session - not used yet but there just in case
session_start(1);

// Enable the Autoloader and initialise it
require_once 'Autoloader.php';
Autoloader::init();

// Check if the application has been installed yet ----------------------------
if(!file_exists('Engine/config.php')){
    session_write_close();
    header("Location: install/index.php");
    die();
}

And I get a class not found error when I open the install/index.php


session_start(1);
// @todo: Disable this in the production version .... I already did this in the main index -- do I have to do this on all pages that may error?
error_reporting(E_ALL & ~E_STRICT);
ini_set("display_errors",1);

// Because we jumped here, we have to reinstall the autoloader -- why?
require_once '../Autoloader.php';
Autoloader::init();

While I can understand I wouldn't want this if I was firing off to a completely different site, is there anyway to retain the settings within the same server environment or do I have to reset everything as above.

I even tried using session in the hope that this would 'remember' but it didn't work.

 

 

 

 

Getting Internal Server Error on Submit

$
0
0

Whenever I hit submit I get an internal server error. Here is the code:

<?php $modsToBeChecked = str_replace(
"\r",
"\n",
str_replace( "\r\n", "\n", $_POST[ 'modsToBeChecked' ] )
);
$modsToBeChecked = explode( "\n", $modsToBeChecked );


var_dump( $modsToBeChecked );?>

$modsToBeChecked is passed in from a textarea form. It is suppose to treat each line in the textbox as one element of the array. Here is the form code in case you need it:

<form  action=""><textarea name="modsToBeChecked" rows="25" cols="50"></textarea>
<input type="submit">
</form>

Sorting list in PHP

$
0
0

Hi!

 

I have this problem that I have to solve in PHP. I have such a difficult with this programming and I would be so grateful if someone could help me solve this.

The problem:

A lecturer has a group of students who need to be assigned to one of two groups for the
purpose of workshop sessions. She has a CSV file containing all the student records in the
following form:
 
student number, student first name, student last name
 
and requires that the students in this file are split into two equal sized groups based on the
alphabetical order of their last names. These two groups should be written out into separate
files in the alphabetical order of their last name.
 
I attach the student list in the post (students.txt)
 
If someone could spend their precious time helping me I would be forever thankful!

Attached Files


Email Contact form CODE // please help

$
0
0

Hi everyone.

Pretty desperate, first time that I'm working with php. Learning this language, makes sense, however I can't figure out why my code is not working.

Emails are not coming in at all. Additional required info (phone number, first name, last name) should be included in the message.

Please help. Thank you everyone.

 

<?php
$to          
"abcd@abcd.com";
$subject      "From Website Contact Form";
$first        $_REQUEST['first'];
$last         $_REQUEST['last'];
$email        $_REQUEST['email'];
$phone        $_REQUEST['phone'];
$MESSAGE_BODY "Name: " $_POST["first"] . "\n";
$MESSAGE_BODY "Name: " $_POST["last"] . "\n";
$MESSAGE_BODY "Contact No: " $_POST["phone"] . "\n";
$MESSAGE_BODY "Email: " $_POST["email"] . "\n";
$MESSAGE_BODY "Requirement: " nl2br($_POST["message"]) . "\n";
$message $_REQUEST['message' 'email' 'first' 'last'];
$from    $_REQUEST['email'];
$headers "From:" $from;
mail($to$subject$MESSAGE_BODY$headers);
echo 
"Your message has been sent";
?>

Can anyone help (php, json and mysqli)

$
0
0

I was pointed in this direction by a friend so firstly, hello :)

 

I'm having some teething problems (basically can't get my head around it) and wondered if anyone would be able to have a look at a script for me (beer money may be provided)

 

I'm currently using a php script which grabs information from a API with curl (JSON format). I'm limited to a number of requests an hour so my plan was to read the file, insert the data into a mysql table so that I could re-read over and over again with no limitations. Then use a script to run every few hours to grab the data.

 

The script I created works however it's a bit buggy with regards to what it does if information is already in the table. If there isn't a previous entry then it inserts everything fine.

 

The JSON data is a multi depth array, and deals with images as well as data so for me, it's rather complex.

 

What I want the script to do is this. Each item is a property (letting agent website)

 

Check to see if the property exists in the database and the JSON. If there is no record in the database, then insert in. If there is a record in the database, update that record. If there is a property in the database which isn't in the JSON file, then delete it from the database.

 

This is basically the same plan for each sub array (pictures, floorplans, etc) however the images are copied from the url given (hosted on amazon) to my own host in order to speed up loading times, etc.

 

i've added a copy of the code but obviously its going to be stupidly hard to understand.

 

Is there any way this could be split into different functions to try and sort it out? haha

<?php


  	$ch = curl_init(); /* Section 1 */
  	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  	curl_setopt($ch, CURLOPT_POST, 1);
  	curl_setopt($ch, CURLOPT_URL, 'URL');
  	//prepare the field values being posted to the service
  	$data = array("appkey" => "KEY","account" => "ACCOUNT" );
  	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

  	//make the request
  	$result = curl_exec($ch);
	$properties = json_decode($result, true);
	$properties = $properties['properties'];
	//pr($parsed_json);
	
	
	foreach($properties as $key => $value) {


		/* Set the vars */
		$microTime = microtime();
		$time = time();
		$cat_id = $value['category_id'];
		$price = $value['price'];
		if ($value['category_id'] == "1") { $price_after = $value['qualifier_name']; } else { $price_after = $value['freq_name']; }
		$full_address = $value['full_address'];
		$address_1 = $value['address_1'];
		$address_2 = $value['address_2'];
		$address_3 = $value['address_3'];
		$address_4 = $value['address_4'];
		$address_5 = $value['address_5'];
		$bedrooms = $value['bedrooms'];
		$bathrooms = $value['bathrooms'];
		$summary = $value['summary'];
		$description = $value['description'];
		$type_name = $value['type_name'];
		$status = $value['status'];
		$feature_1 = $value['feature_1'];
		$feature_2 = $value['feature_2'];
		$feature_3 = $value['feature_3'];
		$feature_4 = $value['feature_4'];
		$lat = $value['lat'];
		$long = $value['lng'];
		
		
		/* Delete the properties from the database which can't be found in the file */
		$searchProp = "SELECT property_id FROM props WHERE property_address_full = '$full_address' AND property_catid = '$cat_id'";
		if ($result = mysqli_query ($linkq, $searchProp)) {
			if (!$whereStatement) { $whereStatement = "WHERE property_id != $row[property_id]"; } else { $whereStatement .= " OR property_id != $row[property_id]"; } // Set the whereStatement for deleting properties with no ID
			$deleteProp = "DELETE FROM props $whereStatement";
			if ($result = mysqli_query ($linkq, $deleteProp)) {
				$totalPropsDeleted++;
				echo "Properties deleted $deleteProp";

				$deleteimg = "DELETE FROM props_images $whereStatement";
				if ($result = mysqli_query ($linkq, $deleteimg)) {
					echo ("Images Deleted Successfully<br />\n");
				} else {
					echo ("Error Deleting");
				}
	
				$deleteepc = "DELETE FROM props_epcs $whereStatement";
				if ($result = mysqli_query ($linkq, $deleteepc)) {
					echo ("EPCs Deleted Successfully<br />\n");
				} else {
					echo ("Error Deleting");
				}
	
				$deletepdf = "DELETE FROM props_pdf $whereStatement";
				if ($result = mysqli_query ($linkq, $deletepdf)) {
					echo ("PDFs Deleted Successfully<br />\n");
				} else {
					echo ("Error Deleting");
				}
	
				$deletefloorplan = "DELETE FROM props_floorplans $whereStatement";
				if ($result = mysqli_query ($linkq, $deletefloorplan)) {
					echo ("Floorplans Deleted Successfully<br />\n");
				} else {
					echo ("Error Deleting");
				}
				
			} else {
				echo "Nothing to delete";
			}
		}
		
		
		echo "<br />";
		
		
		/* Check to see if the property exists currently */
		$existCheck = "SELECT * FROM props WHERE property_address_full LIKE '%$full_address%' AND property_catid = '$cat_id'";
		if ($result = mysqli_query ($linkq, $existCheck)) {
			$row_cnt = mysqli_num_rows($result);
			if ($row_cnt) {
				while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
					echo "Property Exists - $full_address";
					
                    
					if (($row[property_price] != $price) || ($row[property_summary] != $summary) || ($row[property_description] != $description)) {
						$dateUpdated = "property_updated = $microTime,";
					} else {
						$dateUpdated = "property_updated = property_updated,";
					}
														
					/* Property exists so update the property info */							
					$updateProp = "UPDATE props SET property_advertised = property_advertised,
					$dateUpdated
					property_catid = '$cat_id',
					property_price = '$price',
					property_price_after = '$price_after',
					property_address_full = '$full_address',
					property_address_1 = '$address_1',
					property_address_2 = '$address_2',
					property_address_3 = '$address_3',
					property_address_4 = '$address_4',
					property_address_5 = '$address_5',
					property_bedrooms = '$bedrooms',
					property_bathrooms = '$bathrooms',
					property_summary = '$summary',
					property_description = '$description',
					property_type = '$type_name',
					property_status = '$status',
					property_feature_1 = '$feature_1',
					property_feature_2 = '$feature_2',
					property_feature_3 = '$feature_3',
					property_feature_4 = '$feature_4',
					property_lat = '$lat',
					property_long = '$long' WHERE property_id = '$row[property_id]'";
					if (mysqli_query ($linkq, $updateProp)) {
						$totalPropsUpdated++;
						echo (" & Updated");
					} else {
						echo (" & Error Updating");
					}			
				
					echo ("<br />\n");
					
					/* Delete all the photos for this property as it doesn't matter if they are added again */
					$deletePhotos = mysqli_query ($linkq, "DELETE FROM props_images WHERE property_id = $row[property_id] OR property_id = ''");
					printf("Images Deleted: %d\n", mysqli_affected_rows($linkq));
					printf("<br />\n");
					
					/* Loop the current images and add back to the database and asign the property id */
					$primaryimg = 0;
					$totalimg = count($value['images']);
					for ($x = 0; $x < $totalimg; $x++) {
												
						$imagename = $value['images'][$x];	
						if (!$primaryimg) {	$image_main = "1"; } else { $image_main = "0"; }		
						$insertphoto = "INSERT into props_images VALUES ('', '$row[property_id]', '$imagename', '$image_main', '')";
						if (mysqli_query ($linkq, $insertphoto)) {
							echo ("- Inserted ($row[property_id]) ($imagename) ($image_main)\n");
														
							if (!file_exists('images/props/'. $imagename .'.jpg')) {
							
								/* Try and copy the image from the url */
								$file = 'https://utili-media.s3-external-3.amazonaws.com/stevemorris/images/' . $imagename . '_1024x1024.jpg';
								$newfile = 'images/props/' . $imagename . '.jpg';

								if (!copy($file, $newfile)) {
    								echo "- Failed to Copy\n";
								} else {
									echo "- Image Copied";
									/* Resize the image and create a thumb nail */
									$image = new SimpleImage();
									$image->load('images/props/' . $imagename . '.jpg');
									$image->resizeToWidth(240);
									$image->save('images/props/thumb/' . $imagename . '.jpg');
								}
								
							} else {
								echo ("- Nothing to upload, image exists");
							}
							
							echo "<br />\n";							
							
						} else {
							echo ("- Image Insert Error\n");
						}
						
						$primaryimg++;

					} /* close the image loop */
					
					/* Delete all the epcs for this property as it doesn't matter if they are added again */
					$deleteEpcs = mysqli_query ($linkq, "DELETE FROM props_epcs WHERE property_id = $row[property_id]");
					printf("EPCs Deleted: %d\n", mysqli_affected_rows($linkq));
					printf("<br />\n");
					
					/* Loop the current EPCs and insert into the database */
					$totalepc = count($value['epcs']);
					for ($y = 0; $y < $totalepc; $y++) {
												
						$epcname = $value['epcs'][$y];	
						$insertepc = "INSERT into props_epcs VALUES ('', '$new_property_id', '$epcname')";
						if (mysqli_query ($linkq, $insertepc)) {
							echo ("- Inserted EPC ($new_property_id) ($epcname)<br />\n");
						} else {
							echo ("- EPC Insert Error\n");
						}

					} /* close the epc loop */
					
					/* Delete all the pdfs for this property as it doesn't matter if they are added again */
					$deletePdfs = mysqli_query ($linkq, "DELETE FROM props_pdf WHERE property_id = $row[property_id]");
					printf("PDFs Deleted: %d\n", mysqli_affected_rows($linkq));
					printf("<br />\n");
					
					/* Loop the current PDFs and insert into the database */
					$totalpdf = count($value['pdfs']);
					for ($v = 0; $v < $totalpdf; $v++) {
												
						$pdfname = $value['epcs'][$v];	
						$insertpdf = "INSERT into props_pdf VALUES ('', '$new_property_id', '$pdfname')";
						if (mysqli_query ($linkq, $insertpdf)) {
							echo ("- Inserted PDF ($new_property_id) ($pdfname)<br />\n");
						} else {
							echo ("- PDF Insert Error\n");
						}

					} /* close the PDF loop */
					
					/* Delete all the pdfs for this property as it doesn't matter if they are added again */
					$deleteFloorplan = mysqli_query ($linkq, "DELETE FROM props_floorplans WHERE property_id = $row[property_id]");
					printf("Floorplans Deleted: %d\n", mysqli_affected_rows($linkq));
					printf("<br />\n");
					
					/* Loop the current Floorplans and insert into the database */
					$totalfloorplan = count($value['floorplans']);
					for ($v = 0; $v < $totalfloorplan; $v++) {
												
						$floorplanname = $value['floorplans'][$v];	
						$insertfloorplan = "INSERT into props_floorplans VALUES ('', '$new_property_id', '$floorplanname')";
						if (mysqli_query ($linkq, $insertfloorplan)) {
							echo ("- Inserted Floorplan ($new_property_id) ($floorplanname)<br />\n");
						} else {
							echo ("- Floorplan Insert Error\n");
						}
						
					} /* close the Floorplan loop */
					
				}	 /* close the property while loop */

			} else { /* close the if row exists loop */
		
				/* Insert the property as it doesn't exist in the database */			
				$insert = "INSERT INTO props VALUES ('', '$time', '', '$cat_id', '$price', '$price_after', '$full_address', '$address_1', '$address_2', '$address_3', '$address_4', '$address_5', '$bedrooms', '$bathrooms', '$summary', '$description', '$type_name', '$status', '$feature_1', '$feature_2', '$feature_3', '$feature_4', '$lat', '$long', '', '')";
				if (mysqli_query ($linkq, $insert)) {
					$totalPropsAdded++;
					echo ("Property Inserted - $value[full_address]<br />");
					
					/* get the property ID from the newly added property */
					$getPropID = mysqli_query ($linkq, "SELECT property_id FROM props ORDER BY property_id DESC LIMIT 1");
					while ($rowNew = $getPropID->fetch_array(MYSQLI_ASSOC)) {
						$new_property_id = $rowNew[property_id];
					}	
														
					/* Loop the current images and add to the database and asign the property id */
					$primaryimg = 0;
					$totalimg = count($value['images']);
					for ($x = 0; $x < $totalimg; $x++) {
												
						$imagename = $value['images'][$x];	
						if (!$primaryimg) {	$image_main = "1"; } else { $image_main = "0"; }			
						$insertphoto = "INSERT into props_images VALUES ('', '$new_property_id', '$imagename', '$image_main', '')";
						if (mysqli_query ($linkq, $insertphoto)) {
							echo ("- Inserted Image ($new_property_id) ($imagename) ($image_main)<br />\n");
						} else {
							echo ("- Image Insert Error\n");
						}
						
						$primaryimg++;

					} /* close the images loop */
					
					/* Loop the current epcsand add to the database and asign the property id */
					$totalepc = count($value['epcs']);
					for ($y = 0; $y < $totalepc; $y++) {
												
						$epcname = $value['epcs'][$y];	
						$insertepc = "INSERT into props_epcs VALUES ('', '$new_property_id', '$epcname')";
						if (mysqli_query ($linkq, $insertepc)) {
							echo ("- Inserted EPC ($new_property_id) ($epcname)<br />\n");
						} else {
							echo ("- EPC Insert Error\n");
						}

					} /* close the epcs loop */
					
					/* Loop the current pdfs and add to the database and asign the property id */
					$totalpdf = count($value['pdfs']);
					for ($v = 0; $v < $totalpdf; $v++) {
												
						$pdfname = $value['epcs'][$v];	
						$insertpdf = "INSERT into props_pdf VALUES ('', '$new_property_id', '$pdfname')";
						if (mysqli_query ($linkq, $insertpdf)) {
							echo ("- Inserted PDF ($new_property_id) ($pdfname)<br />\n");
						} else {
							echo ("- PDF Insert Error\n");
						}

					} /* close the pdfs loop */
					
					/* Loop the current floorplans and add to the database and asign the property id */
					$totalfloorplan = count($value['floorplans']);
					for ($v = 0; $v < $totalfloorplan; $v++) {
												
						$floorplanname = $value['floorplans'][$v];	
						$insertfloorplan = "INSERT into props_floorplans VALUES ('', '$new_property_id', '$floorplanname')";
						if (mysqli_query ($linkq, $insertfloorplan)) {
							echo ("- Inserted Floorplan ($new_property_id) ($floorplanname)<br />\n");
						} else {
							echo ("- Floorplan Insert Error\n");
						}

					} /* close the floorplans loop */
			
				} else {	
							
					echo ("Insert Error");
					
				} /* close the insert property */
			
				
			}  /* close the row count loop */
			
			
		} /* close the property exists loop */
		
	}
			

	/* close everything */
	curl_close($ch);	
	mysqli_close ($linkq);
	
?>

How to hide a webpage

$
0
0

I have a particular PHP file which is publicly located, however, I don't want anyone but me to access.  Below are my thoughts how to do so.  Please comment.

  1. Use an uncommon name, and definitely not index.php.
  2. Either include a file called index.html in the same directory, or set up Apache not to show them using Options -Indexes, or maybe both for good measure.
  3. Require some variable to be set to a given value in either the GET or POST array, and if not set, throw a 404 header and display the 404 missing file HTML.
  4. If user accesses page and is not logged on as determined by a session value, display a log-on page.
  5. Prevent indexing by either putting <meta name="robots" content="none" /> in the HTML, and using header("X-Robots-Tag: noindex, nofollow", true); in the PHP, or maybe both for good measure.
Seem reasonable?  Anything else?  Thanks

Error and success messages stored in SESSION

$
0
0

Is it a good practice to store error and success messages in SESSION?

 

Folder pages/giftCards
    ->index.php
    ->viewGiftCardCodes.php
    ->redeemGiftCard.php
    ->giftCards.php
    
index.php

<?php

if(defined('script') === FALSE){
	exit('Hacking attempt...');
}

if(loginCheck($userInfo) === FALSE){
	redirect('index.php?do=login&returnUrl='.$_SERVER['REQUEST_URI'], FALSE, TRUE);
}

if($configs['giftCardEnabled'] == 'no'){
	alert('This page is currently disabled.', 'index.php?do=home');
}

$action = isset($_GET['action']) ? $_GET['action'] : '';

switch($action){
	
	case 'redeemGiftCard';
	include 'pages/giftCards/redeemGiftCard.php';
	break;
	
	case 'viewGiftCardCodes';
	include 'pages/giftCards/viewGiftCardCodes.php';
	break;
	
	default:
	include 'pages/giftCards/giftCards.php';
	break;

}

?>

Default action giftCards
REDEEM BUTTON
.................

<?php
$action = '<input type="button" value="Redeem" onclick="location.href=\'index.php?do=giftCards&action=redeemGiftCard&id='.$row['id'].'&currency='.$row['currency'].'&amount='.$row['amount'].'&csrfKey='.$csrf->csrfKey().'&csrfToken='.$csrf->csrfToken().'\'">';
?>

.................


Action redeemGiftCard
.................
If success

<?php
$_SESSION['message']['1'] = 'You have successfully redeemed a gift card worth '.$row['currency'].$row['amount'].'';
redirect('index.php?do=testPage1', FALSE, TRUE);// Page, Refresh, Exit //
?>

If error

<?php
$_SESSION['message']['2'] = 'Database error. Please try again later!';
redirect('index.php?do=testPage1', FALSE, TRUE);// Page, Refresh, Exit //
?>

.................


Default action giftCards
.................

<?php
if(!empty($_SESSION['message']['1'])){
	$success = $_SESSION['message']['1'];
	unset($_SESSION['message']);
}
if(!empty($_SESSION['message']['2'])){
	$error = $_SESSION['message']['2'];
	unset($_SESSION['message']);
}

if(!empty($success)){
	
	print success($success);// HTML and success var //
	
}
if(!empty($error)){
	
	print error($error);// HTML and error var //
	
}
?>

.................

 

 

T_String Error

$
0
0

Hi, again,

 

I'm still working on my Guestbook, and finally realized that the code is antiquated! I'm now trying it with PDO_Mysqli.

 

I get an error:

 

Unexpected T_String in/hermes/bosnaweb o4ay/62713/ipg.jimmybryant.net/Guestbook.php.

 

I don't recognize anything; anyone see the problem?

 

Thanks MUCH,

 

Jimmy

Viewing all 13200 articles
Browse latest View live


Latest Images