PHP

120K

Solutions

33K

Contributors

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

Share tech news, updates, or what's on your mind.

Sign up to Post

When I wanted to learn ASP or ASP.NET I obtained a MS hosting account.
I went to Bluehost to set up an account to learn PHP.

How would I go about this with Python?
0
HTML5 and CSS3 Fundamentals
LVL 13
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Dear Experts,
I use PHP 7.3.

I use a SMS service which is working with CURL, however, in this CURLOPT_POSTFIELD I have 3 diffrent messages.
Obviously I would like to send only my mesaj which is $mesaj

$gonderen is my name
$gsmno is my mobile number
$mesaj is my message

this below Postfield has 3 messages with 3 diffrent receivers. I want to send the first message which is mine.
I couldn't properly cut it. Help is needed. Thank you.

CURLOPT_POSTFIELDS => "{\r\n\t\"bulkId\":\"BULK-ID-123-xyz\",\r\n\t\"messages\":[\r\n\t\t{\r\n\t\t\t\"from\":\"".$gonderen."\",\r\n\t\t\t\"destinations\":[\r\n\t\t\t\t{\r\n\t\t\t\t\t\"to\":\"".$gsmno."\",\r\n\t\t\t\t\t\"messageId\":\"MESSAGE-ID-123-xyz\"\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"to\":\"45644564567\"\r\n\t\t\t\t}\r\n\t\t\t],\r\n\t\t\t\"text\":\"".$mesaj."\",\r\n\t\t\t\"flash\":false,\r\n\t\t\t\"language\":{\r\n\t\t\t\t\"languageCode\":\"TR\"\r\n\t\t\t},\r\n\t\t\t\"transliteration\":\"TURKISH\",\r\n\t\t\t\"intermediateReport\":true,\r\n\t\t\t\"notifyUrl\":\"https://www.example.com/sms/advanced\",\r\n\t\t\t\"notifyContentType\":\"application/json\",\r\n\t\t\t\"callbackData\":\"DLR callback data\",\r\n\t\t\t\"validityPeriod\": 720\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"from\":\"41793026700\",\r\n\t\t\t\"destinations\":[\r\n\t\t\t\t{\r\n\t\t\t\t\t\"to\":\"41793026785\"\r\n\t\t\t\t}\r\n\t\t\t],\r\n\t\t\t\"text\":\"A long time ago, in a galaxy far, far away... 

Open in new window

0
I am building a website.  I noticed that when entering text in the contact form from mobile phones there is this odd delay, anywhere from 1-10 seconds before the letters or words I typed appears.  On my computer and laptop it is fine, no lag.  On my iphones 10 and 7, I tried safari, chrome, and edge...they all do it.  

It's a fairly straight forward contact form, uses php on the back end.  The server resources are good. Internet connection is fast, just wondering what would possibly cause this lag only on mobile.

Not really sure where to start.  Should I be looking for in CSS config?
0
I am very new to PHP, learning dependency Injection.  I have created two classes Author and Question and have injected Author into question.

I want to get echo out of it "What is your favorite Book John Public"

Here is my coded right now

<?php

class Author {
    private $firstName;
    private $lastName;
     
    public function __construct($firstName, $lastName) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
 
    public function getFirstName() {
        return $this->firstName;
    }
 
    public function getLastName() {
        return $this->lastName;
    }
	
}
 
class Question {
    private $author;
    private $question;
 
    public function __construct($question, Author $author) {
        $this->author = $author;
        $this->question = $question;
    }
 
    public function getAuthor() {
        return $this->author;
    }
 
    public function getQuestion() {
        return $this->question;
    }
}

$AuthorObj = new Author("John","Public");

$QuestionObj = new Question("What is your favorite book ",$AuthorObj);

echo $QuestionObj->getQuestion();

Open in new window

0
Hi Experts

Could you check what is needed to be adjusted on this PHP code to make it generates a JSON as an array under an object (not another separated object) ?

