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

Mysql + PHP Help needed for beginner.

$
0
0

Hei everyone. 
I am new on php development and i do not have budget on offering a course :( so i am trying to learn my self. 

 

i need some help on the following :

 

i want to create infopanel.php  where the script will get info from. 

 

For example if user logs in the  script will have to call :

<?php
include '/incl/infopanel.php' ;
?>

The info panel to load all details from  database:

<?php
$name='$myname';
$sur_name='$sname';
$age='$myage';
$country='$mycountry';
?>

So the info with my has to be from database .

 

so can some one help me how to call all information from database to a specific file that i will not have to  call always information on every page 

 

I hope i have been so clean with my request


Connecting to Database using php objects

$
0
0

Hi I am trying to connect to my database but i am having some problems where the server( WAMP) crashes and does not load this page. here is the php coding

<?php

	$db = new PDO("mysql:host=localhost;dbname=test;port=80", "root", "");
	var_dump($db);

when i run this no error comes the page doesnt load. anyone know why? when using PDO do i have to do some sort of configuration changes to wamp? i have even changed the directory of the file and still same issue. any suggestions would be wonderful.

Why is the frame not displaying when using "\n" tag

$
0
0

Hey Guys. I am using php to output to frames. When I add an "\n" tag of even a PHP_EOL the second frame shows blank. The weird thing is when I view the page source I can clearly see the HTML of both frames... Can anyone help me resolve this issue? Thanks!

$iframe =  "<iframe src='menu_new.php' width='65%'  name='menu' id='menu' title='Menu Frame' ></iframe>\n"; //iframe not working when adding the /n on this line


$iframe .= "<iframe src='menu-items.php' width='35%' name='menu-items' id='menu-items' scrolling='yes' noresize='noresize'  title='Menu Items Frame'></iframe>\n";


    echo $iframe;

Warning Message regarding

$
0
0

The following piece of POST header details to output to a file in JSON format returns the following error:

[/code]$params = array("user" => $enjin_id);

$query = http_build_query($params);
$contextData = array("method" => "POST", "header" => "Connection: close\r\n" . "Content-Length: " . strlen($query)."\r\n", "content" => $query );
$context = stream_context_create(array ( "http" => $contextData ));
 
$result = file_get_contents($url, FALSE, $context);[/code]

 

error:

 

file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded

 

 

Can anyone advise what I need to do to ensure that the process is correctly set, of which I assume I need to declare a MIME type and where it is needed?

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

$
0
0
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\websiteku\modul\laporan\laporan.php on line 48

 
$query2 = "SELECT count(*) as jum1 FROM transaksi WHERE nama_kategori = '$namaBidang' AND nama_bayar = Uang";
  $hasil2 = mysql_query($query2);
  $data3 = mysql_fetch_array($hasil2);
  $jumGol1 = $data3['jum1'];
help me guys, how i fix this problem ??

If else syntax - conditional link in form submit button

$
0
0

Hope someone can help put with this - I have inherited a site and am trying to modify some PHP that I am unfamiliar with. I have gotten so far with it, but still have a problem with it.

 

Its a page on an online store offering optional extras depending on the product. The products are furniture, so and there was an option to buy cushions for some. The change I am trying to make is to have an option for two different sizes of cushion depending on the product.

 

So there was a field 'cushions' in the product table, and a page 'accessories.php' that offered the option to add cushions.

 

I have added a new field 'cushions2' and a new page 'accessories2.php' to cover the new size of cushions.

 

The site is here, with this example product:

 

http://www.lloydloomonline.com/product.php?id=32

 

If you click 'Add to cart' the next page offers you the option to add custom paintwork.

 

If you enter something there, and click on 'Add colour to order' it works - i.e. the next page is the one offering the cushions.

 

But if you just click on 'No thank you, proceed with order' it just reloads the page - basically the URL isn't being puled through as it should be.

 

On that page the PHP at the top of the page looks like this:

 


<?php

session_start();
$page = "paintwork";
include("../includes/header.php");
include("../includes/db_open.php");
$sql =
  "SELECT p.*, c.`name` AS `categoryname` " .
  "FROM `products` p, `categories` c " .
  "WHERE p.`category` = c.`id` " .
  "AND p.`id` = '" . $_SESSION["basket"]["items"][$_REQUEST["id"]]["product"] . "'";
$result = mysql_query($sql) or die("Query failed : $sql at line " . __line__);
$row = mysql_fetch_assoc($result);
if (!empty($_POST)) {
    
    $_SESSION["basket"]["items"][$_POST["id"]]["paintwork"] = $_POST["colour"];
    
    if ($row["cushions"] == -1) {
        $url = "accessories.php?id=" . $_REQUEST["id"];
    } else if ($row["cushions2"] == -1) {
        $url = "accessories2.php?id=" . $_REQUEST["id"];
    } else if (!empty($row["glasstop"])) {
        $url = "glasstop.php?id=" . $_REQUEST["id"];
    } else {
        $url = "shopping_cart.php";
    }
?>
 
And the form with the input / submit looks like this:
 
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>" onsubmit="return validate(this)">
      <label for="quantity" style="float: left; width: 75px; margin: 0">COLOUR</label>
 <textarea name="colour" id="colour" style="float: left; height: 80px; width: 250px"></textarea>
      <img src="images/spacer.gif" class="clear" style="height: 10px" />
 <input type="submit" value="ADD COLOUR TO ORDER" id="submit" onmouseover="this.style.color = '#DBC87B'" onmouseout="this.style.color = '#FFFFFF'" style="float: left; margin-left: 75px; margin-right: 10px; width: 255px; padding-bottom: 3px; height: 23px" />
      <a href="<?php echo $url?>" style="float: left; color: #251717; background-color: #DBC87B">NO THANKYOU, PROCEED WITH ORDER</a>
     <input type="hidden" name="id" value="<?php echo $_REQUEST["id"]?>" />
</form>
 
Hope that makes sense - I think it must nearly be there, as all the conditional code seems to work, but the URL isn't being pulled through correctly in the form.
 
If anyone could have a look and hopefully get megabuck on track, I'd really appreciate it.
 
Thank you.
 
 

Creating/Using a Cookie to remember user preference

$
0
0

I'm an experienced programmer with several languages (COBOL, REXX, Java, Javascript, etc.) under my belt over many years but I know very little about PHP. I dabbled in it a bit a year or two back and got it to do what I wanted to do but I'm not sure how to do what I currently need.

 

A bit of context: I have designed a website where the user can choose between various page styles; each style invokes different CSS to give them a different visual experience of the site. They can select the style they want via View/Style in Internet Exploder and View/Page Style in Firefox  but that preference is only remembered as long as they're on that page. As soon as they move to another page on the site, they have to choose the alternate style again or live with the default style. I want them to be able to select that preference ONCE, the store it in a cookie specifically for them, then keep using that style every time they visit the site. (Naturally, I want them to be able to change the style and then remember the new style as well.) There will be many visitors and each will want that same capability. I currently don't require any login to the site. (I'm toying with password-protecting some of the site down the road but that's not a factor in this page style thing that I'm talking about here.

 

Now, my questions.

 

I've found a variety of short articles describing how to use setCookie() to create the cookie (and delete it later) and getCookie() or the newer echo $_COOKIE["name"] to determine the cookie value. However, I am NOT seeing anything that says where I put the code to set and/or read the code within my web pages. I would really appreciate an explanation of that! I expect to write short fragments of php code to do those jobs which I will then imbed within my web pages via SSI (Server Side Includes). Is that reasonable or is there a better way?

 

Also:

1. When the user clicks on the desired Style in the View/Style menu, how do I detect what choice they made?

2. Should the name of the cookie be something like "pageStyle" or should it be something that uniquely identifies the user so that the right cookie is retrieved when the come back? If the latter, what value should I use and how should I obtain it? I assume that something unique about the user obtained from their headers is far better than displaying a dialog and asking them for some unique identifier.

 

I'd rather stay away from Javascript in any of this functionality since I can't rely on it being turned on.

 

One quick aside while I'm here. Does  anyone know how to change the page style if visitors use Google Chrome or Opera? I can't even FIND options for changing the page style in my copies of those two browsers and both are current versions. Do they not support differing page styles at all or do they just hide the technique to choose the style very effectively?

 

--

Henry

Query using PDO Undefined variable error

$
0
0

Hi i have created a query where i want some columns to be retrieved. i get these 2 errors and i dont understand why.

 

Notice: Undefined variable: db

Fatal error: Call to a member function query() on a non-object in 

 

 

this is my query

function get_products_all() { 

$connect = get_connected_db();

try {
	  $results = $db->query("                                  ***** error on this line****
                SELECT  id, product, description, price, picc
                FROM products ORDER BY id DESC
				");
		
    } catch (Exception $e) {
        echo "Data could not be retrieved from the database.";
        exit;
    }

    $result = $results->fetchALL(PDO::FETCH_ASSOC);
	
	return $result;
}

what am i doing wrong?


Pagination Sending Me Crazy

$
0
0

Hi Guys and Girls,

 

I'm having a bit of a hard time getting some pagination working.  I have a script using CURL getting JSON results via a HTTP API.  This is also used in a Wordpress Installation.

 

The API call has a maximum of 50 records returned but allows pagination.  

 

What I can't seem to get right is actually getting this to work.

 

Below is the code that I'm using:

<?php
//functions relating to wordpress go here:
//----------------------------------------
$bg_colors = array('green', 'orange', 'blue', 'yellow', 'red', 'black');
//----------------------------------------
//End functions relating to wordpress

// Start PetRescue PHP/API Code
//----------------------------------------
// Open CuRL/JSON Stuff

$ch = curl_init();
$category=$_GET['category'];
$url="http://www.xxx.com.au/api/listings?token=xxxtokenxxx&group_id=xxx&species=".$category;
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'X-some-API-Key: xxxtokenxxx',
));
$json = json_decode(curl_exec($ch), true);

//Pagination stuffs
if($_GET['page'])
{
$page=substr($_GET['page'],1);
echo 'page'.$page;
}

// Functions relating to the Echo Code

foreach($json['listings'] as $listing)
{
$short_personality=substr($listing['personality'],0,500);
$peturl="http://xxx.org.au/pet-info/?petid=".$listing['id'];
$medium_photo=$listing['photos'][0]['large_340'];
$gallery_first=$listing['photos'][0]['xlarge_900'];
$gender_class=strtolower($listing['gender']);
$breed_class=strtolower($listing['species']);
$name=($listing['name']);
$unique_gallery_name="lightbox['.$inc.']";
    $inc++;
foreach($listing['photos'] as $photosthumb)
          {
            $photo_thumb_large=$photosthumb["xlarge_900"];
			$photo_thumb_hidden=$photosthumb["xlarge_340"];
		  }
$rand_background = $bg_colors[array_rand($bg_colors)];
	
// General IF/AND/ELSE Statements to refine the Echo Output
if($listing['photos'] == null) {
	$medium_photo="http://xxx.org.au/wp-content/themes/xxx/images/photo_coming_soon.png";
}
if($listing['desexed'] == "Yes") {
	$desexed="yes";
}
else {
	$desexed="no";
}
if($listing['vaccinated'] == "Yes") {
	$vaccinated="yes";
}
else {
	$vaccinated="no";
}
if($listing['wormed'] == "Yes") {
	$wormed="yes";
}
elseif($listing['wormed'] == "No") {
	$wormed="no";
}
else {
	$wormed="no";
}
if($listing['heart_worm_treated'] == "Yes") {
	$heart_worm_tested="yes";
}
elseif($listing['heart_worm_treated'] == "No") {
	$heart_worm_tested="no";
}
else {
	$heart_worm_tested="no";
}
if($listing['species'] == "Dog") {
	$adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-dogs/?dog_name=$name";
	$hwt="list-$heart_worm_tested";
}
elseif($listing['species'] == "Cat") {
	$adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-cats/?cat_name=$name";
	$hwt="list-hwt-hidden";
}

// Echo the output

echo'<div class="animal">
		<div class="animal-image">
<a class="size-thumbnail thickbox" rel="'.$unique_gallery_name.'" href="'.$gallery_first.'">
				<img src="'.$medium_photo.'" class="image-with-border" alt="">
				<div class="border" style="width: 340px; height: 340px;">
					<div class="open"></div>
				</div>
			</a>
		<div class="item-title-bg '.$rand_background.'">
				<h2 class="entry-title"> '.$listing['name'].'</h2>
				<div class="animal-adopt-button">
	<a href="'.$adoption_enquiry_link.'" style="background-color: #575757; border-color: #494949; background-position:5px 0;" class="button medium"> Enquire about '.$name.'</a>
				</div>		
			</div>		
		</div>		
		<div class="animal-thumbnail hidden">
<a class="lightbox" rel="'.$unique_gallery_name.'" href="'.$photo_thumb_large.'">
					<img class="animal-thumbnail" src="'.$photo_thumb_hidden.'" >
					</a>
		</div>		
<div class="animal-content">
	<div class="animal-left">
		<ul class="animal-list">
			<li class="list-sex-'.$gender_class.'">'.$listing['gender'].'</li>
			<li class="list-breed-'.$breed_class.'">'.$listing['breeds_display'].'</li>
			<li class="list-age">'.$listing['age'].'</li>
			<li class="list-fee">'.$listing['adoption_fee'].'</li>
		</ul>
	</div>
<div class="animal-right">
		<ul class="animal-list">
			<li class="list-'.$desexed.'">Desexed?</li>
			<li class="list-'.$vaccinated.'">Vaccinated?</li>
			<li class="list-'.$wormed.'">Wormed?</li>
			<li class="'.$hwt.'">Heart Worm Tested?</li>
		</ul>
</div>
<div class="animal-full">
		<ul class="animal-list">
			<li class="list-description">'.$listing['personality'].'</li>
		</ul>
</div></div>
<div class="clearer"></div>
</div>
<div class="delimiter"></div>';
// Close the CURL
}
echo'
<div class="pagination footer-pagination">
<nav class="pagination">
<div class="pages">';
for($i=1;$i<=$json['total_pages'];$i++)
{
$this_page=substr($_GET['page'],1);
$active="";
if($i==$this_page)
{
$active="active";
}
echo '
<span class="page'. $active.'">
<span class="number">
<a rel="prev" href="http://xxx.org.au/pet/?category=dog&page='.$i.'"> '.$i.'</a>
</span>
</span>
</div>
</nav>
</div>';
curl_close($ch);
}
?>

This is a sample of the JSON results:

{"listings":[{"adoption_fee":"$200 ","adoption_process":"For cats, please fill out our <a href=\"http://xxx.org.au/pre-adoption-form-cats/\">Pre-Adoption Questionnaire - Cats</a>.\r\n\r\nFor dogs, please fill out our <a href=\"http://xxx.org.au/pre-adoption-form-dogs/\">Pre-Adoption Questionnaire - Dogs</a>.\r\n\r\nFor more information on our Adoption Process, please visit this <a href=\"http://xxx.au/our-adoption-process/\">link</a>.\r\n\r\nPlease make sure that you are familiar with our <a href=\"http://xxx.org.au/adoption-agreement/\">Adoption Agreement</a> as it has recently changed.\r\n\r\nFor more information on any of our animals, please <a href=\"http://xxx.org.au/contact-us/\">Contact Us</a>.","age":"2 years 5 months","breeds":["Domestic Long Hair"],"breeds_display":"Domestic Long Hair","coat":"Long","contact_name":null,"contact_number":null,"contact_preferred_method":"Email","created_at":"30/1/2014 21:36","date_of_birth":"20/2/2012","desexed":true,"foster_needed":false,"gender":"Female","group":"xxx","heart_worm_treated":null,"id":273191,"interstate":false,"last_updated":"5/8/2014 12:20","medical_notes":"","microchip_number":"","mix":false,"multiple_animals":false,"name":"Helena HC13-394","personality":"Stunning Helena!\r\n\r\nThis beautiful girl is looking for a home that is fairly relaxed. She is not happy about sharing her current foster home with some bossy cats, she likes to be the princess of her realm.\r\n\r\nShe is very affectionate, and when it is quiet she will come and have a big smooch around our legs, and purr her pretty little purr. \r\n\r\nShe is somewhat timid to start with, but enjoys the company of people and once she trusts, she's a very special companion.\r\n\r\n","photos":[{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_70x70_96020.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_130x130_96020.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_340x340_96020.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_900x900_96020.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_70x70_d2d41.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_130x130_d2d41.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_340x340_d2d41.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_900x900_d2d41.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_70x70_982c6.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_130x130_982c6.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_340x340_982c6.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_900x900_982c6.jpg"}],"senior":false,"size":null,"species":"Cat","state":"WA","vaccinated":"Yes","wormed":"Yes"},

And the pagination details are at the bottom of the JSON response:

"page":"1","per_page":"50","total_pages":"6"

The issue I get with all of this, is when calling the PHP file again, it's just returning the first page of results and not the second page.

 

Any help would stop me from eating my own eyeballs, as I've been staring at this for hours!

 

Cheers,

 

Dave

Time based events in PHP

$
0
0

Hi peps,

I am trying to write a script that allows for events to be executed at any given time that user gives it like 
if the user wants it at 2 am the event will execute at that given time

i read some answer they say use cron 
but im using windows how to do it :)??

 

Encryption

$
0
0

Hi Guys,

 

First off, not sure if this is the correct area to post. My question is a little bit mixed, including SQL and PHP.

 

I'm building a basic private messaging system, and planned to use PHP, SQL for the storage, and a little bit of JS on the client. I'm a little confused when it comes to encryption though. My understanding with user password encryption is that the password is stored in the database as a hash, and then a user sent password is compared to the original hash for verification. I've implemented this successfully using password_verify() and password_hash() functions, and I'm pretty sure it's working fine.

 

However, my big question is in regards to the storage of message data. As far as I can tell, this system won't work, it's really only suitable for password verification because the hash can't really be reverted to the original data, it can only be compared? How should I go about encrypting message data? Is it possible? If I open up a SQL database containing private message data on a server, I don't want to be able to read the contents.

 

Any help would be greatly appreciated! :)

About 2:1 banner exchange sites and bots

$
0
0

Hi, I making a banner exchange script. Members will have to place a banner code on their sites to make banners appear. Some members might cheat by using bots to refresh the page to gain impressions and to waste other members impressions so i wanted to know if bots have ip addresses? because i want to only give member impressions if their visitors have ip. What are the other things i can do to check if members are cheating?. Thanks

 

$ip=$_SERVER['REMOTE_ADDR'];

Need help using the array_udiff()

$
0
0

Hey Guys. I am trying to understand how the array_udiff works but  I am having a hard time understanding why the call back function returns a interger? How does that return value preform the camparison?

 

For example in the code below, what does the return 0 , or return 1 or -1 have anything to do with the comparison? Thank you in advance!

function myfunction($a,$b)
{
if ($a===$b)
  {
  return 0;
  }
  return ($a>$b)?1:-1;
}

$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"blue","b"=>"black","e"=>"blue");

$result=array_udiff($a1,$a2,"myfunction");
print_r($result);

display while loop result 3 per row

$
0
0

Hi, I would like to ask, how to display the while loop result 3 per row with the following code below:
 

$startDate = strtotime($datefrom);  
$endDate = strtotime($dateto);  
$date = $startDate;  
 
while( $date <= $endDate) {
echo  "<input type='checkbox' name='date'>";
echo date('d-m-Y', $date) .' ';
$date = strtotime('+1 day', $date);
}
 
Anyone can assist me on this? Thank you.

php code not working on godaddy hosting but working fine on linux vps

$
0
0

i dont understand what is wrong plz help me.

here is code

$name = "img/".rand(1,9999999).".png";
$myFile = $name;
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $html;
fwrite($fh, $stringData);
fclose($fh);
$file=$name;
$fst=file_get_contents($file);
$im=imagecreatefromstring($fst);
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_NEGATE);
//Convert to Grey Scale
for($i=0;$i<123;$i++){
for($j=0;$j<50;$j++){
$px=imagecolorat($im,$i,$j);
if($px<0x303030){
imagesetpixel($im,$i,$j,0);
}else{
imagesetpixel($im,$i,$j,0xffffff);
}
}
}
$database = unserialize(@file_get_contents("db.txt"));
if($database === false) $database = array();
// modify the database if needed
if($_SERVER['REQUEST_METHOD'] == 'POST'){
	if($_POST['submit'] == 'Add')
		$database[$_POST['ident']] = substr($_POST['letter'], 0, 1);
	if($_POST['submit'] == 'Del')
		unset($database[$_POST['ident']]);
	if($fh = @fopen('db111.txt', 'w+')){
		fwrite($fh, serialize($database));
		fclose($fh);
}
}else{
$newimage = true;
}
$width   = 130;
$height  = 40;
$captcha_gridstart   =1;
$captcha_gridspace   =2;
$letters = findletters($im, $width, $height, $captcha_gridstart, $captcha_gridspace);
$count   = count($letters);
$cellw   = ($count > 0) ? intval(100 / $count) : 0;
//dispeckle the image and GET co-ordinates of the characters of captcha image and return them. 
function findletters($image, $width, $height, $gridstart, $gridspace){
	$offsets  = array(); $o = 0;
	$atstartx = true;
	for($x = 0; $x < $width; $x++){
		$blankx = true;
		for($y = 0; $y < $height; $y++){
			if(imagecolorat($image, $x, $y) == 0){
				$blankx = false;
				break;
			}
		}
		if(!$blankx && $atstartx){
			$offsets[$o]['startx'] = $x;
			$atstartx = !$atstartx;
		}else if($blankx && !$atstartx){
			$offsets[$o]['endx']   = $x;
			$atstartx = !$atstartx;
			$o++;
		}
	}
	$count = $o;
	for($o = 0; $o < $count; $o++){
		for($y = 0; $y < $height; $y++){
			$blanky = true;
			for($x = $offsets[$o]['startx']; $x < $offsets[$o]['endx']; $x++){
				if(imagecolorat($image, $x, $y) == 0){
					$blanky = false;
					break;
				}
			}
			if(!$blanky){
				$offsets[$o]['starty'] = $y;
				break;
			}
		}
		for($y = $height-1; $y > $offsets[$o]['starty']; $y--){
			$blanky = true;
			for($x = $offsets[$o]['startx']; $x < $offsets[$o]['endx']; $x++){
				if(imagecolorat($image, $x, $y) == 0){
					$blanky = false;
					break;
				}
			}
			if(!$blanky){
				$offsets[$o]['endy'] = $y;
				break;
			}
		}
	}
	for($o = 0; $o < $count; $o++){
		$offsets[$o]['ident'] = "";
		for($x = $offsets[$o]['startx'] + $gridstart; $x < $offsets[$o]['endx']; $x += $gridspace){
			for($y = $offsets[$o]['starty'] + $gridstart; $y < $offsets[$o]['endy']; $y += $gridspace){
				$offsets[$o]['ident'] .= ((imagecolorat($image, $x, $y) == 0) ? "0" : "1");
				#echo $offsets[$o]['ident'].'<br>';
			}
		}
	}
	return $offsets;
}
$a="";
foreach($letters as $letter){
$asciiletter = $database[$letter['ident']];
if(!empty($asciiletter)) {
$a.=$asciiletter;
}
}

PHP to create new .js file for each registered user

$
0
0
Hello everybody,

This is my first post here and I am beginner in PHP world in terms of writing the code to serve my own purposes.

Well I am building a web app and basically it's a calendar which pulls information from .js file. Now I have thinking for the past couple of days how can I accomplish that each user that registers on the site manipulates its own .js file because information from .js file will be shown on calendar.

Let me tell you how it's currently set up:

1. JavaScript file with particular static name is called under the script that is placed on index.php and the data is displayed on the page itself.

So I would love to have is set it up like this:

1. Index page contains login form - Each registered/logged in user will have its own session
2. User registers and based on username/email new .js file is created out of a blank template and it is named based on user's username
3. user is then redirected to the calendar index which contains javascript that cals out that appropriate .js file based on the what user is logged in and displays data to the calendar

I am not sure if that is doable with PHP or not but that's my thinking how it can be done if it's doable. I am open for any kind of suggestions how all this can be put together and if you do have better ideas I would love to hear from you.

override script generated table data

$
0
0

Hi there,

 

I have a timetable plugin that shows booking entries.

The times are generated dynamically by the plugin.

 

Now I have the situation where I need to override the automatically created time that shows in a table row.

Here's the HTML code generated by the plugin:

 <tr class="row_12">
      <td class="tt_hours_column">00:00</td>

Ist it possible to have a simple PHP script that does the following (please forgive my noobiness) ?

 

if table row is "row_12" then insert "my own pre-defined time"

 

Please don't hate on me, I know I have not the slightest idea about php. I'm just wondering how to solve my plugin problem and if PHP is the right way to do it.

 

I highly appreciate any feedback from you guys :)

renaming files form on local pc

$
0
0

I wrote this script to rename my many tv series I have on my pc, works by finding a string in the file name and replacing it

the script works fine until I want to replace the file name with something that is also in the path

file = band ep01.avi

path = j:\media\ TV shows\Band of Brothers\

 

so if I try to change "Band" to "Band of Brothers" the path changes as well 

is there a way I can change the code so it dosent effect the path ??

<?php

$path = 'J:\media\TV shows\Band of Brothers';

foreach(glob($path.'/*.*') as $filename){         
              echo $filename."</BR>";
}

?> 
 <table align="center" width="200px" border="0" cellspacing="1" cellpadding="3">
 <form name="form1" method="get" action="mov.php">
 <tr>
 <td colspan="3"><strong> </strong></td>
 </tr>
 <tr>
 <td width="71">Replace</td>
 <td width="6">:</td>
 <td width="301"><input name="rep" type="text" id="rep"></td>
 </tr>
 <tr>
 <td>With</td>
 <td>:</td>
 <td><input name="with" type="text" id="with"></td>
 </tr>
 <tr>
 <tr>
 <td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
 </tr></form>
 </table>
 
<?php
                if (isset($_GET["rep"])) {
                $rep1=$_GET['rep'];
                }
                if (isset($_GET["with"])) {
                $with1=$_GET['with'];
                }
                
                
 foreach(glob($path.'/*.*') as $filename){        
              $strip =  str_replace($rep1, $with1, $filename);
              echo $strip."</br>";  
              rename($filename,$strip);
}
    
?>

Redirecting My URL after submitting my contact form

$
0
0

Hi, 

 

i have a contact form with this code: 

<?php
if(isset($_POST['submit']))
{
$flag=1;
if($_POST['yourname']=='')
{
$flag=0;
echo "Please Enter Your Name<br>";
}
else if(!preg_match('/[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*/',$_POST['yourname']))
{
$flag=0;
echo "Please Enter Valid Name<br>";
}
if($_POST['email']=='')
{
$flag=0;
echo "Please Enter E-mail<br>";
}
else if(!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_POST['email']))
{
$flag=0;
echo "Please Enter Valid E-Mail<br>";
}
if($_POST['subject']=='')
{
$flag=0;
echo "Please Enter Subject<br>";
}
if($_POST['message']=='')
{
$flag=0;
echo "Please Enter Message";
}
if ( empty($_POST) )
{
print 'Sorry, your nonce did not verify.';
exit;
}
else
{
if($flag==1)
{

wp_mail(get_option("admin_email"),trim($_POST[yourname])." sent you a message from StraightForwardLegal.com".get_option("blogname"),stripslashes(trim($_POST['message'])),"From: ".trim($_POST['yourname'])." <".trim($_POST['email']).">\r\nReply-To:".trim($_POST['email']));
echo "Thank you for contacting us!<br>  We have received your email. <br> One of our Workers' Compensation Attorneys <br> will be in touch with you as soon as possible";
header ("location: http://www.straightforwardlegal.com"); exit;
}
}
}
?>

and then, 

<div class="frontForm">
<form method="post" id="contactus_form"><span style="font-size: 12px;>
                    <div class="left">
Name*:<br><input type="text" name="yourname" id="yourname" rows="1" maxlength="35"><br>
Email*:<br><input type="text" name="email" id="email" rows="1" value=""><br>
Phone*:<br><input type="text" name="subject" id="subject" rows="1" columns="8" style= "max-height: 18px; min-height: 18px;" value="" /></td></tr>
</div>
 <div class="right" style="margin-top: -120px;"/>
Message*:<textarea name="message" id="message" rows="5" style="height: 90px;"></textarea><br><br>
<input type="submit" name="submit" id="submit" value="Send"/></span>
</form>
           
            </div>
        </div>

    </div>
</div>

I used 

header ("location: http://www.straightforwardlegal.com"); exit;

but, it does not work.  After submitting my contact form, the user gets taken to my contact page instead of going to my home page?  I was wondering if someone could let me know what I have done wrong?

 

Thank you, 

 

Megan 

Keeping a value stored in a variable after reloading the class

$
0
0

Currently, I'm trying to write a contact form, and perhaps I'm overcomplicating it, but I have a public variable called $EquationAnswer that stores the answer to the Captcha method (randomised maths question) and whenever the page reloads, it creates a new instance of the Contact class, which then erases the value that has been stored in that variable.

 

What I'm trying to achieve is keeping the value stored even after a new instantiation of the class. I remember from a class at University that static was a way to do this, but this was in C#.

<?php

class Contact
{
	public $EquationAnswer;

	public function CaptchaCreation()
	{
		$SignArray = array('+', '×', '-');

		$NumberOne = rand(1, 9);
		$NumberTwo = rand(1, 4);

		if($NumberOne < $NumberTwo)
			$SignIndex = rand(0, 1);
		else
			$SignIndex = rand(0, 2);

		$Sign = $SignArray[$SignIndex];

		$EquationString = $NumberOne." ".$Sign." ".$NumberTwo;

		switch($Sign)
		{
			case "+":
				$Answer = $NumberOne + $NumberTwo;
				break;
			case "-":
				$Answer = $NumberOne - $NumberTwo;
				break;
			case "×":
				$Answer = $NumberOne * $NumberTwo;
				break;
		}

		$this->EquationAnswer = $Answer;

		return $EquationString;
	}

	public function EchoContactForm()
	{
		$CaptchaMessage = $this->CaptchaCreation();

		echo "<form method='POST' action=''>\n\n";
		echo "\t\t\t\t\t<table>\n\n";
		echo "\t\t\t\t\t\t<tr><td>Name: </td><td><input type='text' name='name' /></td></tr>\n";
		echo "\t\t\t\t\t\t<tr><td>Email: </td><td><input type='text' name='email' /></td></tr>\n";
		echo "\t\t\t\t\t\t<tr><td>Subject: </td><td><input type='text' name='subject' /></td></tr>\n";
		echo "\t\t\t\t\t\t<tr><td>Message: </td><td><textarea rows=5 name='message'></textarea></td></tr>\n";
		echo "\t\t\t\t\t\t<tr><td>What is: ".$CaptchaMessage."?</td><td><input type='text' name='captcha' /></td><td></td></tr>\n";
		echo "\t\t\t\t\t\t<tr><td colspan=2 style='text-align: right'><input type='submit' name='submit' value='Send' /></td></tr>\n\n";
		echo "\t\t\t\t\t</table>\n\n";
		echo "\t\t\t\t</form>\n";
	}

	public function ContactFormValidation($Name, $Email, $Subject, $Message, $CaptchaInput, $CaptchaAnswer)
	{
		echo $CaptchaAnswer;

		$ErrorsArray = array();

		if(strlen($Name) == 0)
			array_push($ErrorsArray, "You must provide a name.");
		if(strlen($Email) == 0)
			array_push($ErrorsArray, "You must provide an email.");
		if(strlen($Message) == 0)
			array_push($ErrorsArray, "You must provide a message.");
		if(strlen($CaptchaInput) == 0)
			array_push($ErrorsArray, "You must provide an answer to the maths question.");
		if($CaptchaInput != $CaptchaAnswer)
			array_push($ErrorsArray, "Incorrect captcha answer.");

		if(count($ErrorsArray) > 0)
		{
			echo "There are ".count($ErrorsArray)." Errors: <br />";

			foreach($ErrorsArray as $E)
				echo $E."<br />";
		}
		else
		{
			return true;
		}
	}
}

?>

^ That's the Contact class, and the main function that I want to focus on is the last one, "ContactFormValidation()".

 

From the contact form page (which is within a template), I want it to send the EquationAnswer variable to that function so that it can compare what the user has input.

<?php

//Instantiate the contact class
include './inc/PHP/classes/ContactClass.php';
$ContactClass = new Contact;

if(!isset($_POST['submit']))
{
	$ContactClass->EchoContactForm();
}
else
{
	$NameInput = $_POST['name'];
	$EmailInput = $_POST['email'];
	$SubjectInput = $_POST['subject'];
	$MessageInput = $_POST['message'];
	$CaptchaInput = $_POST['captcha'];
	$CaptchaAnswer = $ContactClass->EquationAnswer;

        //Tried echoing out what is in the variable but it produces nothing because the contact class is a new instance.
	//echo $CaptchaAnswer;

	if($ContactClass->ContactFormValidation($NameInput, $EmailInput, $SubjectInput, $MessageInput, $CaptchaInput, $CaptchaAnswer) == true)
	{
		//Mail function
	}
}

?>

Any help would be appreciated.

 

Cheers.

Viewing all 13200 articles
Browse latest View live