Acordingly to
//------------------------------------
// -- Actual JSON obtained by the code
//------------------------------------
{
		"name": "Wagner XXXXXX",
		"nickname": "",
		"email": " ",
		"roles": [
			"professional"
		],
		"internal_id": "CONS:-",
		"cellphone": "11941163485",
		"tags": [
			"COOP:MULTISA",
			"FUNC:Aux. Enfermagem",
			"TIPO_PAGAMENTO:",
			"VALOR:R$0"
		],
		"gender": "masculino",
		"send_invite_when_submit": true,
		"shifts": {
			"date": "2012-12-16",
			"period_name": "Aux. Enfermagem",
			"tags": [
				"ESC:"
			]
		}
	}, // Not to close the object
	{  // Just open an array of shifts objects here.
		"shifts": {
			"date": "2012-12-18",
			"period_name": "Aux. Enfermagem",
			"tags": [
				"ESC:"
			]
		}
	},
	{
		"shifts": {
			"date": "2012-12-20",
			"period_name": "Aux. Enfermagem",
			"tags": [
				"ESC:"
			]
		}
	},
	
//---------------
// -- Needed JSON
//---------------	
{
		"name": "Vinicius",
		"nickname": "Vinicius",
		"email": "vinicius@teste.com",
		// se trabalha na escala, é professional,
		// se é gestor (escalista), é manager
		"roles": [
			"organizador",
			"plantonista"
		],
		"internal_id": "c2917",
		"cellphone": "11-988888889",
		"tags": [
			"tag1", "tag2", "COOPERATIVA-NOME_COOPERATIVA"
		],
		"gender": "male",
		"send_invite_when_submit": true,
		

Open in new window

0
Attempting to update code to work in PHP 7.2 - The code works fine in PHP 5.6 - This is a custom THEME in WordPress BTW

One area of the app adds a log entry for almost every action/area visited.
Receiving ERROR -  [] operator not supported for strings  - to which I believe I have the solution by identifying the variable as an array.

function czar_add_log_callback(){
    check_ajax_referer( 'czar-info-fetch', 'security' );
    $data = array( 'message' => 'Failed', 'html' => 'Failed' );
    
    if( isset($_POST['postid']) && isset($_POST['type']) ){
	
        if( is_user_logged_in() ){
            global $current_user;
            wp_get_current_user();
            $user_info = get_userdata($current_user->ID);
            
            $lead_logs = get_post_meta( $_POST['postid'], 'lead_logs', true ); //THIS IS WHERE THE VAR NEEDS TO BE ASSIGNED AS AN ARRAY
            $timezone = get_field('time_zone' , get_id_by_slug('settings'));
            $curdate = new DateTime('NOW', new DateTimeZone($timezone));
            
            $lead_logs[] = array(      // HERE IS WHERE THE ERROR IS CALLED
                'type' => $_POST['type'],
                'date' => $curdate->format('m/d/Y h:i:s a'),
                'user' => $user_info->user_login
            );
            
            update_post_meta( $_POST['postid'], 'lead_logs', $lead_logs );
            
            $data = array( 'message' => 'Success', 'html' => 'Success' );
        }
	
    }
    
 

Open in new window

0
Hi Experts

Could you point what must to be changed on this PHP code to make object values to be reasigned ?

Accordingly to:
<?

		if ( $bd1->qBD($query6) )
		{
	
			while ($reg6 = $bd1->obtenerRegA())
			{
				
				//print_r('---------------------');
				//print_r($reg6['nome_completo']);
				//print_r('---------------------');
				
				$id_prof = $reg6['id_profissional'];

				if($id_prof = $id_prof_anterior)
				{
						
					//----------------------------------------------
					$obj_sh = array(
							'date' => $reg6['data_entrada_realizada'],
							'period_name' => $reg6['tipo_profissional'],
							'tags' => array('ESC:' )
						);
					
					$data = $obj_sh;
					//----------------------------------------------
					
					$ct++;	
						
						
				}
				else
				{
						// Obtém estas informações apenas na 1.a passagem
						$name =  $reg6['nome_completo'];
						$nickname='';	
						$email= $reg6['email_profissional'];
						$cellphone= $reg6['celular_profissional'];
						$cooperativa = $reg6['cooperativa'];
						$tipo_profissional = $reg6['tipo_profissional'];
						$valor_prof =  $reg6['valor_prof'];
						$gender = $reg6['sexo_profissional'];

						//----------------------------------------------
						$obj_sh  = array(
								'date' => $reg6['data_entrada_realizada'],
								'period_name' => $reg6['tipo_profissional'],
								'tags' => array('ESC:' )
							);
				
						$data = $obj_sh;
						//----------------------------------------------
			

Open in new window

0
I am using sequelize to upload to a mysql database.  I am able to upload the image but I am not able to load the other fields which are all null. I keep getting a "TypeError: Cannot read property 'path' of undefined" error.

Please see the sequelize log below as it is only capturing the "Id" and the "Image."


Executing (default): INSERT INTO `stores` (`ID`,`Image`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?);
Station record was successfully created: [object SequelizeInstance:stores]

router.post("/station", (req, res) => {
upload(req,res,(err)=>{
if(err){
        res.send(err);
        }else{
  let newStation = req.body.Station;
  let newImage = req.file.path.replace(/\\/g, "/");
  let newAddress = req.body.Address;
  let newMonthlycstoresales = req.body['Monthly C-Store Sales'];
  let newOperator = req.body.Operator;
  let newTopsku = req.body['Top SKU'];

  let data = {Station: newStation, Image: newImage, Address: newAddress, ['Monthly C-Store Sales']: newMonthlycstoresales, Operator: newOperator, ['Top SKU']:newTopsku };

Store.create(data)
              .then(stores => {
                 console.log('Station record was successfully created: ' + stores);
                 res.send(req.file);
             })
              .catch(err => {
                 res.send('error: ' + err)
             
                })
               }
              })
            })

I am using multer to upload the files.

const 

Open in new window

0
Hi All,

I use php to read data from stored procedure with MS SQL database.

The SP return several separate data. In .NET we can get it using dataset.

How to do it using PHP code?

Thank you.
0
Hi All,

I want to access google drive folder and its files from application, .NET or PHP.

How could I do it?

Thank you.
0
Microsoft Azure 2017
LVL 13
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Hello, I'm trying for the first time to submit an extension to the magento marketplace, but the technical submission has failed the installation and varnish test.  

From the composer.json file:

"type": "magento2-module",
    "version": "0.0.1",
    "require": {
      "php": "^7.0",
      "magento/framework": "~102.0.2"
    },
    "autoload": {
      "files": [ "registration.php" ],
      "psr-4": {
        "Vendor\\Extension\\": ""
      }
    }

Open in new window


Environment: PHP 7.0.31 Magento 2.2 CE:

Your requirements could not be resolved to an installable set of packages.

 
Problem 1
    - magento/framework 102.0.2 requires php ~7.1.3||~7.2.0 -> your PHP version (7.0.33) does not satisfy that requirement.
    - vendor/extension 1.0.4 requires magento/framework ~102.0.2 -> satisfiable by magento/framework[102.0.2].
    - Installation request for vendor/extension 1.0.4 -> satisfiable by vendor/extension[1.0.4].

Open in new window


Environment: PHP 7.1.22 Magento 2.2 CE

 
Problem 1
   - Can only install one of: magento/framework[102.0.2, 101.0.8].
    - Can only install one of: magento/framework[102.0.2, 101.0.8].
    - Can only install one of: magento/framework[101.0.8, 102.0.2].
    - vendor/extension 1.0.4 requires magento/framework ~102.0.2 -> satisfiable by magento/framework[102.0.2].
    - Installation request for vendor/extension 1.0.4 -> satisfiable by vendor/extension[1.0.4].
    - Installation request for magento/framework (locked at 101.0.8) -> satisfiable by magento/framework[101.0.8].

Open in new window


Environment: PHP 7.1.22 Magento 2.3 CE

Problem 1
    - Can only install one of: magento/framework[102.0.2, 102.0.1].
    - Can only install one of: magento/framework[102.0.2, 102.0.1].
    - Can only install one of: magento/framework[102.0.1, 102.0.2].
    - vendor/extension 1.0.4 requires magento/framework ~102.0.2 -> satisfiable by magento/framework[102.0.2].
    - Installation request for vendor/extension 1.0.4 -> satisfiable by vendor/extension[1.0.4].
    - Installation request for magento/framework (locked at 102.0.1) -> satisfiable by magento/framework[102.0.1].

Open in new window


Environment: PHP 7.2.10 Magento 2.3 CE

Problem 1
    - Can only install one of: magento/framework[102.0.2, 102.0.1].
    - Can only install one of: magento/framework[102.0.2, 102.0.1].
    - Can only install one of: magento/framework[102.0.1, 102.0.2].
    - vendor/extension 1.0.4 requires magento/framework ~102.0.2 -> satisfiable by magento/framework[102.0.2].
    - Installation request for vendor/extension 1.0.4 -> satisfiable by vendor/extension[1.0.4].
    - Installation request for magento/framework (locked at 102.0.1) -> satisfiable by magento/framework[102.0.1].

Open in new window

0
Hi Experts

Could you point what must to be corrected at this PHP code to make it correctly generates the needed JSON code?

Accordingly to:
<?
$prof_anterior = '';
						
while ($reg3 = $bd1->obtenerRegA())
{						
	//....
	
	// Checks if the id_profissional changed
	if( $reg3['id_profissional'] !== $prof_anterior )
	{

            // If changed mount completelly the object					
			$obj->professionals = array(
										array('name'=>$reg3['nome_completo'],
											  'nickname'=>'',
											  'roles'=>array($papel),
											  'internal_id'=>"CONS:".$conselho.'-'.$identificador_interno,
											  'cellphone'=>$reg3['celular_profissional'],
											  'tags'=>array("COOP:".$reg3['cooperativa'],
											  "FUNC:".$reg3['tipo_profissional'],
											  "TIPO_PAGAMENTO:".$tipo_pagamento,
											  "VALOR:R$".$reg3['valor_prof']),
											  "gender"=>$reg3['sexo_profissional'], 
											  "send_invite_when_submit"=>true,
											  'shifts' => $shifts)  // I guess at this point a for/ next must to be implemented to mount all the shift related to 'id_profissional', following the rule, but I don't know how to implement it..
										  );
		
			$schedules[] = $obj; //add each object to the array
	}
	else
	{		
			// Just add another object, not completelly the new array
			$shift_prof->shifts =  $shifts;	
			$schedules[] = $shift_prof; //add each object to the array
	}

    // Goes to the next id_profissional 
	$prof_anterior = 

Open in new window

0
Hi All,

I use laravel to show the screen format. See the attachment.

The problem is at the gadget. There is no scroll bar for filter part.
There is scroll bar for the chart part.

How to solve this problem?

Thank you.
GADGET-VIEW.jpeg
BROWSER-VIEW.PNG
0
Let's say I have a webpage with a photo gallery.
Now let's say that photo gallery has its image file names and locations stored in a database.
Now lets say that I want to run a query in PHP against that database using the gallery id to get the pictures which should show up.
Further suppose I have JS function which writes the elements to html to hold the images based upon the results of the query.

How do we take the php query results, cycle them and run the js to insert them in HTML?

JS function here. Writes the elements under the a div named Gallery wrap.

function thumbnailAdd(dname, elid) {
			var	pth = "http://somedomain.com/"+elid+"/"+dname;
			var tnpath = "http://somedomain.com/"+elid+"/tn/tn_"+dname;
				  $("#tgal").append(
				  '<div class="column">'+
			'<div class="inner">'+
					'<a class="zooming" href='+pth+' title='+dname+'>'+
					'<div class="img-wrap">'+
						'<img src='+tnpath+' alt="Image gallery" title='+dname+' class="mfp-fade>'+
					'</div>' +
					'</a>'+
			'<select class="form-control selectpicker" name="x" data-live-search="true" style="position:relative; top:1px;"><option>test</option></select>'+						
			'</div>'+			
		'</div>'
				  );
				}				

Open in new window


Here is the PHP which tries to get the dbase results and loop the JS function.
		$r = getGallery($elID);
			while ($rw = $r->fetch(PDO::FETCH_ASSOC)) { 
	echo '<script type="text/javascript"> call thumbnailAdd('.$rw["ARTIFACT_NAME"].', '.$elID.')</script>';
											}
		$r = NULL;

Open in new window


This does not work and I don't understand why. Thanks.
0
Hi Experts

Could you point what must to be corrected on this PHP code to consider correctly the array adition when assembling a JSON file?

The resumed code, the relevant part is assigned (lines 204 /  218)
<?
//...
	
try 
	{
	
		$periods = array();
		$professionals = array();
		$gerenciador='';	
		$dias_da_semana_excecao = array();

		  $query2 = "SELECT DISTINCT TOP 1 p.id_paciente, p.nome, e.endereco, TRY_CAST(e.numero as VARCHAR) as numero, e.complemento, e.bairro, e.cidade, e.uf, RTRIM(e.cep) as cep , g.gerenciador,";
		  $query2.= "  	CASE WHEN TRY_CAST(SUBSTRING (e.cep ,1 , 5 ) AS INT) BETWEEN 1000 AND  01599    THEN 'CE'";
		  $query2.= "  	...";
		  $query2.= "		 WHEN TRY_CAST(SUBSTRING (e.cep ,1 , 5 ) AS INT) BETWEEN 11000 AND 11249   THEN 'Santos'";  
		  $query2.= "		 WHEN TRY_CAST(SUBSTRING (e.cep ,1 , 5 ) AS INT) BETWEEN 20000 AND 23799   THEN 'Rio de Janeiro'";  
		  $query2.= "	 ELSE 'INDEFINIDO' END  AS regiao";
		  $query2.= " FROM XXXXX.dbo.pacientes p WITH(NOLOCK)";
		  $query2.= "		INNER JOIN  XXXXX.dbo.paciente_endereco pe WITH(NOLOCK) ON p.id_paciente = pe.id_paciente ";
		  $query2.= "		INNER JOIN  XXXXX.dbo.enderecos e WITH(NOLOCK) ON pe.id_endereco = e.id_endereco ";
		  $query2.= "		INNER JOIN  XXXXX.dbo.internacao i WITH(NOLOCK) ON p.id_paciente = i.id_paciente";
		  $query2.= "		INNER JOIN  XXXXX.dbo.contratos c  WITH(NOLOCK) ON i.id_contrato = c.id_contrato";
		  $query2.= "       INNER JOIN XXXXX.dbo.gerenciadores g WITH(NOLOCK) ON 

Open in new window

0
I am a newbie to MySQLi and am trying out some simple examples.

So I have this code:-

<?php
	require "conMushingDB.php";

	if (!isset($sqlDeleted)) {
  	      $sqlDeleted = '0 ';
    	}
	$arrAddressWHERE = array('Address_Id',2);


	$objAddress = $mysqli->prepare("SELECT * FROM address WHERE Deleted = ?" . $strSQLAND);
	$objAddress->bind_param("i", $arrAddressWHERE[1]);
	$objAddress->bind_param("i" . $arrAddressField[$arrAddressWHERE[0]], $sqlDeleted , $arrAddressWHERE[1]);
?>

Open in new window


This works fine. However I am trying to create the facility to be able to also run the select on the whale table without the AND, but I can't find a way of doing this as when I try and add the second comma conditionally it fails to work. I was hoping I could build a statement to bind where I could make the latter half and second variable type null such as:-

$strBind = "i" . $arrAddressField[$arrAddressWHERE[0]] . ", " .  $sqlDeleted  . $strComma . $arrAddressWHERE[1];
$objAddress->bind_param($strBind );

Open in new window


... but it doesn't work (I tried adding quotes round the variable type too using \" ) but to no avail. Any ideas anyone?
0
Hi Experts

Could you point a possible reason a PHP variable is not accepted by an array element?

Accordingly to:

print_r('-------------');
print_r($xxx);  // Has the correct value 
print_r('-------------');

$obj3->professionals = array(
			array('name'=>$xxx,
				  'nickname'=>'',
				  'roles'=>array($papel),
				  //'role'=>array('plantonista'),
				  'internal_id'=>"CONS:".$conselho.'-'.$identificador_interno,
				  'cellphone'=>$reg5['celular_profissional'],
				  'tags'=>array("COOP:".$reg3['cooperativa'],
				  "FUNC:".$reg5['tipo_profissional'],
				  "TIPO_PAGAMENTO:".$tipo_pagamento,
				  "VALOR:R$".$reg5['valor_prof']),
				  "gender"=>$reg5['sexo_profissional'], 
				  "send_invite_when_submit"=>true,
				  'shifts' => $shifts)
			  );						 

Open in new window


Amazingly $xxx has the correct value but it's not correctly accepted by the array element, another value enters in.

Thanks in advance.
0
Since changing system options on the server can cause serious issues if not done properly, I prefer to check with you before making changes.

Below is the AWS EC2 linux httpd.conf file as it is now.  

1. Is the .htaccess located within the httpd.conf file, or are the controls for the hidden .htaccess file contained within httpd.conf?

2. Which lines would I have to change in order to add ..
<Files *.php>
	Require all denied
	Require local
</Files>

Open in new window

.. and where would I add them?

3. I understand that I have to restart the instance. Since there is no 'restart' option in the management console, does this mean 'Start' the EC2 instance state, or 'Reboot' the running instance?

Thank you

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/html"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    

Open in new window

0
We are running php 7.3.1 via the platform installer on Microsoft Windows server 2016.  The site runs fine, and at random it starts returning 500 errors.  The only way to bring the site back is to restart the app pool.  This ends the php-cgi.exe processes and spans new ones.  The site has stayed up for anywhere from 12 hours to 52 hours.  We are not able to find anything in the windows event logs.  Microsoft support thinks that the php-cgi.exe is having an unhanded exception.  We are also not seeing any fatal errors in the php logs, only a few warning / notices.  Is there anything else we can turn on to capture the actual error, or have iis ignore the error and not lock up my entire site?
0
Build an E-Commerce Site with Angular 5
LVL 13
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Hi Experts,

I have a couple of questions, mainly intro to web programming.

1-      What is the purpose of those 4 file types?
  a.      JavaScript
  b.      PHP
  c.      CSS
  d.      HTM/L.

2-      When opening a datapage, do I always call it thru a PHP file?

3-      How does the browser knows to link my website URL to the files hosted at my server?

4-      I was given Access to production server thru FTP/SSH, is that enough to get all my work done?

5-    What is the best (easiest) way you recommend to learn these kind of stuff...(Coming from Access/VBA/SQL programming)?

Thanks
0
Using MCRYPT is hindering my move to PHP 7.3. Currently mcrypt works fine for encryption and decryption; however, OpenSSL cannot decrypt my MCRYPT’ed data. So it appears that I need to run some kind of script that will get the 3 post_meta fileds from each post, decrypt them using mcrypt, then re-encrypt them with OpenSSL. Further “day-forward encryption will be done using OpenSSL.

I’ve attempted many options for decrypting the MCRYPT’ed data with OpenSSL and they have all returned NULL.
So I’m giving up on that direction.

I think an ETL like script would work to run through the posts (they are (CPT) Custom Post Types called formlead), see if they have encrypted data in the 3 fields (to which most of them will) , then decrypt each field using current MCRYPT method into new vars, then re-encrypt into new OpenSSL method, then write this back to database with the same postID. Then the new decryption method could read the data when needed in the future.

However, I’m not the greatest WordPress PHP coder. Can someone help with the script please? I could load this as a page and specify date range to make sure I’m not overloading the server. There’s about150k posts with 8 million + postmeta rows.

I would be doing this against a local copy of the DB and not production to test. Then I would snapshot the production DB and run against it after hours.

Mock code:
<?php

vars = manually set date range

get posts within date range

while have_posts

get 

Open in new window

1
How do I display my registered user posts from the database using an inner join?

The users table has an id column that in an auto-increment table   - a progressive number each time a person is registered as a user.

The "notices" table has an upload_id incremental column for each notice posted and a "users_id column that holds the id number that corresponds to the registered user.

if (array_key_exists("id",$_POST)) $id = mysqli_real_escape_string($db,$_POST['id']);

$q = "SELECT notices.users_id, notices.description, notices.amount, notices.currency, notices.location, users.email FROM notices INNER JOIN users ON notices.users_id = id WHERE notices.upload_id=$id" ;
    
$r = mysqli_query ($db, $q);

//if (mysqli_num_rows($r) > 0) {

if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.

	// Get the user's information:
	$row = mysqli_fetch_array ($r, MYSQLI_NUM);
}

// Create the form:
echo '<form action="ContactPoster.php" method="post">

<p>Description: ' . $row[5] . '</p>

<p>Amount: ' . $row[6] . '</p>

<p>Currency: ' . $row[7] . '</p>

<p>Location: ' . $row[8] . '</p>

<input type="hidden" name="toemail" value="'.$row[9].' " >';

?>

 
    <p><strong>Your Name:</strong></p> <p><input type="text" name="name" size="30" maxlength="60" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>" /></p>
	
    <p><strong>Your Email Address:</strong> </p> <p><input type="text" name="email" size="30" maxlength="80" value="<?php if 

Open in new window

0
Moving custom wordpress theme from PHP 5.6 to 7.3 to which MCRYPT is no longer supported. However, I have encrypted data that I will still need access to.

How can I move “day forward” with new OpenSSL Encrypt/Decrypt and still decrypt older MCRYPT’ed data?

I will show Current encryption functions as well as new attempts to migrate.
P.S. I did not write the old MCRYPT code, so I don’t know exactly why it written the way it was.

Current Encrypt:
function crypt_ecrypt($key, $algo = MCRYPT_BLOWFISH, $data){
    $key = substr($key, 0, mcrypt_get_key_size($algo, MCRYPT_MODE_ECB));
    $algo = $algo;

    if(!$data){
	return '';
    }
    
    //Optional Part, only necessary if you use other encryption mode than ECB
    $iv_size = mcrypt_get_iv_size($algo, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    
    $crypt = mcrypt_encrypt($algo, $key, $data, MCRYPT_MODE_ECB, $iv);
    return trim(base64_encode($crypt));
}

Open in new window


Current Decrypt
function crypt_decrypt($key, $algo = MCRYPT_BLOWFISH, $data){

    $key = substr($key, 0, mcrypt_get_key_size($algo, MCRYPT_MODE_ECB));
    $algo = $algo;
    if(!$data){
	return '';
    }

    $crypt = base64_decode($data);

    //Optional Part, only necessary if you use other encryption mode than ECB
    $iv_size = mcrypt_get_iv_size($algo, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    $decrypt = mcrypt_decrypt($algo, $key, $crypt, MCRYPT_MODE_ECB, $iv);
    return trim($decrypt);

}

Open in new window


NEW Encrypt: (Sample for Encrypting cookies day-forward)
$method = 'AES-256-CBC';  <— Method passed in
function crypt_cookies_encrypt($key, $method, $data){

    $ivSize = openssl_cipher_iv_length($method);
    $iv = openssl_random_pseudo_bytes($ivSize);

    $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);

    // For storage/transmission, we simply concatenate the IV and cipher text
    $encrypted = base64_encode($iv . $encrypted);

    return $encrypted;
}

Open in new window


NEW Decrypt Attempt for MCRYPT’ed data only using OpenSSL: This isn’t meant to decrypt NEW encrypted data. However, I would like to have both NEW and OLD decrypted in the same function, even if it means changing the way the NEW data is encrypted.
And to be clear, the code below does not appear to work with decrypting the MCRYPT’ed data, it’s still gibberish.

$method = 'bf-ecb';  <— Method passed in
function crypt_decrypt($key, $method, $data){

    if(!$data){
        return '';
    }
    $decrypt = openssl_decrypt($data, $method, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);  //This is what I found that should decrypt MCRYPT data with OpenSSL, but I’m probably doing it wrong by not including the $iv stuff.

    return $decrypt;

}

Open in new window


NEW Decrypt: (Sample for Decrypting cookies day-forward)
$method = 'AES-256-CBC';  <— Method passed in
function crypt_cookies_decrypt($key, $method, $data){

    $data = base64_decode($data);
    $ivSize = openssl_cipher_iv_length($method);
    $iv = substr($data, 0, $ivSize);
    $data = openssl_decrypt(substr($data, $ivSize), $method, $key, OPENSSL_RAW_DATA, $iv);

    return $data;
}

Open in new window

0
Hi:
I use AWS linux and PHP 7.0.27
I want to make access to my scripts more secure to prevent a hacker from adding to the URL to get access to a script directly. I read that putting scripts into a private, 'inaccessible from the browser' directory, then no access using the browser would be possible. Access would only be by PHP.

The directory structure ..

/var/www/html/index.php (public)      root:root

/var/www/private/script1.php (private)            root:apache

If I code an include script in index.php and place the include script in private, the include script is accessed as expected.

However, when I want to access a non-include script (script1.php) from index.php with ..

$url = "./private/script1.php";
ob_end_clean();
header("Location: $url");
exit();

the browser throws the error ..
'The requested URL /private/script1.php was not found on this server.'

I guess this is because index.php is in the public directory for access to/from the browser, and script1.php is in the disallowed private directory,

In this scenario, how can I code PHP to make index.php redirect to script1.php?
0
I am testing out a user registration form for any potential problems. IF my user gets to the registration page and just hits "Register" without putting anything in the form fields, they are only getting warnings on three of the fields. There should be an error message for ALL the fields when the form is validated..

Also the first two come up on the left hand side and one is centered. I would like them all to be the same.

// Check for a first name:
	if (preg_match('/^[A-Z \'.-]{2,20}$/i', $trimmed['first_name'])) {
		$fn = mysqli_real_escape_string($db, $trimmed['first_name']);
	} else {
		echo '<p class="error">Please enter your first name or N/A!</p>';
	}
	
// Check for a middle name:
	if (preg_match ('/^[A-Z \'.-]{1,20}$/i', $trimmed['mid_initial'])) {
		$mi = mysqli_real_escape_string ($db, $trimmed['mid_initial']); 
	} else {
		echo '<p class="error")Please enter your middle name or initial or NA!</p>';
	}
	
// Check for a last name:
	if (preg_match('/^[A-Z \'.-]{2,40}$/i', $trimmed['last_name'])) {
		$ln = mysqli_real_escape_string($db, $trimmed['last_name']);
	} else {
		echo '<p class="error">Please enter your last name or N/A!</p>';
	}
	
// Check for a username:
	if (preg_match ('/^[A-Z0-9 \'.-]{2,30}$/i', $trimmed['username'])) {
		$u = mysqli_real_escape_string ($db, $trimmed['username']);
	} else {
		echo '<div align="center"><p class="error")Please enter a desired username!</p></div>';
	}

// Check for an email address:
	if 

Open in new window

0

PHP

120K

Solutions

33K

Contributors

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.